SAPUI5 OData model: How to consume Northwind OData service in SAPUI5 Application

Knowing odata and understanding how to use it within SAPUI5 applications is of utmost importance to any SAPUI5 developer.

I came across OData during my journey of learning SAPUI5. Prior to that I had no information about OData mostly because I was not working with web applications earlier. I found that without an expertise on how to call and consume OData service inside SAPUI5 applictions its hard to truly call ourselves an SAPUI5 developer.

My aim in this post is to build a SAPUI5 CRUD application connected to a backend OData service.

We will cover the basics of odata such as entity types, associations and navigation properties. This knowledge will prove beneficial when you will be actually consuming OData service in Sapui5 application.

Definition of OData

OData was developed by Microsoft in 2007 and later they made it open source. Its an open data protocol that defines a set of best practices for building and consuming RESTful APIs.

In one of my previous post I explained how to connect Northwind OData service to SAP WebIDE. Northwind is publicity available OData service and hence we will discuss the same so anyone can benefit from it.

Before you actually consume an OData service in a SAPUI5 application, you should explore the service and understand its entity as well as relation between the entities. A tool publicly available to explore OData service is XOData. The tool displays the entity data model. You come to know the entities available along with their properties, keys and associations and navigation properties between them.

Screenshot from XOData tool for Northwind Odata V2
Screenshot from XOData tool for Northwind Odata V2

In the screenshot I have just captured three entities Product, Supplier and Category, but Northwind has many other entities. You can clearly see the properties of Product set as well as the association that it holds with Supplier and Category ( displayed as blue color in above pic).

Good, we understand the EDM of Northwind Odata.

A simple search on Google will give us the Northwind OData service. Click on the Nothwind OData – OData Test Service and you will see the Northwind service document.

sapui5 odata example with northwind odata service service document
sapui5 odata example with northwind odata service service document

$metadata will provide further information like properties of an entity and navigation between entity sets. Check the definition of $metatdata by odata.org.

OData metadata definition
OData metadata definition

Below link fetches the metadata of Northwind OData.

https://services.odata.org/V3/Northwind/Northwind.svc/$metadata

The below image shows the metadata of Northwind. See that there are so many entity types. For Product you can see properties and the navigation property. Also, I have highlighted the Association Name.

Northwind OData metadata document

Northwind OData metadata document

This much information is enough to start working on SAPUI5 CRUD example.

SAPUI5 OData Model

We will use OData model as it is the server-side model, to collect the data from the OData service. Below image describes OData Model and is screen shot from SAP website.

OData Model definition
OData Model definition

How to instantiate SAPUI5 OData Model in SAP Web IDE

You will need the OData service URL to instantiate an OData Model. Remember not to give absolute URL, as WebIDE supports relative URL. Before you proceed further ensure that Northwind odata service is configured in destination of SAP Cloud platform. You can follow sapui5 development environment setup, if you have not yet configured Northwind in Cloud platform destination.

var sServiceURL 
     = "/V2/Northwind/Northwind.svc/";

var oModel = new sap.ui.model.odata.v2.ODataModel({
	serviceURL: sServiceURL
	});
sap.ui.getCore().setModel(oModel);

As soon as the OData model is instantiated using the service URL, a call is triggered to the backend to request service metadata. The service metadata gets loaded asynchronously.

OData model has events to check if metadata has loaded successfully or failed.

metadataLoaded is fired when the metadata document has loaded successfully. metadataFailed is fired when metadata document did not load successfully. You can attach event handler functions to handle these events.

oModel.attachMetadataLoaded(function () {
	var oMetaData = oModel.getServiceMetadata();
	console.log(oMetaData);
	});

SAPUI5 OData Model read create update remove functions

SAPUI5 OData model has ready-made functions available to perform CRUD operations.

SAPUI5 ODdata model using read function

read function will trigger a GET request to the OData service.

function fnSuccess(oData, oResponse) {
// accessing the data from the model now
var oProduct1 = oModel.getData("/Products(1)");
var oProduct1Name = oModel.getProperty("/Products(1)/ProductName");
}
	
function fnError(oError) {
console.log("Error", oError);
}

oModel.read("/Products(1)", 
{
        success: fnSuccess, 
	error: fnError
});

On a successful call to the service, the data is returned to oData parameter of the success handler function. oResponse holds further information, like the status.In case of an error, an error object is returned, whose details are available in parameter oError of error handler function.

Once you have the data, its easy to access the data using methods getData or getProperty.

SAPUI5 trigger OData call via Data Binding

If a data binding is in place between control and Odata service, request to fetch the data from OData service is triggered automatically.

If we wish to fetch a single product, a binding like below will work. Here we bind a product data to an entire page applying element binding.

<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m">
<Page
	title="Page has binding with a single product"
	binding="{/Products(1)}">
	<content>
		<Text 
			text="Product name: {ProductName}"
			class="sapUiMediumMargin">
		</Text>
	</content>
</Page>
</mvc:View>

SAPUI5 Northwind OData example: How to consume Northwind OData service in SAP Web IDE

We will create an SAPUI5 application to consume Northwind OData service in SAP Web IDE. This will strengthen our understanding of consuming odata service in SAPUI5 application.

Right click Workspace and select New->Project from Template to open wizard to create SAPUI5 application. In the Template Selection, select SAPUI5 Application and click Next.

Fill in Project Name: znorthwindodata and Namespace: Amarmn. Let View Type be XML and View Name: View1. Click Finish.

Attach Northwind OData service to SAPUI5 Application

Right click znorthwindodata project, select New -> OData Service. In wizard, click Service URL, and select Northwind from dropdown. In relative URL provide V2/Northwind/Northwind.svc/ and click Test. It returns you all the entity sets of Northwind Odata service. Select Products and click Next at the bottom.

attach northwind odata service to sapui5 application in sap webide
attach northwind odata service to sapui5 application in sap webide

In the Model Selection screen, for Application Model select Use default model and click Next. In the Confirmation screen click Finish.

Web IDE writes all the useful code for you. In manifest.json file, in “sap.app” section it creates a “dataSources” section for Northwind.

"sap.app": {
...
"dataSources": {
	"Northwind.svc": {
		"uri": "/Northwind/V2/Northwind/Northwind.svc/",
		"type": "OData",
		"settings": {
			"localUri": "localService/metadata.xml"
		}
	}
}
},

Next, under “models” section it makes Northwind Odata model as the default model. Empty namespace indicates that it is the default model.

"models": {
"i18n": {
	"type": "sap.ui.model.resource.ResourceModel",
	"settings": {
	"bundleName": "Amarmn.znorthwindodata.i18n.i18n"
	}
},
"": {
	"type": "sap.ui.model.odata.v2.ODataModel",
	"settings": {
		"defaultOperationMode": "Server",
		"defaultBindingMode": "OneWay",
		"defaultCountMode": "Request"
		},
		"dataSource": "Northwind.svc",
		"preload": true
	}
}

A new file serviceBinding.js is created which holds the code for instantiating OData model.

function initModel() {
	var sUrl = "/Northwind/V2/Northwind/Northwind.svc/";
	var oModel = new sap.ui.model.odata.ODataModel(sUrl, true);
	sap.ui.getCore().setModel(oModel);
}

Your project folder structure should look similar to below.

sapui5 application using northwind odata service in sap webide
sapui5 application using northwind odata service in sap webide

In the View.xml place the List control to display the Products.

<mvc:View 
controllerName="Amarmn.znorthwindodata.controller.View1" 
xmlns:mvc="sap.ui.core.mvc" 
displayBlock="true" 
xmlns="sap.m">
<Shell id="shell">
<App id="app">
<pages>
<Page id="page" title="{i18n>title}">
<content>
<List 
	id="productList" 
	class="sapUiResponsiveMargin" 
	width="auto" 
	items="{/Products}">
	<headerToolbar>
	<Toolbar>
	<Title 
	text="Northwind Odata service Products"/>
	</Toolbar>
        </headerToolbar>
	<items>
		<ObjectListItem 
		title="{UnitsInStock} x {ProductName}"
		number="{ parts: [{path:'UnitPrice'},'EUR'], 
	        type: 'sap.ui.model.type.Currency', 
		formatOptions: {showMeasure: false} }" 
		numberUnit="EUR">
		</ObjectListItem>
	</items>
</List>
</content>
</Page>
</pages>
</App>
</Shell>
</mvc:View>

Run the application to see the result.

sapui5 application using northwind odata service in sap webide example
sapui5 application using northwind odata service in sap webide example

This article explains in detail how to create a sapui5 application and consume an OData service inside it. It also explains OData model and its instantiation.

In the next article we discuss about Create, Update and Delete operations using Odata model.

SAPUI5 Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *