Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CORE ABAP / OData (SAP Gateway)

OData (SAP Gateway)

CORE ABAP · ABAP Development ·

Open the interactive lesson →
  1. REST and OData basics
  2. SAP Gateway architecture and deployment
  3. The OData data model (EDM)
  4. Building a service in SEGW
  5. CRUD-Q methods
  6. Query options
  7. $expand and deep insert
  8. $batch and change sets
  9. Function imports
  10. Media and streams (files, PDF)
  11. Concurrency: ETag and CSRF token
  12. Errors, testing, tracing, cache
  13. OData V2 vs V4
  14. CDS-based exposure and the modern way (RAP)
  15. Consuming the service in SAPUI5
  16. Interview questions

How SAP exposes business data to Fiori, mobile and other systems as OData services with SAP Gateway. The classic tool is the Service Builder (SEGW): you model entities, SEGW generates classes, and you code the CRUD-Q methods in ABAP. New S/4HANA development uses RAP (see the RAP section), but SEGW services are everywhere in existing systems and a favourite interview topic. Running example: a demo service ZJP_DEMO_SRV with entity set CarrierSet (table SCARR) and FlightSet (SPFLI).

Part 1 – REST and OData basics

1.1 APIs and web APIs

An API is a set of rules that lets two applications talk to each other (example: an app asks a weather API for today's forecast). The API is the contract between them; neither side needs to know how the other is built.

API style

Format

Notes

SOAP

XML envelope

Strict contract (WSDL), WS-Security; common in older B2B integration (see page 09 Web Services)

RPC (XML-RPC, JSON-RPC, SAP RFC)

XML / JSON / binary

Call a remote procedure by name

WebSocket

usually JSON

Two-way, long-lived connection (push, chat)

REST

JSON, XML …

Most popular style for web APIs; OData is built on REST

  • Remote API = called over any network. Web API = called over HTTP on the web. All web services are APIs, but not all APIs are web services.

1.2 REST – an architectural style

REST (Representational State Transfer) is an architectural style, not a protocol. The server holds resources; the client reads or changes their representations (JSON, XML) with HTTP methods. A service that follows the REST rules is called RESTful. HTTP itself is the stateless protocol underneath.

REST constraint

Meaning

1. Client–server

Client and server are independent; the client only needs the URI of the resource

2. Stateless

Every request carries all information it needs; the server keeps no session between requests

3. Cacheable

Responses say whether they may be cached (e.g. static images, $metadata)

4. Layered system

Proxies, load balancers, gateways can sit in between without client or server noticing

5. Uniform interface

Resources identified by URIs; standard operations (GET/POST/PUT/PATCH/DELETE); self-describing messages; hypermedia links between resources

6. Code on demand (optional)

Server may send executable code to the client (e.g. JavaScript for form validation). Not the same as OData function imports – those are custom server operations.

Stateful vs stateless

Stateful SAP GUI session vs stateless OData requests, with optional soft state

SAP GUI is stateful: each user holds a session (memory, locks) on the server for the whole transaction. OData is stateless: each HTTP request is processed and forgotten, so one server can handle huge numbers of users. (Gateway also has an optional soft state mode that keeps the session for a short time – for performance only.)

1.3 The parts of an HTTP request and response

  • URI (Uniform Resource Identifier) names the resource. URI is the umbrella term: a URL says where it is (locator), a URN gives a permanent name – both are kinds of URI.
  • Method: GET (read), POST (create / action), PUT (replace), PATCH (partial update), DELETE. GET, PUT and DELETE are idempotent (repeating them gives the same result); POST is not.
  • Headers: Content-Type, Accept, Authorization, X-CSRF-Token, If-Match, sap-client …
  • Body: the payload (JSON or XML) for POST/PUT/PATCH; the response body holds the representation.
  • Status code in the response – the first digit tells the class:

Code

Meaning

Typical Gateway situation

200 OK

Success with a body

GET entity / entity set

201 Created

Entity created

POST → CREATE_ENTITY

202 Accepted

Accepted, maybe not finished

V2: $batch response · V4: asynchronous processing

204 No Content

Success, no body

PUT / PATCH / DELETE

304 Not Modified

Unchanged since the ETag you sent

GET with If-None-Match

400 Bad Request

Malformed URI, header or payload

Wrong $filter syntax, wrong key

401 Unauthorized

Not logged on

Missing / wrong credentials

403 Forbidden

Not allowed

Missing S_SERVICE authorization, CSRF token invalid, or service not activated on the hub ("No service found for namespace")

404 Not Found

Resource does not exist

Entity with this key not found

405 Method Not Allowed

Wrong method for this URI

PUT on an entity set

412 Precondition Failed

If-Match ETag is outdated

Someone else changed the record

428 Precondition Required

Must send If-Match

Entity has an ETag, request had none

500 Internal Server Error

Unexpected error / dump

Unhandled exception in the DPC

501 Not Implemented

Method not implemented

DPC_EXT method not redefined

1xx = informational (e.g. 102 Processing), 3xx = redirect (301 Moved Permanently). The list is not exhaustive.

1.4 What OData adds to REST

OData (Open Data Protocol) is an open standard managed by OASIS; OData V4 is also an ISO/IEC standard (20802, 2016). It is both a data format (how entities are described and serialised) and a protocol (how they are read and changed via URIs and HTTP). SAP Gateway is the connector that translates ABAP objects (tables, BAPIs, CDS) into OData entities.

  • Service document (/ZJP_DEMO_SRV/) – lists all entity sets of the service.
  • Service metadata document (/ZJP_DEMO_SRV/$metadata) – the full model: entity types, properties, keys, associations, navigation properties, entity sets, function imports.
  • Formats: V2 supports Atom (XML) and JSON ($format=json); V4 is JSON only. Entity set and entity correspond to Atom/RSS feed and entry.
  • Standard operations CRUD-Q (create, read, update, delete, query) plus query options ($filter, $select, $expand …) that every client understands.
  • Public sample service to practise URIs: https://services.odata.org/V2/Northwind/Northwind.svc/ (Customers, Employees, Orders, Order_Details).

Part 2 – SAP Gateway architecture and deployment

2.1 Why Gateway

Point-to-point integrations vs one OData channel through SAP Gateway

Before Gateway, every consumer (mobile app, portal, Office add-in) got its own custom integration (RFC, BSP, SOAP …). Nothing was reusable. Gateway gives one protocol – OData – so a service is built once and any device or platform can consume it.

2.2 Architecture

SAP Gateway layers: consumers, front-end hub framework (IWFND), back-end enablement (IWBEP), SAP HANA
  • Front-end server – SAP Gateway Hub Framework (IWFND): service catalog, activation, routing to back ends, system aliases, OData runtime, CSRF/security, caching. With Fiori it also hosts the launchpad and UI5 apps.
  • Back-end server – Gateway Back-End Enablement (IWBEP): SEGW, the generated MPC/DPC classes, your business logic, access to tables/BAPIs/CDS on SAP HANA or any database.

2.3 Software components

Release

Front-end (hub) components

Back-end components

7.00 – 7.31 (add-ons)

GW_CORE (OData libraries), IW_FND (runtime, metadata store, service registration). Optional: IW_PGW, IW_CNT (workflow), IW_SCS (Dynpro), IW_CBS (GenIL)

IW_BEP (development, generators for RFC, BOR, BW, F4 help), IW_HDB (HANA). Optional: IW_GIL (GenIL), IW_SPI (SPI)

7.40 and later

SAP_GWFND – one component that contains front-end and back-end parts (former GW_CORE, IW_FND, IW_BEP). Optional add-ons remain separate: IW_FNDGC, IW_PGW, IW_SCS, IW_CNT, IW_CBS

Same SAP_GWFND (incl. RFC, BOR, BW, F4-help and CDS generators). IW_HDB is not part of it any more. Optional: IW_GIL, IW_SPI

2.4 Deployment options – hub vs embedded

Deployment options: embedded (recommended for S/4HANA), central hub with development in back end, legacy development in hub

Option

How

Pros

Cons

Central hub, development in back end

Gateway hub (Fiori front-end server) is a separate system; MPC/DPC live in the back end and are registered on the hub via RFC

Upgrade UI/Gateway without back-end downtime; one central entry for several back ends (multi-origin, routing, security in DMZ)

Extra server to run and patch

Central hub, development in hub

Service implementation on the hub; it calls the back end via RFC

Back end needs no Gateway component (old releases before 7.40)

Only RFC-enabled interfaces usable; rare today

Embedded

Hub framework and back-end enablement in the same system (S/4HANA)

Simple, fewer systems, no RFC hop, better performance

Harder to serve several back ends from one launchpad; UI upgrades follow the back-end system

SAP's recommendation for S/4HANA (since 2020): embedded deployment of the Fiori front-end server. A central hub is now for special cases (e.g. one launchpad for many back-end systems). With a hub, the system alias (/IWFND/MAINT_SERVICE → System Aliases) tells the hub which back end serves the service; embedded uses the alias LOCAL.

Part 3 – The OData data model (EDM)

OData describes data with the Entity Data Model (EDM). Every artefact has a simple ABAP analogy:

EDM artefact

Meaning

ABAP analogy

Property

One field with an EDM type (Edm.String, Edm.Int32, Edm.Decimal, Edm.DateTime …)

Component

Entity type

Named structured type with a key

Structure type

Entity

One instance of an entity type; read with GET, changed with PUT/PATCH

Work area

Entity set

Collection of entities of one type (what you address in a URI)

Internal table

Complex type

Keyless structure, only usable as a property or function result (e.g. Address)

Include structure

Association

Relationship between two entity types with cardinality (1 : n)

Foreign key

Association set

The same relationship between two entity sets

–

Navigation property

Path from one entity to related ones, used in URIs (/CarrierSet('LH')/Flights)

Join path

Entity container

Holds all entity sets, association sets and function imports of a service

The service

Function import

Custom operation beyond CRUD-Q (V2)

Method

OData model: entity container, entity sets, entity type with key, properties and navigation; HTTP operations on sets, entities and $batch

The yellow boxes show the operations: on an entity set GET (feed) and POST (create an entry); on an entity GET, PUT (with ETag), PATCH (partial, with ETag) and DELETE; and POST <service root>/$batch for many requests in one call.

How it looks in $metadata (Northwind)

<EntityType Name="Order_Detail">
<Key><PropertyRef Name="OrderID"/><PropertyRef Name="ProductID"/></Key>
<Property Name="OrderID"   Type="Edm.Int32"   Nullable="false"/>
<Property Name="ProductID" Type="Edm.Int32"   Nullable="false"/>
<Property Name="UnitPrice" Type="Edm.Decimal" Nullable="false" Precision="19" Scale="4"/>
<Property Name="Quantity"  Type="Edm.Int16"   Nullable="false"/>
<Property Name="Discount"  Type="Edm.Single"  Nullable="false"/>
</EntityType>

<Association Name="FK_Order_Details_Orders">            <!-- one order : many details -->
<End Role="Orders"        Type="NorthwindModel.Order"        Multiplicity="1"/>
<End Role="Order_Details" Type="NorthwindModel.Order_Detail" Multiplicity="*"/>
<ReferentialConstraint>
<Principal Role="Orders"><PropertyRef Name="OrderID"/></Principal>
<Dependent Role="Order_Details"><PropertyRef Name="OrderID"/></Dependent>
</ReferentialConstraint>
</Association>

<EntityContainer Name="NorthwindEntities">
<EntitySet Name="Order_Details" EntityType="NorthwindModel.Order_Detail"/>
<AssociationSet Name="FK_Order_Details_Orders"
Association="NorthwindModel.FK_Order_Details_Orders">
<End Role="Orders" EntitySet="Orders"/>
<End Role="Order_Details" EntitySet="Order_Details"/>
</AssociationSet>
</EntityContainer>

<!-- inside EntityType "Customer": the path used in URIs -->
<NavigationProperty Name="Orders" Relationship="NorthwindModel.FK_Orders_Customers"
FromRole="Customers" ToRole="Orders"/>

In SEGW, creating an association between two entity types also creates the navigation property on the principal side and the association set.

Part 4 – Building a service in SEGW

4.1 Project types

  • Service with SAP Annotations – the normal choice. Property flags such as creatable, updatable, sortable, filterable, label, unit; facets nullable, default, max length, fixed length, precision, scale; ABAP field name and type.
  • Service with Vocabulary-Based Annotations – uses OData vocabularies uploaded into the Vocabulary Repository (the standard SAP annotations such as creatable / updatable are not available in this project type).
  • Annotation Model for Referenced Service – adds (UI) annotations to an existing service without changing it.

4.2 Development phases

SEGW phases: data model definition (MPC), service implementation (DPC), generation, maintenance

Phase

What you do

1. Data model definition (→ MPC)

Entity types, properties, keys, entity sets, associations, navigation

2. Service implementation (→ DPC)

Code the CRUD-Q methods in DPC_EXT or map them to a data source

3. Service generation

Generate Runtime Objects – creates the classes and the registration

4. Service maintenance

Register and activate the service on the hub, then test

4.3 Defining the data model – three ways

SEGW project tree (ZSALESORDER_002) and the Data Model Import menu: file, DDIC structure, RFC/BOR, search help
  • Declarative: create entity types, properties, sets and associations by hand.
  • Import a data model file (EDMX / metadata XML, e.g. designed in another tool).
  • Import from the repository: Data Model → right-click → Import → DDIC Structure (tables, views, structures, also CDS SQL views), RFC/BOR Interface (parameters of a BAPI/FM), Search Help. Tick the fields you need and mark the key.

4.4 Step by step

  • 1. SEGW → Create Project (name e.g. ZJP_DEMO, package, project type).
  • 2. Define the data model (import DDIC structure SCARR → entity type Carrier, entity set CarrierSet).
  • 3. Click Generate Runtime Objects (red/white wheel) – the stub classes are created.
  • 4. Register the stub on the hub early and check $metadata – catches model errors before you code.
  • 5. Implement the methods in DPC_EXT (Service Implementation → entity set → operation → Go to ABAP Workbench).
  • 6. Test in the Gateway Client (/IWFND/GW_CLIENT).

4.5 Generated runtime artifacts

Artifact

Example name

Purpose

You edit it?

MPC – model provider class

ZCL_ZJP_DEMO_MPC

Builds the metadata (method DEFINE); inherits /IWBEP/CL_MGW_PUSH_ABS_MODEL

No – regenerated

MPC_EXT

ZCL_ZJP_DEMO_MPC_EXT

Subclass: redefine DEFINE for deep structures, content type, extra annotations

Yes

DPC – data provider class

ZCL_ZJP_DEMO_DPC

Empty CRUD-Q methods per entity set, implements /IWBEP/IF_MGW_APPL_SRV_RUNTIME

No – regenerated

DPC_EXT

ZCL_ZJP_DEMO_DPC_EXT

Subclass: all your business logic (redefine methods)

Yes

Model (registration)

ZJP_DEMO_MDL

Technical model name in the back end

No

Service (registration)

ZJP_DEMO_SRV

Technical service name; the external name users call

No

Rule: never put logic in the base classes – every regeneration overwrites them. Only the _EXT classes survive.

4.6 Service implementation – code-based or mapping

Each operation maps to a DPC_EXT method; Go to ABAP Workbench (code) or Map to Data Source (no code)
  • Code-based: redefine <EntitySet>_CREATE_ENTITY, _GET_ENTITY, _GET_ENTITYSET, _UPDATE_ENTITY, _DELETE_ENTITY in DPC_EXT. Full control – the usual way.
  • Map to Data Source (no code): map each operation to an RFC/BAPI (create, read, update, delete, query separately), to a search help (read and query only), or map the whole entity set to a CDS view (SADL – read and query generated, see Part 14).

4.7 Register and activate

Registered service and model in the back end, catalog entry on the hub, and the /IWFND/MAINT_SERVICE screen

Generation registers the model (wraps the MPC) and the service (wraps the DPC) in the back end. To make it callable you activate it on the hub, which creates an entry in the service catalog and an ICF node: SEGW → Service Maintenance → system → Register, or directly in /IWFND/MAINT_SERVICE → Add Service (system alias, technical service name, package).

  • /IWFND/MAINT_SERVICE: add / delete services, check the ICF node (must be green – SICF /sap/opu/odata), maintain system aliases, load metadata, open Gateway Client or browser, error log, soft state.
  • SEGW Service Maintenance menu: Register (catalog entry), Maintain (jumps to /IWFND/MAINT_SERVICE), Gateway Client, Error Log.
  • Users need authorization object S_SERVICE for the service (generated when you add it; put it in a PFCG role).
  • Tip – which SEGW project belongs to a service? SE16 on view /IWBEP/I_SBD_GA, field TROBJ_NAME. Usually project = service name without _SRV.

4.8 The URI and which method it calls

Parts of a Gateway OData URI and which DPC_EXT method each request calls

Pattern: https://<host>:<port>/sap/opu/odata/sap/<SERVICE>_SRV/<EntitySet>(<key>)?<options>. Add sap-client=100 to choose the client. Keys of string type need single quotes: CarrierSet('LH'); several keys: FlightSet(Carrid='LH',Connid='0400').

Part 5 – CRUD-Q methods

Read returns one entity (by key); query returns an entity set. Each method receives io_tech_request_context (keys, filters, paging …) and fills er_entity / et_entityset.

Query – GET /CarrierSet → CARRIERSET_GET_ENTITYSET

METHOD carrierset_get_entityset.
SELECT carrid, carrname, currcode FROM scarr
INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
" an empty result is NOT an error for a query – just return an empty set
ENDMETHOD.

Read – GET /CarrierSet('LH') → CARRIERSET_GET_ENTITY

METHOD carrierset_get_entity.
DATA ls_key TYPE zcl_zjp_demo_mpc=>ts_carrier.
" converted keys = ABAP field names and types, no manual string handling
io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_key ).

SELECT SINGLE carrid, carrname, currcode FROM scarr
WHERE carrid = @ls_key-carrid
INTO CORRESPONDING FIELDS OF @er_entity.
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING textid           = /iwbep/cx_mgw_busi_exception=>resource_not_found
entity_type      = iv_entity_name
http_status_code =
/iwbep/cx_mgw_busi_exception=>gcs_http_status_codes-not_found.
ENDIF.
ENDMETHOD.

Create – POST /CarrierSet + body → CARRIERSET_CREATE_ENTITY

METHOD carrierset_create_entity.
DATA ls_carrier TYPE zcl_zjp_demo_mpc=>ts_carrier.
io_data_provider->read_entry_data( IMPORTING es_data = ls_carrier ).  "request body

" real projects: AUTHORITY-CHECK + validation + BAPI instead of a direct INSERT
INSERT scarr FROM @( CORRESPONDING scarr( ls_carrier ) ).
IF sy-subrc = 0.
er_entity = ls_carrier.  "returned with 201 Created
ELSE.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING message = |Carrier { ls_carrier-carrid } already exists|.
ENDIF.
ENDMETHOD.

Update – PUT /CarrierSet('LH') → CARRIERSET_UPDATE_ENTITY

Same pattern as create: read_entry_data( ), then UPDATE scarr FROM @…; on success fill er_entity (the response is 204 No Content). PUT replaces the whole entity. For partial updates the client sends PATCH (V2 also MERGE); Gateway calls PATCH_ENTITY, whose default implementation reads the entity with GET_ENTITY, merges the changed fields and calls UPDATE_ENTITY.

Delete – DELETE /CarrierSet('LH') → CARRIERSET_DELETE_ENTITY

METHOD carrierset_delete_entity.
DATA ls_key TYPE zcl_zjp_demo_mpc=>ts_carrier.
io_tech_request_context->get_converted_keys( IMPORTING es_key_values = ls_key ).
DELETE FROM scarr WHERE carrid = @ls_key-carrid.
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
EXPORTING message = |Carrier { ls_key-carrid } not found|.
ENDIF.
ENDMETHOD.

Reading the key with get_keys( ) and VALUE s_carr_id( lt_keys[ 1 ]-value ) also works, but get_converted_keys( ) is type-safe and handles several key fields.

Navigation – GET /CarrierSet('LH')/Flights → FLIGHTSET_GET_ENTITYSET

The target entity set's GET_ENTITYSET is called; ask the context where the call came from and read the source keys:

METHOD flightset_get_entityset.
DATA ls_carrier TYPE zcl_zjp_demo_mpc=>ts_carrier.
CASE io_tech_request_context->get_source_entity_type_name( ).
WHEN zcl_zjp_demo_mpc=>gc_carrier.  "called via /CarrierSet('LH')/Flights
io_tech_request_context->get_converted_source_keys(
IMPORTING es_key_values = ls_carrier ).
SELECT * FROM spfli WHERE carrid = @ls_carrier-carrid
INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
WHEN OTHERS.  "called directly: /FlightSet
SELECT * FROM spfli INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
ENDCASE.
ENDMETHOD.

Summary – operation, HTTP method, ABAP

DPC_EXT method

HTTP

Typical ABAP

CREATE_ENTITY

POST

INSERT / BAPI create

GET_ENTITY

GET (one)

SELECT SINGLE

GET_ENTITYSET

GET (many)

SELECT

UPDATE_ENTITY / PATCH_ENTITY

PUT / PATCH (MERGE)

UPDATE / BAPI change

DELETE_ENTITY

DELETE

DELETE / BAPI delete

EXECUTE_ACTION (function import)

GET or POST

any logic (approve, release …)

CREATE_STREAM / GET_STREAM / UPDATE_STREAM / DELETE_STREAM

POST / GET / PUT / DELETE

upload, download, replace, delete a file

GET_EXPANDED_ENTITY / GET_EXPANDED_ENTITYSET

GET + $expand

header with its items in one call

CREATE_DEEP_ENTITY

POST with nested items

deep insert (header + items)

Part 6 – Query options

6.1 Handled by the framework (no code)

Option

Example

Effect

$format

/SalesOrderHeaders?$format=json

JSON instead of Atom XML

$select

?$select=SalesOrder,SalesOrg,Vtweg

Only these properties in the response (you may still read all fields – check get_select( ) to optimise)

$count

/SalesOrderHeaders/$count

Number of entities – only on a collection, not on a single entity

$links

/SalesOrderHeaders('4970')/$links/Items

Only the URIs of related entities (V2)

$value

/SalesOrderHeaders('4970')/Bstnk/$value

Raw value of one property (or the media of a stream entity)

$expand

?$expand=Items

Works generically – but see Part 7 (N+1 problem)

$metadata

/ZJP_DEMO_SRV/$metadata

Model document

6.2 Need your code in GET_ENTITYSET

The framework parses them, but you must apply them – otherwise the client gets all rows unsorted: $filter, $orderby, $top, $skip, $inlinecount, $skiptoken, search. Best practice on HANA: push them into the SELECT (code pushdown, see ABAP on HANA › 01 HANA Fundamentals) instead of reading everything and filtering in ABAP. Helper class for in-memory cases: /IWBEP/CL_MGW_DATA_UTIL (methods filtering, orderby, paging).

$filter

URIs: ?$filter=Kunnr eq '1390', ?$filter=(Kunnr eq '1390' or Kunnr eq '1175') and Vtweg eq '10'. String literals use single quotes. Operators: eq, ne, gt, ge, lt, le, and, or, not, substringof('LH',Carrid) / startswith(...) (V2).

METHOD carrierset_get_entityset.
DATA lr_carrid TYPE RANGE OF scarr-carrid.
" $filter as select-options per property (old parameter IT_FILTER_SELECT_OPTIONS is legacy)
DATA(lt_filters) = io_tech_request_context->get_filter( )->get_filter_select_options( ).
IF line_exists( lt_filters[ property = 'CARRID' ] ).
lr_carrid = CORRESPONDING #( lt_filters[ property = 'CARRID' ]-select_options ).
ENDIF.
SELECT carrid, carrname, currcode FROM scarr
WHERE carrid IN @lr_carrid  "empty range = no restriction
INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
ENDMETHOD.

Generic alternative: get_osql_where_clause_convert( ) returns the whole $filter as an ABAP SQL WHERE string with ABAP field names, for WHERE (lv_where). It only works if the entity properties map 1 : 1 to the table fields. (The old IV_FILTER_STRING parameter is the legacy version of this.)

Free-text search – without SQL injection

Never build the WHERE clause by pasting the user's search string into SQL text – a classic SQL injection hole (' OR '1' = '1). Use host variables (bind parameters) instead; if you ever must build dynamic SQL from input, escape it with cl_abap_dyn_prg=>quote( ) / escape_quotes( ).

DATA(lv_search) = io_tech_request_context->get_search_string( ).  "?search=luft*
IF lv_search IS NOT INITIAL.
DATA(lv_pattern) = to_upper( replace( val = lv_search sub = `*` with = `%` occ = 0 ) ).
SELECT carrid, carrname, currcode FROM scarr
WHERE upper( carrid ) LIKE @lv_pattern  "@host variable = bound, not pasted
OR upper( carrname ) LIKE @lv_pattern
INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
ELSE.
DATA(lv_where) = io_tech_request_context->get_osql_where_clause_convert( ).  "from $filter
SELECT carrid, carrname, currcode FROM scarr
WHERE (lv_where)
INTO CORRESPONDING FIELDS OF TABLE @et_entityset.
ENDIF.

$orderby

?$orderby=Currency,CarrierID or ?$orderby=SalesOrder desc. Best: map to ORDER BY in the SELECT; for data already in an internal table use a dynamic SORT. (Older code uses the importing parameter IT_ORDER – the legacy equivalent of get_orderby( ), as IT_FILTER_SELECT_OPTIONS is for $filter.)

DATA(lt_order) = io_tech_request_context->get_orderby( ).  "property + 'asc' / 'desc'
IF lt_order IS NOT INITIAL.
DATA(lt_sort) = VALUE abap_sortorder_tab(
FOR ls_order IN lt_order
( name       = to_upper( ls_order-property )
descending = xsdbool( ls_order-order = 'desc' ) ) ).
SORT et_entityset BY (lt_sort).
ENDIF.

$top, $skip and $inlinecount (client-side paging)

?$skip=20&$top=10 = rows 21–30. $inlinecount=allpages (V2) asks for the total number of rows next to the page (V4: $count=true). Typical bugs to avoid: OFFSET … UP TO in the wrong order, no ORDER BY, and an in-memory variant that deletes the first row when no $skip is given. Correct version, paging pushed to the database:

METHOD salesorderset_get_entityset.
DATA(lv_top)  = CONV i( io_tech_request_context->get_top( ) ).   "0 if not sent
DATA(lv_skip) = CONV i( io_tech_request_context->get_skip( ) ).  "0 if not sent

IF io_tech_request_context->has_inlinecount( ) = abap_true.  "total BEFORE paging
SELECT COUNT(*) FROM vbak INTO @DATA(lv_total).
es_response_context-inlinecount = lv_total.
ENDIF.

SELECT vbeln, auart, vkorg, vtweg, spart, bstnk, kunnr
FROM vbak
ORDER BY vbeln      "OFFSET needs a defined order
INTO CORRESPONDING FIELDS OF TABLE @et_entityset
UP TO @lv_top ROWS  "UP TO 0 ROWS = no limit
OFFSET @lv_skip.
ENDMETHOD.

In-memory alternative (data already read): /iwbep/cl_mgw_data_util=>paging( EXPORTING is_paging = is_paging CHANGING ct_data = et_entityset ) – keeps rows skip+1 … skip+top.

$skiptoken (server-side paging)

Client-side paging: the client decides the page with $skip/$top. Server-side paging: even if the client asks for everything, the server returns one page plus a next link (…/SalesOrderHeaders?$skiptoken=50) which the client follows. Example (it also works for small tables and produces a next link only when more rows exist):

CONSTANTS lc_page_size TYPE i VALUE 50.
DATA(lv_start) = CONV i( io_tech_request_context->get_skiptoken( ) ).  "0 on first call
DATA(lv_rows)  = lc_page_size + 1.  "read one extra row to detect 'more'

SELECT vbeln, auart, kunnr FROM vbak
ORDER BY vbeln
INTO CORRESPONDING FIELDS OF TABLE @et_entityset
UP TO @lv_rows ROWS
OFFSET @lv_start.

IF lines( et_entityset ) > lc_page_size.
DELETE et_entityset INDEX lv_rows.                              "drop the extra row
es_response_context-skiptoken = |{ lv_start + lc_page_size }|.  "next link
ELSE.
CLEAR es_response_context-skiptoken.                            "last page: no next link
ENDIF.

Part 7 – $expand and deep insert

7.1 $expand and the N+1 problem

$expand returns related entities in one round trip: /SalesOrderHeaders?$expand=Items, several navigations ?$expand=Items,Partners. The framework handles it generically – but by calling the item query once per header:

Request

Generic $expand calls

/SalesOrderHeaders?$expand=Items (100 headers)

HEADER_GET_ENTITYSET 1× + ITEMS_GET_ENTITYSET 100× (N+1 SELECTs)

/SalesOrderHeaders('4970')?$expand=Items

HEADER_GET_ENTITY 1× + ITEMS_GET_ENTITYSET 1×

For lists, redefine /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_EXPANDED_ENTITYSET (one entity: GET_EXPANDED_ENTITY) and read headers and items with two SELECTs. Steps: (1) define a deep structure (header + item table whose component name equals the navigation property), usually in MPC_EXT; (2) fill it; (3) copy_data_to_ref( ) into er_entityset; (4) tell the framework which navigation you already filled.

METHOD /iwbep/if_mgw_appl_srv_runtime~get_expanded_entityset.
TYPES BEGIN OF ty_order_deep.
INCLUDE TYPE zcl_zsalesorder_002_mpc=>ts_salesorderheader.
TYPES items TYPE zcl_zsalesorder_002_mpc=>tt_salesorderitem.  "name = navigation property
TYPES END OF ty_order_deep.
DATA lt_deep TYPE STANDARD TABLE OF ty_order_deep WITH EMPTY KEY.

" other entity sets: call super->get_expanded_entityset( ... ) with all parameters + RETURN

SELECT vbeln, kunnr, netwr FROM vbak ORDER BY vbeln INTO TABLE @DATA(lt_head) UP TO 100 ROWS.
IF lt_head IS NOT INITIAL.
SELECT vbeln, posnr, matnr, netwr FROM vbap  "ONE select for all items
FOR ALL ENTRIES IN @lt_head WHERE vbeln = @lt_head-vbeln
INTO TABLE @DATA(lt_item).
ENDIF.
LOOP AT lt_head INTO DATA(ls_head).
APPEND CORRESPONDING #( ls_head ) TO lt_deep ASSIGNING FIELD-SYMBOL(<ls_deep>).
<ls_deep>-items = VALUE #( FOR i IN lt_item WHERE ( vbeln = ls_head-vbeln )
( CORRESPONDING #( i ) ) ).
ENDLOOP.

copy_data_to_ref( EXPORTING is_data = lt_deep CHANGING cr_data = er_entityset ).
APPEND 'ITEMS' TO et_expanded_tech_clauses.  "framework must NOT call ITEMS_GET_ENTITYSET
ENDMETHOD.

7.2 Multi-level expand

Multi-level navigation Order → material plant → description and Order → storage location, with the $expand URIs

Separate navigations with a comma, go deeper with a slash: ?$expand=NP1/MNP1,NP2. The nested types must again use the navigation property names as component names:

TYPES: BEGIN OF ts_material_deep,
matnr   TYPE matnr,
werks   TYPE werks_d,
matdesc TYPE STANDARD TABLE OF ts_matdesc WITH DEFAULT KEY,         "nav MNP1
END OF ts_material_deep,
BEGIN OF ts_order_deep,
aufnr    TYPE aufnr,
rsnum    TYPE rsnum,
matnr    TYPE matnr,
matplant TYPE STANDARD TABLE OF ts_material_deep WITH DEFAULT KEY,  "nav NP1
matsloc  TYPE STANDARD TABLE OF ts_matsloc WITH DEFAULT KEY,        "nav NP2
END OF ts_order_deep.

7.3 Deep insert – create header and items in one POST

  • 1. Create the deep structure and bind it in MPC_EXT → DEFINE:
METHOD define.
super->define( ).
DATA(lo_entity_type) = model->get_entity_type( iv_entity_name = 'SalesOrderHeader' ).
lo_entity_type->bind_structure(
iv_structure_name = '\CLASS=ZCL_ZSALESORDER_002_MPC_EXT\TYPE=TS_ORDER_DEEP' ).
ENDMETHOD.
  • 2. Redefine CREATE_DEEP_ENTITY in DPC_EXT: read the payload into the deep structure, split it into header and item tables, post with a BAPI, put the results (new number) back, copy_data_to_ref( ) into er_deep_entity.
METHOD /iwbep/if_mgw_appl_srv_runtime~create_deep_entity.
DATA ls_order TYPE zcl_zsalesorder_002_mpc_ext=>ts_order_deep.
io_data_provider->read_entry_data( IMPORTING es_data = ls_order ).

" header = ls_order fields, items = ls_order-items  -> e.g. BAPI_SALESORDER_CREATEFROMDAT2
" (no COMMIT WORK here if the request runs inside a $batch change set)
ls_order-vbeln = lv_new_order.  "number returned by the BAPI

copy_data_to_ref( EXPORTING is_data = ls_order CHANGING cr_data = er_deep_entity ).
ENDMETHOD.
  • 3. Test: POST on the header entity set with the items inline – response 201 Created:
POST /sap/opu/odata/sap/ZSALESORDER_002_SRV/SalesOrderHeaders
Content-Type: application/json
X-CSRF-Token: <token from a previous GET>

{ "Kunnr": "1390", "Vkorg": "1010", "Vtweg": "10",
"Items": [ { "Posnr": "10", "Matnr": "MAT-01", "Kwmeng": "2" },
{ "Posnr": "20", "Matnr": "MAT-02", "Kwmeng": "5" } ] }

Part 8 – $batch and change sets

$batch request with read parts and change sets; how a change set runs

$batch packs several requests into one HTTP POST to /sap/opu/odata/sap/<service>/$batch (multipart MIME, each part with its own headers). Fiori apps use it all the time. Write operations are grouped in change sets: an unordered group of create/update/delete operations that is processed as one LUW – all or nothing. A read is never in a change set.

POST /sap/opu/odata/sap/ZEMPLOYEE_002_SRV/$batch
Content-Type: multipart/mixed; boundary=batch_01

--batch_01
Content-Type: multipart/mixed; boundary=changeset_01

--changeset_01
Content-Type: application/http
Content-Transfer-Encoding: binary

PUT EmployeeSet(12) HTTP/1.1
Content-Type: application/json

{"EmployeeId":12,"Name":"Demo User","City":"Pune","Salary":"5000.00","Currency":"EUR"}

--changeset_01
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE EmployeeSet(11) HTTP/1.1

--changeset_01--

--batch_01
Content-Type: application/http
Content-Transfer-Encoding: binary

GET CarrierSet HTTP/1.1

--batch_01--
  • Dates in V2 JSON look like "StartDate": "\/Date(1609459200000)\/" (milliseconds since 1970); V4 uses ISO 8601 (2021-01-01).

Change-set rules

  • No COMMIT WORK inside CREATE/UPDATE/DELETE_ENTITY – the request dumps and nothing is processed.
  • If one operation fails, the whole change set fails and the response contains one error for it.
  • Each change set = one LUW; two change sets = two LUWs. The response status (V2) is 202 with one part per request; in V4, 202 means asynchronous processing.
  • CHANGESET_BEGIN is always called first. Its default allows only one operation per change set – redefine it to allow more. CHANGESET_END is called last; the framework does COMMIT WORK there.
  • Defer mode (7.40 SP09+): set cv_defer_mode = abap_true in CHANGESET_BEGIN. The framework then does not call the single CRUD methods; CHANGESET_PROCESS receives all operations at once (good for one BAPI call), still without commit.
METHOD /iwbep/if_mgw_appl_srv_runtime~changeset_begin.
" empty redefinition = allow several operations in one change set
" cv_defer_mode = abap_true.   -> use CHANGESET_PROCESS instead of single CRUD calls
ENDMETHOD.

METHOD /iwbep/if_mgw_appl_srv_runtime~changeset_end.
COMMIT WORK.  "one commit for the whole change set
ENDMETHOD.

Parallel processing

Read requests outside change sets can run in parallel (default on; switch per service in /IWBEP/CONF_SERVICE or /IWFND/MAINT_SERVICE → Service Implementation → Configuration). Example: 3 GET + 2 POST + 1 PUT + 1 DELETE run as one parallel block of 3 GETs, then each modifying request one after another. The configured maximum is ignored when few work processes are free. Parallelisation works only for local / single-back-end setups, not for multi-origin composition.

$expand vs $batch vs parallel calls

Operation

2 calls

More than 2 calls

Read with association

$expand or parallel calls

$expand

Read without association

Parallel calls

$batch

Update, several LUWs

Asynchronous parallel calls or $batch

$batch

Update, one LUW

$batch (one change set)

$batch (one change set)

Benefits of $batch: fewer client ↔ Gateway round trips (network time), one Gateway ↔ back-end round trip for single-LUW updates, less back-end CPU. Balance it against payload size. SAP's caution: consider not using $batch for many independent reads if parallelisation is off, because Gateway then processes the parts sequentially.

Part 9 – Function imports

A function import is a custom operation that does not fit CRUD-Q: approve / reject / release a sales order, confirm an order, check flight availability, count orders by status. (Function imports exist only in V2; V4 has actions and functions, and RAP uses actions – see RAP › 05 · Business Logic & Messages.)

  • Definition in SEGW: name, return type kind (complex type, entity type, or none), return entity set, cardinality (0..1, 1, 0..n, 1..n), HTTP method, parameters (name, EDM type, length, precision).
  • Method rule: GET must have no side effects (pure read); anything that changes data must be POST (and then needs a CSRF token).
  • Naming: no HTTP verb in the name (ProductsByRating, not GetProductsByRating). If you are inventing CreateX / UpdateX / DeleteX, X should probably be an entity type with normal CRUD.
  • URI: /sap/opu/odata/sap/ZJP_DEMO_SRV/GetFlightNumbers?CarrierId='LH' (parameters as query options).
  • All function imports of a service run through one method, /IWBEP/IF_MGW_APPL_SRV_RUNTIME~EXECUTE_ACTION – so CASE on the name. The result goes back through er_data.
METHOD /iwbep/if_mgw_appl_srv_runtime~execute_action.
DATA: ls_result TYPE zcl_zjp_demo_mpc=>ts_flights,
ls_param  TYPE zcl_zjp_demo_mpc=>ts_getflightnumbers.
CASE io_tech_request_context->get_function_import_name( ).
WHEN 'GetFlightNumbers'.
io_tech_request_context->get_converted_parameters(
IMPORTING es_parameter_values = ls_param ).
ls_result-carrierid = ls_param-carrierid.
SELECT COUNT(*) FROM sflight WHERE carrid = @ls_param-carrierid
INTO @ls_result-flightnos.
copy_data_to_ref( EXPORTING is_data = ls_result CHANGING cr_data = er_data ).
WHEN 'ConfirmOrder'.
" ... POST function import with side effects
ENDCASE.
ENDMETHOD.

Part 10 – Media and streams (files, PDF)

Images, PDFs, Excel, ZIP, audio, video and text files are transported as media entities. Steps:

  • 1. In SEGW mark the entity type as Media (HasStream).
  • 2. In MPC_EXT → DEFINE set the MIME-type property as content type.
  • 3. Redefine the stream methods in DPC_EXT: CREATE_STREAM, GET_STREAM, UPDATE_STREAM, DELETE_STREAM. Inputs: is_media_resource (MIME_TYPE, VALUE = xstring) and iv_slug (file name).

Operation

Request

Upload (create)

POST /ZMEDIA_SRV/MediaSet + header slug: file name + binary body

Download (read)

GET /ZMEDIA_SRV/MediaSet('photo1.png')/$value

Replace (update)

PUT /ZMEDIA_SRV/MediaSet('photo1.png')/$value

Delete

DELETE /ZMEDIA_SRV/MediaSet('photo1.png')/$value

CLASS zcl_zmedia_mpc_ext IMPLEMENTATION.
METHOD define.
super->define( ).
model->get_entity_type( iv_entity_name = 'Media'
)->get_property( iv_property_name = 'Mimetype' )->set_as_content_type( ).
ENDMETHOD.
ENDCLASS.

" ---- DPC_EXT
METHOD /iwbep/if_mgw_appl_srv_runtime~create_stream.
DATA(ls_media) = VALUE zmedia_file( filename = iv_slug
mimetype = is_media_resource-mime_type
value    = is_media_resource-value ).
INSERT zmedia_file FROM @ls_media.
IF sy-subrc = 0.
copy_data_to_ref( EXPORTING is_data = ls_media CHANGING cr_data = er_entity ).
ENDIF.
ENDMETHOD.

METHOD /iwbep/if_mgw_appl_srv_runtime~get_stream.
DATA(lv_key) = VALUE #( io_tech_request_context->get_keys( )[ 1 ]-value OPTIONAL ).
SELECT SINGLE FROM zmedia_file FIELDS value, mimetype
WHERE filename = @lv_key
INTO @DATA(ls_file).
IF sy-subrc = 0.
" file name for the browser's download / inline display
set_header( VALUE #( name  = 'Content-Disposition'
value = |inline; filename="{ lv_key }"| ) ).
DATA(ls_stream) = VALUE ty_s_media_resource( mime_type = ls_file-mimetype
value     = ls_file-value ).
copy_data_to_ref( EXPORTING is_data = ls_stream CHANGING cr_data = er_stream ).
ENDIF.
ENDMETHOD.
" UPDATE_STREAM: MODIFY zmedia_file FROM @ls_media.
" DELETE_STREAM: DELETE FROM zmedia_file WHERE filename = @lv_key.

Typical media scenarios

  • Smart Form as PDF: SSF_FUNCTION_MODULE_NAME → call the generated FM with OTF output → CONVERT_OTF to PDF → return the xstring in GET_STREAM (MIME type application/pdf).
  • Adobe Form as PDF: FP_FUNCTION_MODULE_NAME → FP_JOB_OPEN (output parameters with getpdf = 'X') → generated FM (/1BCDWB/SM…) → FP_JOB_CLOSE → PDF from fpformoutput-pdf → copy_data_to_ref( ). URI: <EntitySet>(Key1='V1',Key2='V2')/$value.
  • Upload a file to DMS: entity with Docu_Name, Docu_Number, Docu_Version, Docu_Type, Docu_Part; in CREATE_STREAM split the slug into name and extension, call BAPI_DOCUMENT_CREATE2, return the document key. Test with POST + header SLUG = file.pdf.

Part 11 – Concurrency: ETag and CSRF token

11.1 Concurrency control

When two users change the same record at the same time, data can become inconsistent. The classic problems: lost update (the second save overwrites the first), dirty read (reading uncommitted data), non-repeatable read (the same read gives different results).

Approach

How it works

Fits OData?

Pessimistic

Lock on read (ABAP: enqueue lock objects, ENQUEUE_/DEQUEUE_ FMs); others must wait. Safe, but slower; deadlocks possible

No – a lock cannot be held across stateless requests

Optimistic

Read without lock; at save time check whether the data changed since it was read (timestamp / hash) and reject stale updates

Yes – this is what the ETag does

Semi-optimistic

Mix: short locks only for selected critical resources

Special cases

Rolling back all operations when one fails is a property of a transaction / LUW, not of optimistic locking.

11.2 ETag

ETag: As ETag Property in SEGW and the framework check (GET_ENTITY compare, then update, 412 or 428)
  • An ETag is a version stamp of an entity – usually the last-changed timestamp, sometimes a hash.
  • Set it at entity type level in SEGW: column As ETag Property (e.g. ChangedAt).
  • GET returns the ETag (response header and __metadata/etag). The client sends it back in If-Match on PUT/PATCH/DELETE. Before calling UPDATE_ENTITY the framework reads the current entity via GET_ENTITY and compares: equal → update runs; different → 412 Precondition Failed.
  • No If-Match on an ETag-enabled entity → 428 ("request is required to be conditional; try using the If-Match header"). If-Match: * skips the check.
  • Another message you may meet: "The Data Services Request could not be completed due to a conflict with the current state of the resource" (seen when If-Match was sent on a GET). Use If-Match only on PUT/PATCH/DELETE and If-None-Match on GET.
  • Conditional read: GET with If-None-Match = current ETag → 304 Not Modified (no body); different → 200 with data and the new ETag.

11.3 CSRF token

Cross-Site Request Forgery: a malicious page makes the user's browser send a modifying request with the user's session cookie. Gateway therefore requires an X-CSRF-Token for every POST, PUT, PATCH, MERGE and DELETE (and for $batch):

  • 1. Any GET (service document, $metadata or an entity) with header X-CSRF-Token: Fetch → the token comes back in the response header (bound to the session cookie).
  • 2. Send it in X-CSRF-Token: <value> on the modifying request, with the same session cookie.
  • Missing or invalid token → 403 Forbidden, "CSRF token validation failed". GET requests never need it. UI5's ODataModel and the Gateway Client handle it automatically.

You do not have to implement GET_ENTITYSET to be able to POST. You only need some GET to fetch the CSRF token.

Sequence: fetch CSRF token and ETag, update with If-Match, stale update gets 412

Part 12 – Errors, testing, tracing, cache

12.1 Raising errors and messages

Exception class

Use for

/IWBEP/CX_MGW_BUSI_EXCEPTION

Business errors: not found, invalid input, BAPI returned an error (4xx)

/IWBEP/CX_MGW_TECH_EXCEPTION

Technical errors: unexpected situation, system problems (500)

Both inherit from /IWBEP/CX_MGW_BASE_EXCEPTION. Messages are collected in the message container (/IWBEP/IF_MESSAGE_CONTAINER): ADD_MESSAGE, ADD_MESSAGE_TEXT_ONLY, ADD_MESSAGES_FROM_BAPI, ADD_MESSAGE_FROM_BAPI, ADD_ERROR_DETAIL.

  • Error in the response body (request fails): raise the exception with the container.
  • Success/warning messages in the response header sap-message (request succeeds): add them with iv_add_to_response_header = abap_true – Fiori shows them as toasts / message popover.
DATA(lo_msg) = mo_context->get_message_container( ).
lo_msg->add_message( iv_msg_type   = /iwbep/cl_cos_logger=>error
iv_msg_id     = 'ZJP_SO'
iv_msg_number = '001'
iv_msg_v1     = CONV #( lv_po_number ) ).
" or copy all BAPI messages: lo_msg->add_messages_from_bapi( it_bapi_messages = lt_return ).

RAISE EXCEPTION NEW /iwbep/cx_mgw_busi_exception( message_container = lo_msg ).  "7.52+
" older syntax: RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
"                 EXPORTING textid = /iwbep/cx_mgw_busi_exception=>business_error
"                           message_container = lo_msg.

12.2 Testing and monitoring transactions

Transaction

Where

Purpose

/IWFND/MAINT_SERVICE

Hub

Activate/maintain services, system aliases, ICF node, soft state

/IWFND/GW_CLIENT

Hub

Gateway Client: send any request, save test cases, replay, CSRF handled

/IWFND/ERROR_LOG

Hub

Error log with context, request/response data, replay, jump to ST22 and the back-end log

/IWBEP/ERROR_LOG

Back end

Back-end error log, jump to the service implementation (DPC code)

/IWFND/TRACES

Hub

Per user / URI prefix: error-log level, performance trace (V2 only), payload trace

/IWFND/STATS

Hub

Request statistics (response times per service)

/IWFND/CACHE_CLEANUP, /IWBEP/CACHE_CLEANUP

Hub / back end

Delete the metadata cache

/IWBEP/CONF_SERVICE

Back end

Service configuration (e.g. $batch parallelisation)

ST22, SAT, ST05

Back end

Dumps; ABAP and SQL trace for slow DPC methods

SICF

Both

ICF node /sap/opu/odata must be active

The Gateway Client is opened from SEGW (Service Maintenance → system → SAP Gateway Client) or /IWFND/MAINT_SERVICE. It replays requests, stores test cases, handles SSO and the CSRF token for you. After a failed call, its Error Log button jumps straight to /IWFND/ERROR_LOG for that request.

  • In an embedded deployment hub and back end are the same system, so both logs are there.
  • Browser testing: append ?sap-ds-debug=true (readable debug view) and sap-statistics=true (timing header).

sap-statistics – where did the time go?

Value

Time spent in

gwhub

Gateway framework on the hub

gwrfcoh

RFC overhead hub ↔ back end (network)

gwbe

Gateway framework in the back end

gwapp

Your service implementation (DPC_EXT)

gwnongw

Non-Gateway components (e.g. Excel conversion)

gwappsum / gwbewait

Only for $batch parallelisation

fw

gwhub + gwbe + gwrfcoh (framework total)

gwtotal

fw + gwapp

12.3 Cache cleanup

If model changes do not show up (new property missing in $metadata), clear the caches – carefully, it costs performance (SAP Note 2319491):

Gateway Client Metadata → Cleanup Cache, and the cache transactions and programs per layer
  • Gateway Client → Metadata → Cleanup Cache (Ctrl+Shift+F12) or Rebuild Cache (current / all services).
  • Transactions /IWFND/CACHE_CLEANUP (hub) and /IWBEP/CACHE_CLEANUP (back end); /UI2/CUST → SAP Fiori → Data Administration → Invalidate Caches.
  • Programs /UI2/INVALIDATE_CLIENT_CACHES, /UI2/INVALIDATE_GLOBAL_CACHES, /UI5/DEL_ODATA_METADATA_CACHE.

12.4 Multi-origin services

One URI can read the same service from several back-end systems: add the segment parameter ;mo – /sap/opu/odata/sap/ZJP_DEMO_SRV;mo/CarrierSet. Each entity gets a property SAP__Origin with the system alias; filter on it: ?$filter=SAP__Origin eq 'ERP_EU'. Requests are processed per back end (no $batch parallelisation).

Part 13 – OData V2 vs V4

Most SEGW services are V2. RAP can publish both; V4 is the recommended version for new RAP UI services.

Topic

OData V2

OData V4

Standard

Microsoft Open Specification

OASIS standard, ISO/IEC 20802

Formats

Atom XML and JSON

JSON only (metadata still XML / CSDL)

Total count

$inlinecount=allpages

$count=true

Search

SAP search= parameter

$search (standard)

Custom operations

Function imports

Actions (change data, POST) and functions (read)

Partial update

MERGE or PATCH

PATCH

Links

$links

$ref

$expand

Simple paths

Nested options: $expand=Items($select=Matnr;$filter=…), $levels

Aggregation

SAP annotations only

$apply (groupby, aggregate)

SAP URL

/sap/opu/odata/sap/<SRV>/

/sap/opu/odata4/sap/<binding>/srvd/sap/<srvd>/0001/

Build with

SEGW, RAP binding (V2)

RAP service binding (V4); SEGW V4 projects only code-based

Part 14 – CDS-based exposure and the modern way (RAP)

Here OData meets ABAP on HANA: when the service reads a CDS view, the SADL (Service Adaptation Description Language) framework turns $filter, $orderby, $top/$skip and $search into SQL that runs in HANA – no paging or filter code in ABAP.

Way to build

Platform

OData

Status

SEGW code-based (Parts 4–12)

All NetWeaver / S/4 releases

V2 (V4 code-based in newer releases)

Still supported; maintain existing services

SEGW + CDS: Map to Data Source / Reference Data Source (SADL)

7.40 SP05+

V2

Read via CDS, no coding; legacy for new development

@OData.publish: true in the CDS view

7.40 SP08 – 7.5x

V2

Obsolete – not for view entities, not in ABAP Cloud

ABAP Programming Model for Fiori (CDS + BOPF, draft from 7.51)

S/4 1610–1809

V2

Legacy – replaced by RAP

RAP: service definition + service binding

7.54+ (S/4HANA 1909+), ABAP environment

V2 and V4

The modern way – see the RAP section

(CAP – Cloud Application Programming Model)

SAP BTP (Node.js / Java)

V2 / V4

Not ABAP; CDS models + JavaScript/Java handlers

SEGW with a CDS view (no code)

  • Map to Data Source: Data Model → Import → DDIC Structure (the CDS view's SQL view) → Service Implementation → entity set → Map to Data Source → type Business Entity, CDS~ZCDS_VIEW → generate, register, test.
  • Reference Data Source: Data Model → right-click → Reference → Data Source → choose the CDS view (and its associations). Entity types, sets and navigation are generated from the CDS model; read-only unless the CDS has a transactional BO behind it.

Legacy – @OData.publish (know it for interviews)

@AbapCatalog.sqlViewName: 'ZCDSODATADB'       " legacy DDIC-based view (see ABAP on HANA › 05 CDS Views)
@OData.publish: true                          " generates service ZCDSODATA_CDS on activation
define view ZCDSODATA as select from vbak {
key vbeln as sono,
erdat,
erzet,
ernam
}
  • Activation generates the service <view>_CDS (MPC, DPC, registration). You still activate it in /IWFND/MAINT_SERVICE and test it in /IWFND/GW_CLIENT.
  • URIs: /sap/opu/odata/sap/ZCDSODATA_CDS/$metadata, /ZCDSODATA (collection), /ZCDSODATA('18317') (single entity), /ZCDSODATA/$count (number of rows). /ZCDSODATA('18317')/$count is not valid – $count works only on collections.
  • With parameters (with parameters p_vkorg : vkorg) two entity sets are generated: ZCDS_ODATA_PARAM(p_vkorg='1010')/Set (navigate via the parameters entity) and ZCDS_ODATA_PARAMSet(p_vkorg='1010',sono='4343').
  • Read-only unless combined with BOPF (@ObjectModel.transactionalProcessingEnabled) – also obsolete.

Modern – RAP service binding (one-liner)

define service ZUI_SalesOrder { expose ZC_SalesOrder as SalesOrder; } + a service binding (OData V4 – UI or Web API) → Publish → Preview. No SEGW, no MPC/DPC, ETag/locking/draft/CSRF handled by the framework. Full details on RAP › 03 · Projection, UI, Access Control & Service; Fiori elements UI annotations (@UI.lineItem, @UI.selectionField) on ABAP on HANA › 05 CDS Views.

Security checklist for any service

  • AUTHORITY-CHECK (or CDS access control) inside the DPC methods – S_SERVICE only allows calling the service.
  • Never build dynamic SQL from $filter or search strings without escaping (Part 6).
  • HTTPS only (STRUST), CSRF protection on (default), no technical users with broad roles for Fiori apps.

Part 15 – Consuming the service in SAPUI5

Fiori apps talk to the back end only through OData – never directly to CDS views, function modules or BAPIs. The UI5 ODataModel reads $metadata, binds controls to entity sets, handles CSRF tokens and groups requests into $batch automatically. Today most apps are Fiori elements (generated from annotations, built with SAP Fiori tools in Business Application Studio or VS Code).

// manifest.json – the service is declared once, the model is created by the component
"sap.app": { "dataSources": { "mainService": {
"uri": "/sap/opu/odata/sap/ZCDSODATA_CDS/", "type": "OData",
"settings": { "odataVersion": "2.0" } } } },
"sap.ui5": { "models": { "": { "dataSource": "mainService" } } }
<!-- XML view: table bound to the entity set -->
<Table id="salesOrders" items="{/ZCDSODATA}" growing="true">
<headerToolbar><Toolbar><Title text="Sales Order Details"/></Toolbar></headerToolbar>
<columns>
<Column><Text text="Sales Order"/></Column>
<Column><Text text="Created On"/></Column>
<Column><Text text="Created At"/></Column>
<Column><Text text="Created By"/></Column>
</columns>
<items>
<ColumnListItem>
<Text text="{sono}"/><Text text="{erdat}"/><Text text="{erzet}"/><Text text="{ernam}"/>
</ColumnListItem>
</items>
</Table>

growing="true" makes the table load pages with $skip/$top automatically.

Legacy UI5 code (recognise it, don't write it)

Old

Today

new sap.ui.model.odata.ODataModel(url) (V1 model)

sap.ui.model.odata.v2.ODataModel or sap.ui.model.odata.v4.ODataModel, declared in manifest.json

sap.ui.view({ viewName: 'views.MyView', type: 'XML' }) in index.html

Component-based app with manifest.json, routing, XMLView.create (async)

data-sap-ui-xx-bindingSyntax="complex"

data-sap-ui-compatVersion="edge", async loading

Theme sap_bluecrystal

sap_horizon

Eclipse SAPUI5 tools + proxy/http/<host> servlet

SAP Business Application Studio / VS Code with Fiori tools and UI5 Tooling (proxy in ui5.yaml)

Freestyle table for simple lists

Fiori elements List Report from annotations

Part 16 – Interview questions

Q1. What is OData, and how is it different from plain REST?

REST is an architectural style. OData is a standardised REST protocol (OASIS, V4 also ISO) that adds a data model ($metadata), standard URI conventions, CRUD-Q semantics and query options ($filter, $expand …), so any client can use any service the same way.

Q2. What are MPC, DPC and the _EXT classes?

MPC defines the model (metadata), DPC provides the data (CRUD-Q methods). Both are regenerated by SEGW, so you redefine methods only in MPC_EXT (deep structures, content type) and DPC_EXT (business logic).

Q3. Which method runs for GET /CarrierSet, GET /CarrierSet('LH'), POST, PUT, PATCH, DELETE?

GET_ENTITYSET, GET_ENTITY, CREATE_ENTITY, UPDATE_ENTITY, PATCH_ENTITY (default → GET_ENTITY + UPDATE_ENTITY), DELETE_ENTITY. Function imports → EXECUTE_ACTION; $value on media → GET_STREAM.

Q4. Which query options need code, and how do you implement paging?

$filter, $orderby, $top, $skip, $inlinecount, $skiptoken and search. Read them from io_tech_request_context and push them into the SELECT (WHERE, ORDER BY, UP TO n ROWS OFFSET m). $skip/$top = client-side paging; $skiptoken = server-side paging with a next link.

Q5. $expand vs navigation – and why redefine GET_EXPANDED_ENTITYSET?

Navigation (/Header('1')/Items) returns only the related entities; $expand returns header and items together. Generic $expand calls the item query once per header (N+1); GET_EXPANDED_ENTITYSET reads all items in one SELECT and sets et_expanded_tech_clauses.

Q6. What is a deep insert?

One POST that creates a header with its items (nested JSON). Bind a deep structure in MPC_EXT DEFINE, redefine CREATE_DEEP_ENTITY, read the payload, post with a BAPI, return the result via copy_data_to_ref.

Q7. Explain $batch and change sets. Where is the COMMIT?

$batch sends many requests in one HTTP call. Write operations go into change sets; each change set is one LUW, all or nothing. Never commit in the CRUD methods – the framework commits in CHANGESET_END. Redefine CHANGESET_BEGIN to allow more than one operation; defer mode uses CHANGESET_PROCESS.

Q8. How does Gateway handle concurrent updates?

Optimistically with an ETag (e.g. ChangedAt marked as ETag property). GET returns it, the client sends it in If-Match; if the record changed meanwhile the update gets 412 Precondition Failed. Missing If-Match → 428. Enqueue locks don't fit stateless OData.

Q9. What is the CSRF token and when do you get 403?

A token fetched with X-CSRF-Token: Fetch on any GET and sent back on every modifying request. Without a valid token Gateway answers 403 "CSRF token validation failed". GET_ENTITYSET is not required for POST.

Q10. Hub vs embedded deployment – which does SAP recommend for S/4HANA?

Embedded (Fiori front-end server inside S/4HANA) is the recommendation since 2020: simpler, no RFC hop. A central hub is for special cases such as one launchpad over many back ends.

Q11. How do you raise errors, and where do you look when a call fails?

Business errors: /IWBEP/CX_MGW_BUSI_EXCEPTION, technical: /IWBEP/CX_MGW_TECH_EXCEPTION, both with the message container. Analyse in /IWFND/ERROR_LOG (hub), /IWBEP/ERROR_LOG (back end), ST22, /IWFND/TRACES, and replay in /IWFND/GW_CLIENT.

Q12. Three ways to expose a CDS view as OData – which is current?

(1) @OData.publish: true – obsolete; (2) SEGW Map to Data Source / Reference Data Source – legacy; (3) RAP service definition + service binding (V2/V4) – the current way. V2 vs V4: V4 is JSON-only, $count=true instead of $inlinecount, actions/functions instead of function imports.

🏠 Start Here · ◀ 07 · Interfaces · 09 · Web Services ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP