0% found this document useful (0 votes)
3 views83 pages

Skip To Content

The document discusses the architecture and functionality of OData services in SAP ABAP, detailing the types of OData services and their integration with SAP UI5 and Fiori applications. It outlines the process for creating OData services using the SEGW transaction, including defining data models, service implementations, and runtime artifacts. Additionally, it covers CRUD operations, testing OData services, and the use of BAPI/RFC for data handling, emphasizing the flexibility and reusability of OData services across different front-end applications.

Uploaded by

aaamir khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views83 pages

Skip To Content

The document discusses the architecture and functionality of OData services in SAP ABAP, detailing the types of OData services and their integration with SAP UI5 and Fiori applications. It outlines the process for creating OData services using the SEGW transaction, including defining data models, service implementations, and runtime artifacts. Additionally, it covers CRUD operations, testing OData services, and the use of BAPI/RFC for data handling, emphasizing the flexibility and reusability of OData services across different front-end applications.

Uploaded by

aaamir khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Skip to content

o LinkedIn
Insights of SAP ABAP

Swathi Abhishek Akkannavar

SAP
Odata in ABAP
Published by
Poorvi Rao
on
April 4, 2024

ABAP and Fiori Architectural behavior


Difference between SAP ABAP apps and SAP UI5/FIORI apps
Architecture
ODATA Services : main purpose is to implement “DATABASE
functionality”

ODATA Services are of 3 types

1 a) OData ABAP Service -> performs Database operations with SAP ECC/CRM/SRM/SCM
2
3 b) Odata HANA service -> performs Database operations with SAP HANA
4
5 c) odata External Service->performs Database operations with non-SAP
SAP UI5 : is a framework used for developing Custom Front-end
apps with website features
and these SAP Ui5 Apps can consume/access all types of ODATA
Services
to deal with Database functionality

SAP FIORI: is a package with collection of standard front-end apps


for “common business activities”

approve/reject Purchase order —–> SAP FIORI app -> internally


developed using UI5 + ODATA

approve/reject Timesheet —–> SAP FIORI app -> internally


developed using UI5 + ODATA

approve/reject Leave REquest —–> SAP FIORI app -> internally


developed using UI5 + ODATA

check price & availability —–> SAP FIORI app -> internally
developed using UI5 + ODATA

create sales order —–> SAP FIORI app -> internally developed using
UI5 + ODATA

change sales order —–> SAP FIORI app -> internally developed
using UI5 + ODATA

Tracking sales Order —–> SAP FIORI App -> internally developed
using UI5 + ODATA

Tracking Purchase Order —–> SAP FIORI APP -> internally developed
using UI5 + ODATA

There are more than 500 standard FIORI apps ( developed internally
using SAP Ui5 + ODATA )

Note : As developer, we can develop custom Front-end Apps , we


can enhance standard Front-end Apps , we can develop OData
services

SAP UI5 custom Front-end apps can consume all types of OData
services
SAP FIORI standard front-end app can consume all types of Odata
Services
because SAP FIORI is internally based on SAP UI5

OData ABAP service are mainly executed under SAP Netweaver


Gateway Component
with Database operation ( SELECT, INSERT , DELETE , UPDATE )

SAP Netweaver Gateway support two formats mainly


a) XML FORMAT

b) JSON FORMAT

Example for XML and JSON Format


Advantage of OData Services

1. OData Services are independent of Front-end app’s


i,e ODATA Services can be accessed in various front-end app’s
like SAP Ui5 , SAP FIORI, .NET , PHP ,etc…
2. OData Services can be “re-usable”
ODATA ABAP services will be developed under SEGW Tcode

SEGW -> SAP Netweaver Gateway Service Builder tool

ODATA ABAP service Project

Every Odata ABAP service Project contains mainly


1) Data Model
2) Service Implementation
3) Runtime Artifacts
4) Service Maintainence

Data Model

Entity Type : is an option to maintain collection of fields with data


Type and length
Entity Type is similar to STRUCTURE in NORMAL ABAP

Entity : is an option to hold single record at a time


ENTITY is similar to WORKAREA in Normal ABAP

Entity Set : is an option to hold collection of records


ENTITYSET is similar to INTERNAL TABLE in NOrmal ABAP

Association : is the relationship between two Entity Types

Association Set : is the relationship between Two Entity Sets

Note : under Single Odata Project, we can create any Number of


Entity Types, ENTITYSETs

Service Implementation : mainly contains “CRUD Methods”


SAP UI5/FIORI ODATA Service

Create ——-> Create_ENTITY( ) method -> C -> INSERT statement

bindElement ——–> GET_ENTITY( ) method -> R -> SELECT Query


( 0/1 )

bindRows/bindItems—-> GET_ENTITYSET( ) method -> R -> SELECT


QUERY ( 0/1/N )

update ——> UPDATE_ENTITY( ) method -> U -> UPDATE statement

remove ——-> DELETE_ENTITY( ) method -> D -> DELETE statement

Note : The above methods are technically known as “CRUD


methods”

RUNTIME Artifacts :

Runtime Artifacts mainly contains Runtime Classes ( which are


autogenerated )

_MPC -> Model Provider Class ( * )

_MPC_EXT -> Model Provider Extension Class

_DPC -> Data Provider Class

_DPC_EXT -> Data PRovider Extension Class ( * )

_SRV -> REGISTERED SERVICE

_MDL -> REGISTERED MODEL

Service Maintenance

Error log -> to trace/find out errors occured during service execution
Gateway Client -> temporary screen to test OData Service
functionality

Register -> To register odata service under SAP NW Gateway

Methods in ODATA

1. Update_stream( ) method : it is used to upload file content


from front end app (SAP Ui5 fiori)

this method contains

1. it_key_Tab : will capture input file name from frontend app


(SAP UI5/Fiori)
2. is_media_resource : will capture input file content , file type
from front end app (SAP UI5/FIORi) .
Get_stream( ) method : it is a method used to download file content.
and this method contains the following parameters

it_key_tab : will capture input file name from front end app (SAP
UI5/FIORI)

er_stream : Will send ouput file content file type to front end app
(SAP UI5/FIORI)

Execute_action ( ) method : it is mainly used for ‘Funtion import’


concept in odata service

it contains three parameters

iv_Action_name : will capture name of funtion triggered in front end

it_parameter : will capture input values from front end app.

er_data : will send output data to frontend application


Simple example for
creating Odata in SEGW
for Sales data [ VBAK –
VBAP ]

Step 1. Go to transaction code – SEGW .

Click on Icon Create. A pop window will appear , Fill the details as
per below mention in screen shot and click on check icon or enter.
Below screen will appear where you can see below folder in project.
In Folder data model, we can see three sub folders. Entity Type – it
acts as work area , Entity Sets -It act as internal table and
associations.
Now we are going to define structure of work area and internal table
, Right click on Data model select import and select DDIC structure .

Here give the details of structure and structure name as per below
screen below.

Select radio button Entity type and and click on check box entity set.
fill ABAP structure as VBAK and click on next
Now you will get the pop up screen with VBAK table fields name.
Select fields for your structure and click on next.
project5
Other window will appear where we have to select the key field. tick
on Vbeln as key field and click on finish. You may get warning
message , it can be totally ignored.
Now expand folder entity type and fill the below parameters in
properties , Please don’t tick Null check box for VBELN as it is key
field.

Similarly Create Structure for SD Item following same steps


click on Save button at the top of menu bar

Now click on generate Icon, A pop up window will appear with class
details , click on tick icon and proceed further. It will ask for package
, give details and proceed further . These are also knowns as
runtime artifacts.
Step 2. Go to transaction code /IWFND/MAINT_SERVICE .

Click on push button Add services .


Next screen will appear, give the alias name and execute , Search
you for your project .

Now double click on your project name . A pop up window will


appear , enter the package details and click on tick icon. An
Information message will be shown where it will confirm about the
service is created and metadata loaded successfully
Now click back and go to main screen of transaction
/IWFND/MAINT_SERVICE and find your service.

Click on SAP Gateway Client


A new screen will come, Execute the transaction and check the
response .
Now we will write code to get data.

Step 3. Go to transaction code SEGW and expand folder service


Implementation .

Under service implementation – Expand SDheaderSet. you will find


different options. Right click on GetEntitySet and select GO to ABAP
work Bench . It will redirect to the class
Now expand the method drop down and select method for
GetEntitySet for Header data and right click and select redefine.

Write below code in method. Save and activate all related objects
for classes.
Similarly , Write code for GetEntitySet for Item and activate .
Similarly add code for GetEntity for VBAK as shown below

Step -4

Go to transaction /IWFND/MAINT_SERVICE and find out you service ,


select your service and click on load metadata.
Information message will pop up – Metadata has been loaded
successfully.

Now Click on SAP Gateway Client .

Now Click on Entity set.

Select entity for header and enter


Click and execute and you will get the header data in response

Similarly, Select entity set for item and execute . You will get data
for item
Here , We had completed our Odata service creation with a Service
Builder Project with two entities and two entity-sets. We have
generated the runtime artifacts and registered and activated our
OData service. We had redefined methods of header and item entity
set , load metadata and test the entity set with for test data.

Developing OData ABAP


service with BAPI/RFC

Note : we can develop odata service in two ways

1 1) using BAPI/RFC
2 2) without using BAPI/RFC

Let us consider : OData ABAP service using BAPI/RFC

Procedure :
Step1 : In SE37 Transaction Code ,
analyze the input parameters of BAPI : for ex : Airline
analyze the output parameters of BAPI : for ex : Flight_List
analyze the behavior of BAPI

1 for ex : BAPI_FLIGHT_GETLIST

Step2 : open SEGW Transaction Code , click on Create icon,


Provide Project name = ZFLIGHT_LIST
description = Odata Project with BAPI
save in package/local

Step3 : create Entity Type and Entity Set by importing fields


from ABAP structure = BAPISFLDAT
i,e
Right click Data Model -> import -> DDIC structure
provide Entity Type name = Flight
provide ABAP structure = BAPISFLDAT
select checkbox to create EntitySet ( FlightSet )
click on next -> select the fields -> next
select atleast one field as Key Field ( For ex : Airlineid )
continue
save
step4 : Maintain Mapping between OData Service and BAPI
i,e
Expand Service implementation Folder
expand FlightSet ( EntitySet )
right click on GETENTITYSET option
select “MAP to DATASOURCE” option

provide Data Source Type = Remote Function Call


provide Data Source Name = BAPI_FLIGHT_GETLIST
click on continue
 At odata level, click on add button , select Airlineid

 Drag drop Airline from BAPI to OData Service Airlineid Field ->
INPUT MApping

 Drag drop Fields from BAPI ( FLIGHTLIST ) to ODATA SERVICE


Fields -> Output Mapping

 save
step5 : Generate Runtime Artifacts
i,e just click on red color icon and continue -> save in package/local
step6 : Register the service under SAP NW Gateway
i,e open Service Maintenance -> click on “Register” option ->
continue
save it in package/local
continue
Maintenance : In the below screen, by using “Add Service”, you can
add the service, if not added with previous step.
step7 : Test OData Service
i,e
open Gateway Client
select Entity Set ( FlightSet )
and select GET operation and execute the service
To fetch all records

1 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet
To fetch records based on Input

1 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?$filter=Airlineid eq 'DL'
2
3 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?$filter=Airlineid eq 'AA'
4
5 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?$filter=Airlineid eq 'SQ'

To fetch records with json format

/sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?
$filter=Airlineid eq ‘AA’&$format=json

To fetch records with xml format

/sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?
$filter=Airlineid eq ‘AA’&$format=xml
To fetch records count

/sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet/$count

We can verify the data by cross verifying the data by executing BAPI
Standalone
To fetch records with specific fields

/sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet?
$select=Airlineid,Airline,Price

Note : If we use BAPI/RFC under OData Service ,


Then there are two techniques
a) with MAPPING
b) without Mapping

Note : Mapping is used for defining data transfer between ODATA


and BAPI
for sending and receiving data between ODATA and BAPI

Note : when generate runtime Artifacts ,


According to Input and output mapping between ODATA and BAPI
the code is also autogenerated internally under DPC Class
GETENTITYSET method
Note : if we use mapping technique between OData And BAPI
Then as a developer, we need not write code explicitly

Note : SAP Gateway Client is temporary screen for testing Odata


Service
The actual screens, we design using SAP Ui5/FIORI by accessing
OData Service

Note : while testing odata service , we can use below keywords

1 filter
2 count
3 format=xml ( default )
4 format=json
5 metadata
select
6 etc....
7

Filter query :
Every ODATA ABAP Service URL will be in below format

/sap/opu/odata/SAP/Z9PM_ODATAPROJECT1_SRV/FlightSet
______ ———————- _
commmon path service Name EntitySet

Note : If odata service is tested successfully,


then as a developer, we can develop screens using SAP UI5/FIORI
by accessing odata service with Service URL for triggering Database
functionality

Do’s And Dont’s in Odata


Get more insights of CRUD
operations
Developing OData Service with CRUD methods
( GET_ENTITY( ) method )

GET_ENTITY( ) method contains 2 parameters

1 1) it_key_tab : will capture Input key field values from Front-end app ( SAP UI5/FI
2
3 2) er_entity : will send output record to front-end app ( SAP Ui5/FIORI )
Search strings
OData Service with Search concept using wild card character

Requirement :

serviceURL/EMPSet?search=*

serviceURL/EMPSet?search=KIRAN

serviceURL/EMPSet?search=SUMAN

serviceURL/EMPSet?search=V*

serviceURL/EMPSet?search=S*

serviceURL/EMPSet?search=*N

serviceURL/EMPSet?search=K*N

TO deal with above requirement, we can implement code under


GET_ENTITYSET( ) method

To capture searchstring from front-end application ( SAP UI5/FIORI ) ,


we can use below statement

1 IO_TECH_REQUEST_CONTEXT->GET_SEARCH_STRING( ).

ABAP SELECT statement with WHERE clause using “LIKE” operator


must be used to deal with Wild card chacter

ET_ENTITYSet will send output record(s) to front-end app ( SAP


UI5/FIORI )
Procedure :

step1 : Open Your odata service IN SEGW transaction code

step2 : Make sure that Entity TYpe and Entity Set is available

step3 : open Data Provider Extension Class ( DPC_EXT )


open GET_ENTITYSET( ) method
and implement below code
___________________________________________

1
Data searchstring TYPE String.
2
3 searchstring = IO_TECH_REQUEST_CONTEXT->GET_SEARCH_STRING( ).
4
5 Replace all OCCURRENCES OF '*' in searchstring with '%'.
6
7 SELECT * from ZUSERINFO into
8 CORRESPONDING FIELDS OF table ET_ENTITYSET
Where FIRSTNAME LIKE SEARCHSTRING .
9
_____________________________________________________________
10
11 save and activate
12
step4 : open Service Maintainence and open GATEWAY client
and TEST THE Service

1 select EntitySet ( EMPSet ) and execute the service with below syntax
2
3 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/EMPSet?search=*A
4
5 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/EMPSet?search=S*
6
7 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/EMPSet?search=*
8
9 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/EMPSet?search=KIRAN
10
/sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/EMPSet?search=K*
11
12 etc.
13

HTTP Response
Common HTTP Status Codes for SAP UI5/FIORI/ODATA

HTTP status codes 1XX -> Informational MEssages

HTTP status codes 2XX -> SUCCESS Messages

HTTP status codes 3XX -> RE-DIRECTIONAL MESSAGES

HTTP Status codes 4XX -> Client Side ERROR messages

HTTP Status Codes 5XX -> Server Side ERROR Messages

1 [Link]

Note : AS a developer, we can use below tools for TEsting Odata


Service

1 1) SAP GATEWAY CLIENT -> SAP software ( GUI Based )


2
3 2) REST CLIENT -> THird party Software ( BROWSER based )
File Upload and Download
in Odata
Database Table : ZFILESTABLE

Under Database Table , File Content field is created with


“RAWSTRING” data type
Rawstring data type is capable of storing any type of file content
( pdf , gif, bmp, txt etc.. )

Note : For File Upload, we can implement code under


Update_STREAM( ) method

1 UPdate_stream( ) method contains


2
3 1) it_key_tab -> will capture input key field value from Front-end app ( SA
4
5 2) IS_MEDIA_RESOURCE-> will capture input file type and input file content from f
6
7 Note : IS_MEDIA_RESOURCE is of TYPE TY_S_MEDIA_RESOURCE ( structure )
8
TY_S_MEDIA_RESOURCE contains MIME_TYPE -> technically FILE TYPE
9
VALUE -> technically FILE CONTENT
10

Note : for File Download, we can implement code under


GET_Stream( ) method

1 GET_STREAM( ) method contains


2
3 1) IT_KEY_TAB -> will capture input key field value from Front-end APP ( SAP UI5/
4
5 2) ER_STREAM -> will send output file type and output file content to front-end

Procedure

step1 : open you Odata Service in SEGW Tcode or Create New Odata
service in SEGW

step2 : create Entity Type and Entity Set with ABAP structure =
ZFILESTABLE
select atleast one field as key field ( select Userid Field )
save and continue

step3 : select your Entity Type -> and Mark it as “MEDIA” option
save

step4 : Click on red color icon -> regenerate runtime artifacts ->
continue

step5 : open Data Provider Extension Class ( DPC_EXT )


click on change
select UPDATE_STREAM( ) method and -> “redefine”
and implement below code for File Upload functionality
_________________________________________________

1
2 Data WA_KEY_TAB TYPE /IWBEP/S_MGW_NAME_VALUE_PAIR.
Data WA TYPE ZCL_Z9PM_ODATAPROJECT2_MPC=>TS_FILE.
3
4 Read Table IT_KEY_TAB into WA_KEY_TAB index 1.
5
6 wa-USERID = WA_KEY_TAB-VALUE.
7 wa-SYDATE = Sy-DATUM.
8 wa-SYTIME = sy-UZEIT.
9 wa-FILETYPE = IS_MEDIA_RESOURCE-MIME_TYPE.
wa-FILECONTENT = IS_MEDIA_RESOURCE-VALUE.
10
11 INSERT into ZFILESTABLE values WA.
12
13 ____________________________________________________________
14 save and activate
15

step6 : select GET_STREAM( ) method -> “REDEFINE” the method


and implement below code for FILE DOWNLOAD functionality
_________________________________________________
1
2 Data wa_key_tab TYPE /IWBEP/S_MGW_NAME_VALUE_PAIR.
3 Data Wa TYPE ZCL_Z9PM_ODATAPROJECT2_MPC=>TS_FILE.
4 Data WaStream TYPE TY_S_MEDIA_RESOURCE.
5
Read Table IT_KEY_TAB into WA_KEY_TAB index 1.
6
7 select Single * from ZFILESTABLE into
8 CORRESPONDING FIELDS OF WA
9 where Userid = WA_KEY_TAB-VALUE.
10
11 WASTREAM-MIME_TYPE = wa-FILETYPE.
WASTREAM-VALUE = wa-FILECONTENT.
12
13
14
COPY_DATA_TO_REF( EXPORTING IS_DATA = WASTREAM
15 CHANGING CR_DATA = ER_STREAM
16 ).
17 ______________________________________________________________
18 save and activate
19

step7 : open service Maintainence -> open Gateway Client


and Test the service

1
2 FILE UPLOAD functionality Testing
3 ___________________________________
select EntitySet ( FileSet ) , use below url syntax
4 add file -> select your file from desktop/folder
5 and select "PUT" operation and execute the service
6
7 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/FileSet('5001')/$value
8
9
10 File Download Functionality Testing
__________________________________
11
open Gateway Client
12 select Your Entity Set ( FileSet ) , use below url syntax
13 -> select "GET" operation and execute the service
14
15 /sap/opu/odata/SAP/Z9PM_ODATAPROJECT2_SRV/FileSet('5001')/$value
16

NOte : COPY_DATA_TO_REF : can be used to avoid the type


incompatibility between source and Target

Note :

1 /FileSet('5003')/$value + PUT -> triggers UPDATE_STREAM( ) method


2 _______
3 media EntitySet
4
5
6 /FileSet('5003')/$value + GET -> triggers GET_STREAM( ) method
7 _______
media EntitySet
8
Associations in Odata
Associations define the relationship between two or more Entity
Types (for example, Employee WorksFor Department). Instances of
associations are grouped in Association Sets.

Navigation Properties are special properties on Entity Types


which are bound to a specific association and can be used to refer to
associations of an entity.

Association/ Provides [Link]


Navigation associate Products?$format=json
d
(depende
nt)
entity/en
tities
using
Navigati
on
property

Provides
associate
d
(depende
nt)
entity/en
tities [Link]
$expand
+ Princi $expand=Products&$format=json
pal
entity/en
tities

using
Navigati
on
property

Use the below link to get more information about the this topic

[Link]
code-association-navigation-and-data-provider-expand-in-odata-
service/ba-p/13114714

Odata URI Options


We can divide OData URI to 2 parts:

1. Do Not Need Custom Implementation

1. $select
2. $count
3. $expand
4. $format
5. $links
6. $value
2. Need Custom Implementation
1. $orderby
2. $top
3. $skip
4. $filter
5. $inlinecount
6. $skiptoken

With Implementation
1. $orderby: The $orderby option is used to specify a sort order for
the results of a query. It is used in the URL of an OData service to
indicate how the results should be sorted.

The syntax for the $orderby option is as


follows: $orderby=propertyName [asc|desc], where propertyName is
the name of the property by which the results should be sorted, and
“asc” or “desc” is used to specify the sort order (ascending or
descending, respectively).

For example, if we want to retrieve a list of customers and sort them


by last name in descending order, the URL would look like this:

1 [Link] desc

It is also possible to sort by multiple properties using the $orderby


option, by separating each property with a comma.

1 [Link] desc, FirstNa

The code the $orderby can be written as:

1 METHOD ekkoset_get_entityset.
2
*- To get data from DB
3
SELECT * FROM ekko INTO TABLE @DATA(lt_ekko) UP TO 10 ROWS.
4
5 *- Check the $orderby in the Odata Query
6 READ TABLE it_order INTO DATA(ls_order) INDEX 1.
7 IF sy-subrc IS INITIAL.
8 IF ls_order-order = 'desc'.
SORT lt_ekko BY (ls_order-property) DESCENDING.
9 ELSE.
10 SORT lt_ekko BY (ls_order-property) ASCENDING.
11 ENDIF.
12 ENDIF.
13
14 *- Check the size of the table for $inlinecount
IF io_tech_request_context->has_inlinecount( ) = abap_true.
15 DESCRIBE TABLE lt_ekko LINES DATA(lv_size).
16 es_response_context-inlinecount = lv_size.
17 ENDIF.
18
19
20
MOVE-CORRESPONDING lt_ekko TO et_entityset.
21
22 ENDMETHOD.
23
24

Below is the output:

1. $[Link]
Another better way to use the $orderby can be the standard way of
using it, displayed below:

1 *- Check the $orderby in the Odata Query


2 /iwbep/cl_mgw_data_util=>orderby(
EXPORTING
3 it_order = it_order " the sorting order
4 CHANGING
5 ct_data = lt_ekko
6 ).
7

2. $top: The $top option is used to specify the maximum number of


results that should be returned in a query. It is used in the URL of an
OData service to indicate how many results should be returned. The
syntax for the $top option is as follows: $top=n, where n is an
integer indicating the number of results that should be returned.

For example, if we want to retrieve the top 10 customers, the URL


would look like this:

1 [Link]

The $top option can be used in combination with other options such
as $filter, $select and $orderby to further refine the results of a
query.

1 [Link] eq 'US'&$top=5&

It’s important to note that the $top option is used to limit the
number of records returned in one response and not to restrict the
total number of records returned by the OData service.

1 METHOD ekkoset_get_entityset.
2
3 *- To get data from DB
SELECT * FROM ekko INTO TABLE @DATA(lt_ekko) UP TO 10 ROWS.
4
5 *- Check the $orderby in the Odata Query
6 /iwbep/cl_mgw_data_util=>orderby(
7 EXPORTING
8 it_order = it_order " the sorting order
9 CHANGING
ct_data = lt_ekko
10 ).
11
12 *- For paging i.e. $top and $skip
13 /iwbep/cl_mgw_data_util=>paging(
14 EXPORTING
is_paging = is_paging " paging structure
15
CHANGING
16 ct_data = lt_ekko
17 ).
18
19 *- Check the size of the table for $inlinecount
20 IF io_tech_request_context->has_inlinecount( ) = abap_true.
DESCRIBE TABLE lt_ekko LINES DATA(lv_size).
21 es_response_context-inlinecount = lv_size.
22 ENDIF.
23
24 MOVE-CORRESPONDING lt_ekko TO et_entityset.
25
26 ENDMETHOD.
27
28
29
30

We can use it as below:

2. $[Link]
3. $skip: The $skip option is used to specify the number of results
that should be skipped before returning the results in a query. It is
used in the URL of an OData service to indicate how many results
should be skipped. The syntax for the $skip option is as follows:
$skip=n, where n is an integer indicating the number of results that
should be skipped.

For example, if we want to retrieve all customers but skip the first
10, the URL would look like this:
1 [Link]

The $skip option can be used in combination with other options such
as $top, $filter, $select, and $orderby to further refine the results of
a query.

1 [Link] eq 'US'&$skip=5

It’s important to note that the $skip option is used to skip the
records from the beginning of the result set, so it is typically used in
combination with the $top option to retrieve a specific page of
results.

Same code of paging(used in 3. $top). The below snippet is showing


the second 2nd record as it is fetching the 1st record after skipping
1st one.

3. $[Link]
4. $filter: The $filter option is used to specify filter criteria for the
results of a query. It is used in the URL of an OData service to
indicate which results should be returned based on certain
conditions. The syntax for the $filter option is as follows:
$filter=condition, where the condition is a logical expression that
evaluates to true or false.

The condition can be built using comparison and logical operators


(eq, ne, gt, ge, lt, le, and, or, not).

For example, if we want to retrieve all customers whose last name


starts with “S”, the URL would look like this:

1 [Link]

If we want to retrieve all customers whose last name starts with “S”
and whose first name is “John”, the URL would look like this:

1 [Link]

The $filter option can be used in combination with other options


such as $top, $skip, $select, and $orderby to further refine the
results of a query.

1 METHOD ekkoset_get_entityset.
2
3 *- To get data from DB
4 *- it_filter_select_options will have filter values for $filter keyword
IF it_filter_select_options IS INITIAL.
5 SELECT * FROM ekko INTO TABLE @DATA(lt_ekko) UP TO 10 ROWS.
6 ELSE.
7 READ TABLE it_filter_select_options INTO DATA(ls_sopt)
8 WITH KEY property = 'Ebeln'.
9 IF sy-subrc IS INITIAL.
SELECT * FROM ekko INTO TABLE @lt_ekko WHERE ebeln IN @ls_sopt-select_opti
10 ENDIF.
11 ENDIF.
12
13 *- Check the $orderby in the Odata Query
14 /iwbep/cl_mgw_data_util=>orderby(
EXPORTING
15
it_order = it_order " the sorting order
16 CHANGING
17 ct_data = lt_ekko
18 ).
19
20 *- For paging i.e. $top and $skip
/iwbep/cl_mgw_data_util=>paging(
21 EXPORTING
22 is_paging = is_paging " paging structure
23 CHANGING
24 ct_data = lt_ekko
25 ).
26
27
28
29 *- Check the size of the table for $inlinecount
30 IF io_tech_request_context->has_inlinecount( ) = abap_true.
31 DESCRIBE TABLE lt_ekko LINES DATA(lv_size).
32 es_response_context-inlinecount = lv_size.
33 ENDIF.
34
MOVE-CORRESPONDING lt_ekko TO et_entityset.
35
36 ENDMETHOD.
37
38
39

We can test the above code as:

4. $[Link]
5. $inlinecount: It is used to include the total count of all the
matching results in the response. It is used in the URL of an OData
service to indicate that the total count of the matching results
should be included in the response. The syntax for the $inlinecount
option is as follows: $inlinecount=allpages, where “allpages” is a
keyword indicating that the total count should be included.

For example, if we want to retrieve all customers and include the


total count of customers in the response, the URL would look like
this:

1 [Link]

The $inlinecount option can be used in combination with other


options such as $filter, $top, $skip, $select and $orderby to further
refine the results of a query.

1 [Link] eq 'US'&$top=5&

It’s important to note that the $inlinecount option will include the
count of the matching results in the response, the count will be
included in the “.count” attribute of the response.
5. $[Link]
6. $skiptoken: The $skiptoken option is used with the $top option
to retrieve a specific page of results by providing a token that
represents the position in the result set from where the next set of
results should be retrieved. When a partial response is returned by
the server, the $skiptoken value is included in the __next link of the
response, allowing clients to easily retrieve the next set of results
without having to construct or interpret the $skiptoken value
themselves.

The syntax for the $skiptoken option is as follows:


$skiptoken=token, where the token is a string value representing
the position in the result set from where the next set of results
should be retrieved.

For example, if we want to retrieve the next set of 10 customers


starting from the 11th customer, the URL would look like this:
1 [Link]

The $skiptoken option can be used in combination with other


options such as $filter, $top, $select and $orderby to further refine
the results of a query.

1 [Link] eq 'US'&$top=5&

It’s important to note that the $skiptoken option is used to navigate


through the result set in a pagination manner, and it should be used
in conjunction with $top option and the result set should be sorted in
the same order as in the query that generated the skiptoken.

6. $[Link]

The $skiptoken option is used with the $top option to retrieve a


specific page of results by providing a token that represents the
position in the result set from where the next set of results should
be retrieved. When a partial response is returned by the server, the
$skiptoken value is included in the __next link of the response,
allowing clients to easily retrieve the next set of results without
having to construct or interpret the $skiptoken value themselves.

The syntax for the $skiptoken option is as follows:


$skiptoken=token, where the token is a string value representing
the position in the result set from where the next set of results
should be retrieved.

For example, if we want to retrieve the next set of 10 customers


starting from the 11th customer, the URL would look like this:

1 [Link]

The $skiptoken option can be used in combination with other


options such as $filter, $top, $select and $orderby to further refine
the results of a query.

1 [Link] eq 'US'&$top=5&

It’s important to note that the $skiptoken option is used to navigate


through the result set in a pagination manner, and it should be used
in conjunction with $top option and the result set should be sorted in
the same order as in the query that generated the skiptoken.
6. $[Link]

The $skip and $skiptoken looks same in first look but they are some
difference. To know further about $skip and $skiptoken you can visit
this blog: Difference between $skip and $skiptoken in Odata

Conclusion
SAP has provided us multiple options to play with for real-time
requirements with a little effort. I would recommend you to try these
query options and debug to see how it works. The blog was divided
into the following parts.

 $orderby: sorts data by one or more fields.


 $top and $skip: enable server-side paging.
 $filter: retrieves specific data from an entity set based on a set
of criteria.
 $inlinecount: provides the total number of records in an entity
set.
 $skiptoken: enables server-side paging using a continuation
token.

In the world of Odata services, there are two types of services –

 Those created from SEGW


 Those based on CDS views

When creating Odata services from SEGW, custom implementation


is required for the $orderby, $top, $skip, $filter, and $inlinecount
query options. However, this is not the case when the Odata service
is based on a CDS view. In this scenario, SAP provides these query
options without the need for implementation, making the
development process simpler and more efficient.

It’s important to note that this difference exists because of the


fundamental architectural differences between SEGW and CDS
views. SEGW generates ABAP code based on metadata, whereas
CDS views are defined in the ABAP repository and translated into
Open SQL. By leveraging the capabilities of CDS views, developers
can benefit from SAP’s pre-built query options and focus on
delivering value to their customers.

1. $select

the $select query option in OData is used to specify which properties


or fields of a resource should be included in the response. The
$select option is typically used to optimize performance by limiting
the number of columns that are returned in a query. The value of
the $select option is a comma-separated list of the properties or
fields that should be included in the response.

For example, if you want to retrieve only the name and address
fields of a customer resource, you would use a query
like /Customers?$select=Name, Address.

This is an example string that is likely being used to select specific


fields, “Name” and “Address,” from a collection of “Customers” in a
database.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet?$select=Ebeln, Bukrs, Ernam

The above query will give selected fields i.e Ebeln, Burks and Ernam
from the DB:
1. $[Link]

We can get a similar result for a particular record as well.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet('4500000000')?$select=Ebeln, Bukrs, Er

The above query will give the below result:


$[Link]

2. $count

The $count query option in OData is used to retrieve the number of


entities in a collection. The $count option is typically used to
optimize performance by limiting the amount of data that is
returned in a query.

When the $count option is included in a query, the response will


include the total number of entities in the collection, rather than the
actual entities themselves.

For example, if you want to retrieve the number of customers in a


customer resource, you would use a query like /Customers/$count.

The response will return a single number, for example 28.


It’s important to note that the $count option can only be used on
collections and not on individual entities.

We can also combine the $count with other options like $top, $skip,
$filter, $expand etc.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet('6000000000')/ToPOItem/$count

The above query will count the total number of records for the
mentioned PO number.

$[Link]
3. $expand

The $expand query option in OData is used to retrieve related


entities along with the requested entity. The $expand option is used
to retrieve related data in a single request instead of making
multiple requests to the server.

For example, if you have an entity called “Orders” and it has a


navigation property called “OrderItems” which represents the items
that are part of the order, you can use the $expand option to
retrieve both the Order and the OrderItems in a single request.

The query would look like /Orders?$expand=OrderItems

This query would return the Order entity along with the related
OrderItems entities in the same response. You can also specify
multiple navigation properties by separating them with a comma.

It is important to note that, when using $expand query option, it


increases the size of the response and can affect the performance of
the query. Therefore, it’s good practice to use it judiciously and only
when it’s needed.

We can also use it in combination with other query options like


$select, $filter, $top, $skip etc.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKPOSet(Ebeln='6000000000',Ebelp='00010')?$exp

The above query will give the below result:

3. $[Link]
4. $format
The $format query option in OData is used to specify the format of
the response. The $format option can be used to request the
response in different formats such as JSON, XML

/Orders?$format=json

/Orders?$format=xml

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet?$format=json

The above query will give the result in JSON format.

4. $[Link]
5. $links
The $links query option in OData is used to return the links between
entities. The $links option is used to retrieve navigation links
between related entities in a single request.
When the $links option is included in a query, the response will
include URLs for the navigation properties of the entity, which can
be used to retrieve the related entities. For example, if you have an
entity called “Orders” and it has a navigation property called
“OrderItems” which represents the items that are part of the order,
you can use the $links option to retrieve the URLs for the OrderItems
entities.

The query would look like /Orders?$links=OrderItems.

This query would return the URLs for the related OrderItems entities
in the same response. You can also specify multiple navigation
properties by separating them with a comma.

It is important to note that, when using $links query option, it


increases the size of the response and can affect the performance of
the query. Therefore, it’s good practice to use it judiciously and only
when it’s needed.

We can also use it in combination with other query options like


$select, $filter, $expand, $format etc.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet('6000000000')/$links/ToPOItem

The above query will give the below result:

5. $[Link]
6. $value
The $value query option in OData is used to return only the value of
a primitive property or a complex property without the property
name and metadata. The $value option is used to retrieve the value
of a property in a single request instead of returning the entire
entity or complex object.

For example, if you have an entity called “Products” and it has a


primitive property called “Price”, you can use the $value option to
retrieve the value of the Price property in a single request.

The query would look like /Products(‘001’)/Price/$value.

This query would return the value of the Price property in the
response.

It is important to note that, the $value option can only be used on


primitive properties and complex properties and not on collection
properties.

This can be used in combination with other query options like


$select, $filter, $expand, $format etc.

1 /sap/opu/odata/sap/ZNS_PORELATED_SRV/EKKOSet('6000000000')/Bukrs/$value

The above query will show the value of Burks for the mentioned
records.

$[Link]
Share this:

 X

 Facebook


Loading…

Leave a comment
Previous Post
ABAP Webservice [ Part of Interface ]
Next Post
Module Pool Programming in ABAP
 Facebook
 Twitter
 Instagram
A [Link] site





Design a site like this with [Link]
Get started

You might also like