Emre Göçmen Blog

Creating and Managing SAP OData Services

5 min. read
1442 views
0 comments

Emre Göçmen

Author

Creating and Managing SAP OData Services

Guide to Creating and Managing OData Services for SAP ABAP Developers

In this comprehensive article, I will present a step-by-step guide on how SAP ABAP developers can effectively create and manage SAP OData services. In modern enterprise applications, OData services play a critical role in providing standard and secure access to SAP data. In subsequent articles, I will cover detailed implementation examples and advanced scenarios.

OData Protocol: Why Is It Important in SAP Integrations?

OData (Open Data Protocol) is an HTTP-based, RESTful protocol that provides a standard method for querying and manipulating data sources. The adoption of OData in SAP systems offers the following advantages:

  • Standardized data access and manipulation
  • Easy integration with Fiori applications, mobile apps, and third-party solutions
  • Native compatibility with SAPUI5/Fiori applications
  • Consistent approach for data exchange with applications outside the SAP system
  • Advanced querying, filtering, and data manipulation capabilities

Steps for Creating OData Services

1. Data Source Selection and Analysis

The first step in creating an OData service is selecting the right data source. Key considerations at this stage include:

Data Source Options:

  • SAP Tables: For direct access to table data (e.g., MARA, VBAK, KNA1)
  • CDS Views: Complex Data Services views, analytically and functionally prepared data
  • Function Modules: Data access through function modules callable via RFC
  • BAPIs: Access to business processes through Business APIs

Data Source Analysis:

  • Data volume and performance requirements
  • Relational data structure and connections
  • Data security and sensitivity level
  • Read/Write requirements (read-only or modifiable data)

As a best practice, using CDS views instead of direct tables is recommended, especially for large data volumes. CDS views provide performance optimization by preprocessing data and facilitate managing complex data relationships.

// Example CDS View Definition
@AbapCatalog.sqlViewName: 'ZMATERIAL_VIEW'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Material Data for OData Service'
define view ZI_Material_CDS as select from mara as Material
  left outer join marc as Plant on Material.matnr = Plant.matnr
{
  key Material.matnr as MaterialNumber,
  Material.mtart as MaterialType,
  Material.matkl as MaterialGroup,
  Material.meins as BaseUnitOfMeasure,
  Plant.werks as Plant,
  Plant.lgort as StorageLocation
}
where Material.mtart = 'FERT';

2. Data Model, Provider, and Entity Set Definition

Defining the data model for an OData service creates the building blocks of the service. The following steps are taken at this stage:

Creating the Data Model:

  • Entity Types: Define the structure of data objects (e.g., Material, Customer)
  • Associations: Connections between entities (e.g., Customer-Order relationship)
  • Complex Types: Composite data structures

Entity Set Definition:

  • Entity sets represent collections in the OData service
  • Define which CRUD (Create, Read, Update, Delete) operations are allowed for each entity set
  • Define navigation paths between entity sets

You can make these definitions through SAP Gateway Builder (Transaction SEGW) or create a data model directly using the CDS-based approach.

// Entity Set Definition Example in Gateway Service Builder
DATA: lo_entity_type TYPE REF TO /iwbep/if_mgw_odata_entity_typ.
DATA: lo_entity_set  TYPE REF TO /iwbep/if_mgw_odata_entity_set.

lo_entity_type = mo_model->create_entity_type( 'Material' ).
lo_entity_type->create_property( 'MaterialNumber' )->set_is_key( ).
lo_entity_type->create_property( 'MaterialType' ).
lo_entity_type->create_property( 'MaterialGroup' ).
lo_entity_type->create_property( 'BaseUnitOfMeasure' ).

lo_entity_set = mo_model->create_entity_set( 'MaterialSet' ).
lo_entity_set->set_entity_type( lo_entity_type ).

3. Determining Query Options and Operations

OData services provide various querying and manipulation features. At this stage, you define which query options users can use and which operations they can perform.

Query Options:

  • $filter: Data filtering (e.g., MaterialType eq 'FERT')
  • $select: Selecting specific fields (e.g., $select=MaterialNumber,MaterialType)
  • $expand: Retrieving related entities (e.g., $expand=Plants)
  • $orderby: Sorting (e.g., $orderby=MaterialNumber desc)
  • $top/$skip: Used for pagination
  • $count: Return total record count

Operations:

  • Functions: Read-only operations (e.g., GetMaterialStock)
  • Actions: Data-modifying operations (e.g., CreatePurchaseOrder)
  • Entity Operations: Standard CRUD operations
// Custom Function Definition Example
DATA: lo_function TYPE REF TO /iwbep/if_mgw_odata_function.

lo_function = mo_model->create_function( 'GetMaterialStock' ).
lo_function->create_parameter( 'MaterialNumber' )->set_type_edm_string( ).
lo_function->create_parameter( 'Plant' )->set_type_edm_string( ).
lo_function->create_result_structure( 'StockData' ).

OData Service Implementation

1. Service Implementation

After defining the data model, you move on to implementing the behavior of the OData service. The following components are developed at this stage:

Data Provider Class (DPC):

  • Code required to retrieve and process data
  • Implementation of CRUD operations
  • Execution of custom functions and actions
// Get_Entity Method Implementation Example
METHOD /iwbep/if_mgw_appl_srv_runtime~get_entity.
  DATA: lv_material_number TYPE matnr,
        ls_material        TYPE zcl_material_mpc=>ts_material.
  
  " Get key field
  io_tech_request_context->get_converted_keys( 
    IMPORTING es_key_values = ls_material ).
  
  lv_material_number = ls_material-materialnumber.
  
  " Retrieve material data
  SELECT SINGLE matnr, mtart, matkl, meins
    FROM mara
    INTO CORRESPONDING FIELDS OF ls_material
    WHERE matnr = lv_material_number.
  
  " Return result
  copy_data_to_ref(
    EXPORTING is_data = ls_material
    CHANGING  cr_data = er_entity ).
ENDMETHOD.

Model Provider Class (MPC):

  • Definition of metadata
  • Technical definitions of entity types and relationships

2. Data Access Controls and Authorization

Security of OData services is a critical component of a successful implementation. A robust authorization mechanism should include:

SAP Authorization Objects:

  • Service-level authorization (S_SERVICE authorization object)
  • Data-level authorization (custom authorization objects)

Authorization Check Implementation:

  • Authority checks in service methods
  • Data access control in CDS views (@AccessControl.authorizationCheck)
  • Separate authorizations for data reading and modification operations
// Authorization Check Example
METHOD check_authority.
  DATA: ls_auth TYPE zsap_material_auth.
  
  ls_auth-actvt = '03'. " Display authority check
  ls_auth-matgr = iv_material_group.
  
  CALL FUNCTION 'AUTHORITY_CHECK_TCODE'
    EXPORTING
      tcode        = 'Z_MATERIAL_DATA'
    EXCEPTIONS
      user_invalid = 1
      OTHERS       = 2.
      
  IF sy-subrc <> 0.
    RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
      EXPORTING
        textid = /iwbep/cx_mgw_busi_exception=>authorization_failure.
  ENDIF.
  
  AUTHORITY-CHECK OBJECT 'Z_MAT_AUTH'
    ID 'ACTVT' FIELD ls_auth-actvt
    ID 'MATGR' FIELD ls_auth-matgr.
    
  IF sy-subrc <> 0.
    RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
      EXPORTING
        textid = /iwbep/cx_mgw_busi_exception=>authorization_failure.
  ENDIF.
ENDMETHOD.

3. Error Handling and Logging

A robust OData service should have comprehensive error handling and logging mechanisms:

Error Handling:

  • Custom error codes and messages
  • Structured responses for business logic errors
  • Proper handling of technical errors

Logging Strategy:

  • Logging of service calls
  • Detailed recording of error conditions
  • Monitoring of performance metrics
// Error Throwing and Logging Example
METHOD handle_material_not_found.
  DATA: lo_message_container TYPE REF TO /iwbep/if_message_container,
        lo_exception         TYPE REF TO /iwbep/cx_mgw_busi_exception.
        
  " Create log
  /iwbep/cl_sb_gen_dpc_rt_util=>log_message(
    EXPORTING
      iv_msg_type   = 'E'
      iv_msg_id     = 'Z_MATERIAL'
      iv_msg_number = '001'
      iv_msg_v1     = iv_material_number
      iv_entity_type= 'Material' ).
      
  " Create and throw error
  lo_message_container = mo_context->get_message_container( ).
  lo_message_container->add_message(
    EXPORTING
      iv_msg_type   = 'E'
      iv_msg_id     = 'Z_MATERIAL'
      iv_msg_number = '001'
      iv_msg_v1     = iv_material_number ).
      
  RAISE EXCEPTION TYPE /iwbep/cx_mgw_busi_exception
    EXPORTING
      message_container = lo_message_container.
ENDMETHOD.

Performance Optimization and Best Practices

1. Performance Optimization Techniques

The performance of OData services directly affects the user experience. The following techniques help you develop high-performance OData services:

Data Access Optimization:

  • Selective data retrieval (only fields needed)
  • Pagination and incremental loading techniques
  • Efficient SQL queries and indexing
  • Analytical optimizations in CDS views (@Analytics.dataExtraction)

Caching Strategies:

  • Client caching with Etag usage
  • SAP Gateway caching
  • Application-level caching for frequently used and infrequently changing data
// ETag Implementation Example
METHOD /iwbep/if_mgw_appl_srv_runtime~get_entity.
  " ... Other code
  
  " Create ETag (e.g., based on last modified date)
  lv_etag = |{ ls_material-last_changed_date }{ ls_material-last_changed_time }|.
  
  " Set ETag
  io_tech_request_context->set_etag_response( lv_etag ).
  
  " ... Other code
ENDMETHOD.

2. Delta Query Support

For large datasets, a delta querying mechanism provides a significant performance advantage. This allows retrieving only data that has changed since the last query operation.

// Delta Token Implementation
METHOD /iwbep/if_mgw_appl_srv_runtime~get_entityset.
  DATA: lv_delta_token TYPE string,
        lt_delta_key   TYPE STANDARD TABLE OF /iwbep/s_mgw_delta_key.
        
  " Check delta token
  io_tech_request_context->get_delta_token(
    IMPORTING
      ev_delta_token = lv_delta_token ).
      
  IF lv_delta_token IS NOT INITIAL.
    " Retrieve delta data (based on last change date)
    " ...
    
    " Create new delta token
    lv_new_token = |{ sy-datum }{ sy-uzeit }|.
    io_tech_request_context->set_delta_token_response( lv_new_token ).
  ELSE.
    " Retrieve all data
    " ...
  ENDIF.
ENDMETHOD.

3. Managing Large Data Volumes

When working with large data volumes, the following techniques are recommended:

  • Server-side pagination (instead of $top and $skip)
  • Data streaming techniques
  • Query optimization (effective use of WHERE conditions)
  • Parallel processing techniques

Testing and Deployment of OData Services

1. Test Strategy

A comprehensive testing strategy ensures the reliability of your OData services:

Unit Tests:

  • Testing each CRUD operation
  • Testing custom functions and actions
  • Testing error conditions

Integration Tests:

  • Testing with different clients (SAP UI5, mobile applications, third-party systems)
  • Authorization and security tests
  • Performance and load tests

Testing Tools:

  • SAP Gateway Client (Transaction /IWFND/GW_CLIENT)
  • API testing tools like Postman
  • Automated test scripts (ABAP Unit)

2. Deployment and Maintenance

The following steps should be followed for the deployment and subsequent maintenance of OData services:

Deployment Operations:

  • Service registration and activation (Transaction /IWFND/MAINT_SERVICE)
  • Transport and version management strategy
  • Documentation and usage guides

Monitoring and Maintenance:

  • Monitoring service performance (Transaction /IWFND/TRACES)
  • Analysis of usage statistics
  • Regular optimization and update plan

Real-World Applications and Use Cases

OData services can be used in various enterprise scenarios:

Fiori Applications:

  • Access to SAP data with user-friendly interfaces
  • Mobile-first business processes
  • Analytical and reporting applications

System Integrations:

  • SAP data integration with third-party applications
  • Data exchange with IoT (Internet of Things) devices
  • Hybrid cloud scenarios

Business Process Innovations:

  • Digital transformation projects
  • Mobile workflows
  • Customer and supplier portals

Conclusion and Next Steps

SAP OData services have become an indispensable technology for modern integration scenarios and user experience. The comprehensive guide presented in this article will help ABAP developers create secure, high-performance, and scalable OData services.

In my upcoming articles, I will focus more deeply on the following topics:

  • Advanced OData features and OData V4 implementation
  • OData and SAP Fiori integration scenarios
  • Optimization techniques for large data volumes
  • Security best practices for OData services
  • Concrete example projects and real-world applications

OData services are one of the most effective ways to open your SAP systems to the modern digital world. Properly designed and implemented OData services can bring agility, efficiency, and innovative business processes to your enterprise.

You can use the comments section for questions or contributions, or contact me directly.


This article has been prepared for SAP ABAP developers, taking into account the latest SAP technologies and best practices. The code examples and techniques in the article have been adapted from real projects and should be thoroughly tested before being applied to production systems.

Comments

0

You must be logged in to comment.

No comments yet.

Be the first to comment.

Emre Göçmen

Author & Developer

I write about my experiences as a SAP ABAP & Full Stack developer.

Category

SAP

SAP

Subscribe to Newsletter

Subscribe to my newsletter to get notified about new articles.