Sapui5 Odata Model example

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. This article explains SAPUI5 Odata Model, demonstrates how to use Northwind Odata service with SAP WebIDE.

1.What is Odata
2.Northwind OData service
3.SAPUI5 Odata model
4. How to instantiate SAPUI5 OData Model
5.How to consume OData service in SAPUI5
6. SAPUI5 ODdata model read function
7. SAPUI5 Data Binding between OData model and SAPUI5 control
8. SAPUI5 Northwind OData example: How to consume Northwind OData service in SAP Web IDE
9. Configure Northwind Odata service in SAP WebIDE
10 Instantiation of Odata model in SAPUI5 application
11.Conclusion

What is OData?

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

Northwind Odata service

Northwind is publicly available OData service. You can use this freely available OData service to learn how to use and consume Odata service in SAPUI5 applications with SAP WebIDE.

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. Northwind Odata contians 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

SAPUI5 OData Model

SAPUI5 supports OData model. OData is a server side model. The data resides at the server and a request is made by client to retrieve data from the server. This is Odata model read scenario. OData model holds the data retrieved from server and can be bind to SAPUI5 controls to display data.

Check the definition of OData model from SAP website.

OData Model definition
OData Model definition

How to instantiate SAPUI5 OData Model in SAP Web IDE

When instantiating an Odata Model, we need to pass OData service URL to the service URL parameter. Service Url is a mandatory parameter when instantiating an Odata model.

Notice that in WebIDE, when instantiating an Odata model, a relative URL is passed and not absolute url.

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, an odata service 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);
	});

How to consume OData service in SAPUI5

After instantiating an Odata model, the next step would be to consume it in SAPUI5 application. OData model can be consumed in SAPUI5 either through binding or through give API functions. create( ), read( ), update( ) and remove( ) functions are available to perform the CRUD operations.

SAPUI5 ODdata model read function

read( ) function will trigger a GET request to the OData service. A sample code is shown below.

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 Data Binding between OData model and SAPUI5 control

If a data binding is in place between control and Odata model, 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.

  1. Right click Workspace and select New->Project from Template to open wizard to create SAPUI5 application.
  2. In the Template Selection, select SAPUI5 Application and click Next.
  3. Fill in Project Name: znorthwindodata and Namespace: Amarmn. Let View Type be XML and View Name: View1. Click Finish.

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

Data connection Northwind Odata service to SAPUI5 project in SAP WebIDE

These steps establishes data connection between Northwind Odata service and SAPUI5 application in SAP WebIDE. It will do all necessary configuration in SAPUI5 application to make Odata service ready to consume.

  1. Right click your sapui5 project
  2. select New -> OData Service.
  3. In wizard, select Service URL, and select Northwind from dropdown.

    (Note: If you did not find Northwind service in drop down, it indicates that you do not have Northwind configured as destination in Hana cloud platform. Do not worry. Check the below section to configure Northwind destination in SAP WebIDE quickly ).
  4. In relative URL provide V2/Northwind/Northwind.svc/
  5. click Test. It returns you all the entity sets of Northwind Odata service.
  6. Select Products and click Next at the bottom.
  7. In the Model Selection screen, for Application Model select Use default model and click Next. In the Confirmation screen click Finish.
  8. This completes instantiation of Odata model using Northwind Odata service.
SAPUI5 OData model: How to consume Northwind OData service in SAPUI5 Application
SAPUI5 OData model: How to consume Northwind OData service in SAPUI5 Application

Configure Northwind Odata service in SAP WebIDE- Optional

Step 1 :Click on create new data source

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

Step 2: Enter hana account username and password, do not give ‘trial’ suffix for user name
Proxy type – Internet
URL – https://services.odata.org/
Authenticaion – No Autentication

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

Step 3- Enter relative URL – /V2/Northwind/Northwind.svc/
and click test.
Northwind service starts appearing.

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

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

This completes instantiation of Odata model using Northwind Odata service.

Instantiation of Odata model in SAPUI5 application

The above step takes care of Instantiation of Odata model in SAPUI5 applicaiton. 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);
}

Code View1.xml.view

In this example we attempt to read a single Product via the Northwind OData service. Binding is done at the page level. The below example also shows that just like JSON model, expression binding is possible with OData models as well.

<mvc:View controllerName="Amarmn.znorthwindodata.controller.View1" 
xmlns:mvc="sap.ui.core.mvc" 
displayBlock="true" 
xmlns="sap.m"
xmlns:core="sap.ui.core" 
xmlns:f="sap.ui.layout.form">
<Shell id="shell">
<App id="app">
<pages>
<Page title="Product {ProductID}Info" binding="{/Products(1)}">
<content>
<ObjectHeader title="{ProductName}"
	number="{ parts: [{path:'UnitPrice'},'EUR'], 
        type: 'sap.ui.model.type.Currency', 
        formatOptions: {showMeasure:false} }" 
        numberUnit="EUR">
<attributes>
<ObjectAttribute text="Units instock:{UnitsInStock}"/>
<ObjectAttribute text="Units onorder:{UnitsOnOrder}"/>
<ObjectAttribute text="Reorder Level:{ReorderLevel}"/>
<ObjectAttribute text="Quantity perUnit: {QuantityPerUnit}"/>
</attributes>
<statuses>
<ObjectStatus text="ID:{ProductID}"/>
<ObjectStatus text="{= ${Discontinued} ? 'Discontinued':'Available'}" 
state="{= ${Discontinued}?'Error':'Success'}"/>
</statuses>
</ObjectHeader>
</content>
</Page>
</pages>
</App>
</Shell>
</mvc:View>

Run the application to see the result.

sapui5 northwind odata service example

We are aware that Northwind OData service provides navigation between the Product and the Supplier and the Category. We extend the above code to fetch the Supplier and Category data for the Product. We will display these data inside IconTab. Understand that no extra binding is required at the Page level. Add the below piece of code just after the closing of ObjectHeader tag. Notice that we have made Element binding between the SimpleForm and the Category or Supplier.

<IconTabBar expanded="true" class="sapUiResponsiveContentPadding">
<items>
<IconTabFilter icon="sap-icon://activity-items">
<f:SimpleForm binding="{Category}">
   <core:Title text="Category Information"/>
   <Label text="CategoryID"/>
   <Text text="{CategoryID}"/>
   <Label text="CategoryName"/>
   <Text text="{CategoryName}"/>
   <Label text="CategoryDescription"/>
   <Text text="{Description}"/>
</f:SimpleForm>
</IconTabFilter>
<IconTabFilter icon="sap-icon://supplier">
<f:SimpleForm binding="{Supplier}">
   <core:Title text="Supplier Information"/>
   <Label text="SupplierID"/>
   <Text text="{SupplierID}"/>
   <Label text="CompanyName"/>
   <Text text="{CompanyName}"/>
   <Label text="Address"/>
   <Text text="{Address}"/>
   <Label text="City"/>
   <Text text="{City}"/>
   <Label text="PostalCode"/>
   <Text text="{PostalCode}"/>
   <Label text="Country"/>
   <Text text="{Country}"/>
   <core:Title text="ContactInformation"/>
   <Label text="ContactName"/>
   <Text text="{ContactName}"/>
   <Label text="ContactTitle"/>
   <Text text="{ContactTitle}"/>
</f:SimpleForm>
</IconTabFilter>
</items>
</IconTabBar>

Run the application to see the below output.

sapui5 northwind odata service example

Conclusion

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. We also learn how to configure Northwind Odata service in SAP WebIDE. We learnt how to do binding between Odata model and SAPUI5 control. We also made use of navigation property between the Product and Supplier and Product and Category.

SAPUI5 Tutorials