Category: ABAP

ABAP

  • Call Transaction Method in SAP BDC

    Introduction

    A Call transaction is a very simple report program. Once you execute and come out of the program, there is no log to cross check.

    Syntax:

    CALL TRANSACTION <transaction code> USING <it_bdcdata>
    MODE ‘A/E/N’
    UPDATE ‘A/S/L’
    MESSAGE INTO <it_msg_details>.

    Here, it_bdcdata represents the internal table that has instructions for one time execution of the t-code. This is the same table that we discussed in the section “SAP BDC Technical Details”. So, this internal table at one moment will hold instructions for only one record.

    Here, we have three different options for MODE. The modes determine the control over screen display.

    • A: It means, while execution of the program, all screens will be displayed. It is best suited for testing purpose as it is a foreground testing.
    • N: It means, while execution of the program, no screens will be shown even in case of success or error. This is best suited for production execution as it is a background job.
    • E: It means, the screens with message will be displayed every time there is an error. This is also used for testing purpose, in case SY-SUBRC fails for method N, and you are not able to identify the position of error.

    Here, we have three different options for UPDATE. The update command signifies Create, Update and delete operation over table/database. And, this UPDATE command provided the control over the sequence of database operations. Like, if data will be saved for all external file one by one, or in parallel.

    • A: It means Asynchronous. It means irrespective of the face that first set of data was processed and data was being saved in db, the next round of data process will start and not wait for the completion of first. This also means for large amount of data, the speed of the program will be faster in this mode. But, also there is a very rare chance of getting errors.
    • S: It means Synchronous. It means, every time the command CALL TRANSACTION is executed, until the data is saved in table and a success SY-SUBRC comes, it will not execute the CALL TRANSACTION for the next set of data. It is preferred in Production mode, as it is error free (Although slower).
    • L: It means Local. This is the command which signifies that the update for entire data (whole excel or csv or txt) will be executed at once, in the end, and only after the “COMMIT WORK” statement. The use case for Local Update or Update Function Module is where you either want all data to updated or none. The best use case is updating header and detail, and if detail or header fails, none of these tables will be updated. You can read more about it here.

    Here, it_msg_details saves all the messages that are produced over the screen (success, warning, information or error).

    Call Transaction Method Flow

    As you can see in the above design flow, the excel will be converted into internal table, and then BDC Codes (CALL TRANSACTION) will be called where <it_bdcdata> will be in form of BDCDATA format with various fields such as Program, DYNPRO, etc including field and value holding data of first row of the excel. Once the database process completes, the next data of the excel will be processed and so on.

    Steps to upload data in SAP system using BDC

    To understand the above process, we will show case a simple example where we will:

    1. Create multiple tables for Employee Data that can be created using a report.

    We have created these tables: zBarry_emp (for employee basic information), zBarry_sal (for employee Salary information) and zBarry_add (for employee address details). The fields are as shown below:

    zBarry_emp

    Field Name Field Type
    EMPID (Key) INT4
    FNAME CHAR20
    LNAME CHAR20
    PHONE CHAR20

    zBarry_sal

    Field Name Field Type
    EMPID (Key) INT4
    SALARY CHAR20

    zBarry_add

    Field Name Field Type
    EMPID (Key) INT4
    CITY CHAR20
    PIN CHAR20
    STATE CHAR20
    COUNTRY CHAR20

    2. The report will be able to take many fields as input.

    Now, we will create a report ZBARRYEMP_REPORT to take multiple inputs via screen and save them in the above tables. The code of the same is shown below:

    REPORT ZBARRYEMP_REPORT.
    Data: ls_emp type ZBARRY_EMP,
          ls_sal type zbarry_sal,
          ls_add type zbarry_add,
          lv_MSG type char20.
    
    PARAMETERS: p_empid TYPE int4,
    p_fname type char20,
    p_lname type char20,
    p_phone type char20,
    p_salary type char20,
    p_city type char20,
    p_pin type char20,
    p_state type char20,
    p_con type char20.
    
    " mapping for Employee Info
    ls_emp-empid = p_empid.
    ls_emp-fname = p_fname.
    ls_emp-lname = p_lname.
    ls_emp-phone = p_phone.
    
    
    " mapping for Employee Salary
    ls_sal-empid = p_empid.
    ls_sal-salary = p_salary.
    
    " mapping for Employee Address
    ls_add-empid = p_empid.
    ls_add-city = p_city.
    ls_add-pin = p_pin.
    ls_add-state = p_state.
    ls_add-country = p_con.
    
    " SQL Operations.
    INSERT ZBARRY_EMP FROM ls_emp.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
     INSERT ZBARRY_sal FROM ls_sal.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
      INSERT ZBARRY_add FROM ls_add.
    If Sy-subrc = 0.
    lv_MSG = 'Create is successful'.
    else.
      lv_MSG = 'Create Failed'.
           Endif.
    
           if lv_MSG EQ 'Create Failed'.
             MESSAGE lv_MSG TYPE 'E' DISPLAY LIKE 'E'.
               ENDIF.

     

    Output:

    ABAP Report for BDC

    3. Then, we will create a t-code for our report.

    We will create a T-code “ZMYTCODE” using SE93 for our report “ZBARRYEMP_REPORT”.

    Tcode for BDC

    Steps to Record a transaction code using BDC

    4. Thereafter, we will run a BDC recording (using T-Code SHDB) and get BDCDATA from that recorder.

    Step 1. Go to t-code SHDB and click on “New Recording”

    SHDB New Recording

    Step 2: Provide T-Code, any name for recording and set update mode as “Synchronous”.

    Create Recording SHDB

    Step 3: It will open your Report. Now, provide all the data, and press execute.

    BDC Recorder

    Now click, back to see your BDCDATA, for our example it looks like this:

    INDEX PROGRAM DYNPRO DYNBEGIN FNAM FVAL
    1 T ZMYTCODE
    2 ZBARRYEMP_REPORT 1000 X
    3 BDC_CURSOR P_CON
    4 BDC_OKCODE =ONLI
    5 P_EMPID 12
    6 P_FNAME Rudra
    7 P_LNAME Pandey
    8 P_PHONE 99999999
    9 P_SALARY INR 9999999
    10 P_CITY Mughalsarai
    11 P_PIN 232101
    12 P_STATE Uttar Pradesh
    13 P_CON India
    14 ZBARRYEMP_REPORT 1000 X
    15 BDC_OKCODE /EE
    16 BDC_CURSOR P_EMPID

    Now, here you can see that all our entered data is also recorded in the recording.

    Here BDC_OKCODE “=ONLI” is for our “Execute” button, and BDC_OKCODE = “/EE” is showcasing that we pressed back. We will use the code until we press execute.

    You can test your recording by clicking “Process” button:

    Test BDC

    While testing, do change data with a new set. Before exiting, you must save your recording.

    Steps to Create a BDC Program

    5. Now, we will create a program that accepts excel input and convert that excel into an internal table.

    Step 1: Create a new ABAP report “ZBARRYEMP_BDC” using t-code SE38.

    Step 2: Create the following:

    • local structure of type “bdcdata” where we will map our excel data with bdcdata that we recorded earlier
    • local internal table of type “bdcdata” where we will push our local structure that we have created above
    • local structure and internal table of type “bdcmsgcoll” where we will save the message for every call that we make to the recording
    • local internal table and local structure to hold excel data that we will upload

    We have created the following:

    REPORT ZBARRYEMP_BDC.
    " local structure with combined fields of emp table, salary table and address table
    TYPES: BEGIN OF ls_emp,
      empid type INT4,
      fname type char20,
      lname type char20,
      phone type char20,
      salary type char20,
      city type char20,
      pin type char20,
      state type char20,
      country type char20,
      END OF ls_emp.
    
    DATA: ls_bdcdata TYPE bdcdata,
          ls_msg type bdcmsgcoll.
    
    DATA: lt_bdcdata TYPE TABLE OF bdcdata,
          lt_bdcmsg TYPE TABLE OF bdcmsgcoll,
          lt_bankdata TYPE TABLE OF ls_emp.

     

    Step 3: Now, we will import the excel data using Function Module ‘TEXT_CONVERT_XLS_TO_SAP’ and push it to our internal table it_empdata. You can read more about Excel upload in ABAP here.

    " Uploading Excel and converting it into Interna Table
    TYPE-POOLS truxs.
    PARAMETERS p_file TYPE rlgrap-filename.
    
    DATA : t_upload  TYPE STANDARD TABLE OF ls_emp,
           wa_upload TYPE ls_emp,
           it_type   TYPE truxs_t_text_data.
    
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
        EXPORTING
          field_name = 'p_file'
        IMPORTING
          file_name  = p_file.
    
    START-OF-SELECTION.
      CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
        EXPORTING
          i_tab_raw_data       = it_type
          i_filename           = p_file
        TABLES
          i_tab_converted_data = t_upload[]
        EXCEPTIONS
          conversion_failed    = 1
          OTHERS               = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 .
      ENDIF.
    
    END-OF-SELECTION.

     

    Step 4: Now in a loop we will keep pushing the bdcdata parameters that is

    • PROGRAM, DYNPRO, DYNBEGIN: These will remain constant for one screen (in our case, constant for whole program as we have only one screen). These will be taken from the BDCDATA that we have generated i.e.
    ZBARRYEMP_REPORT 1000 X
    • FNAM, FVAL: These will hold the key and values (In our case, the keys are the parameters that we used for input in our ABAP report “ZBARRYEMP_REPORT” while the values will be taken from excel upload.
    • The first two fields for a screen are always BDC_CURSOR  and BDC_OKCODE.  The value can be retrieved from the generated BDCDATA. In this case, the values are ‘P_CON ‘ and ‘=ONLI’, respectively.

     

    Step 5: Once the values are taken as per BDCDATA structure, we call the “CALL TRANSACTION” statement. These entire statements will be looped until the operation finishes for the entire excel data.

    The syntax for CALL TRANSACTION is:

    CALL TRANSACTION <transaction code> USING <it_bdcdata>
    MODE ‘A/E/N’
    UPDATE ‘A/S/L’
    MESSAGES INTO <it_msg_details>.

     

    For our example, the above value will become:

    CALL TRANSACTION ‘ZMYTCODE’ USING lt_bdcdata
    MODE ‘N’
    UPDATE ‘S
    MESSAGES INTO lt_bdcmsg.

     

    Step 6: Now upload an excel file with the given format. In our example, we have an excel as shown below:

    Excel format BDC

    Note: Do not include the header. The excel should look like this:

    Excel with Data for BDC

    Once you are done with the ABAP Changes, then run the report, upload the excel file and once the ABAP Report executes, check the table to see if all the records are uploaded or not.

    ABAP Code for BDC Program

    REPORT ZBARRYEMP_BDC.
    " local structure with combined fields of emp table, salary table and address table
    TYPES: BEGIN OF ls_emp,
      empid type int2,
      fname type char20,
      lname type char20,
      phone type char20,
      salary type char20,
      city type char20,
      pin type char20,
      state type char20,
      country type char20,
      END OF ls_emp.
    
    DATA: ls_bdcdata TYPE bdcdata,
          ls_msg type bdcmsgcoll.
    
    DATA: lt_bdcdata TYPE TABLE OF bdcdata,
          lt_bdcmsg TYPE TABLE OF bdcmsgcoll,
          lt_empdata TYPE TABLE OF ls_emp.
    
    " Uploading Excel and converting it into Interna Table
    TYPE-POOLS truxs.
    PARAMETERS p_file TYPE rlgrap-filename.
    
    DATA : t_upload  TYPE STANDARD TABLE OF ls_emp,
           wa_upload TYPE ls_emp,
           it_type   TYPE truxs_t_text_data.
    
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
      CALL FUNCTION 'F4_FILENAME'
        EXPORTING
          field_name = 'p_file'
        IMPORTING
          file_name  = p_file.
    
    START-OF-SELECTION.
      CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP'
        EXPORTING
          i_tab_raw_data       = it_type
          i_filename           = p_file
        TABLES
          i_tab_converted_data = t_upload[]
        EXCEPTIONS
          conversion_failed    = 1
          OTHERS               = 2.
      IF sy-subrc <> 0.
        MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                WITH sy-msgv1 sy-msgv2 .
      ENDIF.
    
      " Loop the above table t_upload[] data until all data is uploaded via BDC
      LOOP AT t_upload into wa_upload.
    * Screen 1 - Field 1 is always BDC_CURSOR
    ls_bdcdata-PROGRAM = 'ZBARRYEMP_REPORT'.
    ls_bdcdata-DYNPRO = '1000'.
    ls_bdcdata-DYNBEGIN = 'X'.
    ls_bdcdata-fnam = 'BDC_CURSOR'.
    ls_bdcdata-fval = 'P_CON'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 2 - Always BDC_OKCODE
    ls_bdcdata-fnam = 'BDC_OKCODE'.
    ls_bdcdata-fval = '=ONLI'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 3
    ls_bdcdata-fnam = 'P_EMPID'.
    ls_bdcdata-fval = wa_upload-empid.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 4
    ls_bdcdata-fnam = 'P_FNAME'.
    ls_bdcdata-fval = wa_upload-fname.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 5
    ls_bdcdata-fnam = 'P_LNAME'.
    ls_bdcdata-fval = wa_upload-lname.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 6
    ls_bdcdata-fnam = 'P_PHONE'.
    ls_bdcdata-fval = wa_upload-phone.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 7
    ls_bdcdata-fnam = 'P_SALARY'.
    ls_bdcdata-fval = wa_upload-salary.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 8
    ls_bdcdata-fnam = 'P_CITY'.
    ls_bdcdata-fval = wa_upload-city.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 9
    ls_bdcdata-fnam = 'P_PIN'.
    ls_bdcdata-fval = wa_upload-pin.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 10
    ls_bdcdata-fnam = 'P_STATE'.
    ls_bdcdata-fval = '=ONLI'.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    
    * Screen 1 - Field 10
    ls_bdcdata-fnam = 'P_CON'.
    ls_bdcdata-fval = wa_upload-country.
    APPEND ls_bdcdata to lt_bdcdata.
    CLEAR ls_bdcdata.
    ENDLOOP.
    
    "Call BDC Transaction
    CALL TRANSACTION 'ZMYTCODE' USING lt_bdcdata MODE 'A' UPDATE 'S' MESSAGES INTO lt_bdcmsg.
    CLEAR lt_bdcdata.
    
    END-OF-SELECTION.

     

    Output

    BDC Program Output

  • BDC (Batch Data Communication) in SAP ABAP: Complete Guide

    Introduction

    In SAP environment, suppose you need to upload a data from an external source like an excel sheet. You have a program for the upload already in the system. You will therefore, visit the program or transaction, and then simply open the file location, upload the file, check for errors and that’s it.

    Therefore, these will be the steps that you will follow for a file upload. Suppose, you have Ten Thousand files to be uploaded via the same program. Wouldn’t it be a tedious job? SAP knew it, and hence created something called SAP BDC, which records your upload steps and automatically replicate it for next sets or batches of data. In this article, we will learn everything about SAP BDC with simple examples.

    What is BDC – Batch Data Communication in SAP ABAP?

    SAP BDC stands for Batch Data Communication. It was renamed by SAP to Batch Input, about 20 years ago. Still, the famous name i.e. BDC is used to refer it.

    In terms of definition, Batch Input or BDC are the sets of methods provided by SAP to transfer/migrate data from other SAP or Non SAP Systems.

    Why we need BDC?

    We need Batch Input of BDC for the following reasons:

    1. Data conversion or migration from Non SAP systems (e.g. csv, excel, text) to SAP Systems (e.g. SAP Table). It mostly happen for a new development (Master Data Migration) and SAP Upgradation.

    BDC Process Flow

    2. Automate daily tasks of a user. If the daily task of user is to upload data from a 3rd party to SAP System via T-Code.

    SAP BDC Design

    If you are asked to upload a set of data into database, in single table, you would quickly create a report, with file uploader, and use SQL to push that data into required table. But, if you are asked to upload hundred columns of data into tons of tables, based upon various conditions, based upon a T-Code, then it will be a tedious job.

    BDC solves our problem, by cutting our second task. Our part is to just push the excel until the transaction screen, and the rest is taken care.

    In below image, the usual case would be that you will open a t-code, enter required input and click save. In case of BDC, it creates recording of your upload process and give you the code of the recording. Using the provided code, you can create a program to upload excel and pass the data to that BDC recoded code, and the rest is taken care automatically.

    BDC Design

    SAP BDC Technical Details

    Every time you record your screen, a few fields are auto generated (called BDCDATA) as below:

    • Program Name (PROGRAM): The name of program for the transaction
    • Screen Number (DYNPRO): The screen number is auto generated
    • Field Name (s) [FNAM]: The field name for which value was provided. In case of multiple field, it will be repeated
    • Field Value (s) [FVAL]: For all the above fields, the entered value is recorded here
    • OK Code [BDC_OKCODE]: The event that occurred during recording. Either you pressed Enter or Clicked a button, the code for the same will be captured here
    • DYNBEGIN: This indicates that the new screen has started
    • BDC_CURSOR: It saves the current position of the cursor

    A common example based upon above structure is shown below:

    INDEX PROGRAM DYNPRO DYNBEGIN FNAM FVAL
    1 SAPMM07M 400 X
    2 BDC_CURSOR RM07M-LGORT
    3 BDC_OKCODE /00
    4 MKPF-BLDAT 22.12.2022
    5 MKPF-BUDAT 22.12.2022
    6 RM07M-BWARTWA 413
    7 RM07M-WERKS 2010
    8 RM07M-LGORT HRSL
    9 RM07M-WVERS2 X
    10 SAPMM07M 410 X
    11 BDC_CURSOR MSEG-UMLGO
    12 BDC_OKCODE /00
    13 MSEG-MATNR SLBW
    14 MSEG-ERFMG 20
    15 MSEG-ERFME to
    16 MSEG-WERKS 2010
    17 MSEG-LGORT HRSL
    18 MSEG-CHARG A693264
    19 MSEG-UMLGO HRSL

    You do not have to understand the above code, just check the field names discussed before and how they appear in the BDCDATA generated. You can even check the structure “BDCDATA” in SE11. Also, you can check another SE11 structure BDCMSGCOLL which is used for Collecting messages in the SAP System.

    Note: The recording by SHDB that we will discuss later is a client dependent process, and it has to be saved as a local file in desktop and has to be uploaded the same in to other systems.

    SAP BDC Transaction Codes (Tcode)

    The following T-Codes are used with respect to BDC or Batch Input:

    T-Code Use
    SM35 It is used to run Batch Input Sessions
    SHDB It is used to record a BDC (Batch Input) Session
    BDCUPDATE It is used to check updates in Batch Input

     

    Apart from these, you can find all other relevant T-Codes here.

    Methods of Batch Input or Types of BDC Call

    Now, we have a basic idea of BDC and its terminologies. Now, we will learn how to start with a BDC process. There are two different ways of doing the same. These are:
    1. Call Transaction Method
    2. Classical Batch Input Method or BDC Session Method

    We have discussed each individually in a different article (click them) and created respective programs.

    Error handling in SAP BDC

    There are many reasons due to which your BDC might fail; we will discuss a few issues and errors that are very generic to BDC.

    Important Guidelines for SAP BDC

    Following are the important guidelines in terms of SAP BDC:

    • BDC works by executing t-codes using data uploaded, hence all the data and logic validations are not done in BDC programs but are done in individual t-codes (the reports running behind those t-codes).
    • BDC is suitable for very large amount of data.
    • BDC should be tested in mode A and E, and should be deployed in production in mode N.
    • For different screens you must update the DYNPRO number, else the program will fail.
    • Every time you press enter or click, it is recorded in the BDCDATA. You should write code for every event in your BDC Program.

    Why BDC is not recommended

    BSC is closely associated with screens and t-codes. Every new release of a product in SAP, there might be chance of enhancing the screen; hence making the old BDC becomes non-applicable. Hence, BDC is not recommended for longer run.

    Alternative to SAP BDC

    The alternative to SAP BDC is SAP BAPI. There are several BAPIs that can replace the data transfer of a particular transaction. Even SAP recommends using BDC only in case there are no BAPIs for a t-code.

  • SAP ABAP RAP CRUD Operation in S/4HANA Cloud [Managed]

    Preface – This post is part of the SAP ABAP RAP series.

    Introduction

    SAP RAP stands for Restful Application Programming. It is the newest framework by SAP to develop projects using ABAP and S/4HANA. In this project, we will learn simple steps to learn how to create a program on SAP ABAP RAP CRUD Operation in S/4HANA Cloud [Managed].

    Types of Projects using SAP RAP

    • S/4HANA On Premise [Managed]
    • S/4HANA Cloud [Managed]
    • S/4HANA On Premise [Managed with Save]
    • S/4HANA Cloud [Managed with Save]
    • S/4HANA On Premise [Unmanaged]
    • S/4HANA Cloud [Unmanaged]

    ABAP RAP Configuration Flow

    ABAP RAP Configuration Flow

    ABAP RAP Data Flow

    ABAP RAP Data Flow

    Project Structure

    Here is what we will do

    • Create ABAP Table
    • Create CDS Views
    • Add Metadata
    • Create Behaviour Definition
    • Create Service Definition
    • Create Service Binding
    • Test the RAP Fiori Application

    RAP Project Structure

    Steps to Follow

    1. Create a Z table => Populate Table
    2. On top of the table, create an Interface CDS View => Metadata Extension
    3. On top of your basic or Interface CDS view, create a root view (Consumption View)
    4. On top of the CDS view, create Behaviour Definition
    5. On top of the Consumption CDS view, create a Service Definition
    6. On top of Service Definition, we add Service Binding
    7. Activate and Click Publish

     

    Code

    1. Table

    @EndUserText.label : 'Employee Data'
    @AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
    @AbapCatalog.tableCategory : #TRANSPARENT
    @AbapCatalog.deliveryClass : #A
    @AbapCatalog.dataMaintenance : #RESTRICTED
    define table zemp_data {
    
      key client : abap.clnt not null;
      key empid  : abap.int4 not null;
      fname      : abap.sstring(20);
      lname      : abap.sstring(20);
      phone      : abap.sstring(20);
    
    }

    Program to Upload data via Class:

    CLASS zemp_data_rudra DEFINITION
      PUBLIC
      FINAL
      CREATE PUBLIC .
      PUBLIC SECTION.
      Interfaces if_oo_adt_classrun.
    METHODS
     UPLOAD_EMP_DATA.
      PROTECTED SECTION.
      PRIVATE SECTION.
    ENDCLASS.
    
    
    
    CLASS zemp_data_rudra IMPLEMENTATION.
    METHOD : UPLOAD_EMP_DATA.
    Data: lt_type_emp TYPE STANDARD TABLE OF Zemp_data.
          lt_type_emp = Value #( ( empid = 1
         fname = 'Rudra'
         lname = 'Pandey'
         phone = '999999')
         ( empid = 2
         fname = 'Deepak'
         lname = 'Ram'
         phone = '888888')
         ).
    
    INSERT Zemp_data from TABLE @lt_type_emp.
    ENDMETHOD.
    METHOD if_oo_adt_classrun~main.
    UPLOAD_EMP_DATA( ).
    ENDMETHOD.
    
    
    ENDCLASS.

     

     

    2. Interface CDS View

    @AbapCatalog.sqlViewName: 'ZV_EMPDATA'
    @AbapCatalog.compiler.compareFilter: true
    @AbapCatalog.preserveKey: true
    @AccessControl.authorizationCheck: #NOT_REQUIRED
    @EndUserText.label: 'Interface View'
    define root view Z_I_EMP_DATA as select from zemp_data {
        key empid,
        fname,
        lname,
        phone
    }
    

     

    3. Metadata Extension

    @Metadata.layer: #CORE
    @UI: { 
    headerInfo: { 
    typeName: 'Employee Data',
    title: { type: #STANDARD, label: 'Employee Data', value: 'empid'}
    }
    }
    annotate view Z_C_EMP_DATA
        with 
    { 
    @UI.facet: [{ id: 'EmpView',
    purpose: #STANDARD,
    type: #IDENTIFICATION_REFERENCE,
    label: 'Employee Data',
    position: 10 }]
    
    @UI: { lineItem:[{
    position: 10,
    importance: #HIGH,
    label:'Employee ID'}],
    identification: [{ position: 10}],
    selectionField: [{ position: 10}]
    }
      Empid;
      
      
      @UI: { lineItem:[{
    position: 20,
    importance: #HIGH,
    label:'First Name'}],
    identification: [{ position: 20}],
    selectionField: [{ position: 20}]
      }
      Fname;
      
    @UI: { lineItem:[{
    position: 30,
    importance: #HIGH,
    label:'Last Name'}],
    identification: [{ position: 30}],
    selectionField: [{ position: 30}]
      }
      Lname;
      
      @UI: { lineItem:[{
    position: 40,
    importance: #HIGH,
    label:'Phone Number'}],
    identification: [{ position: 40}],
    selectionField: [{ position: 40}]
      }
    
      Phone;
        
    }

     

    4. Consumption View

    @AccessControl.authorizationCheck: #NOT_REQUIRED
    @EndUserText.label: 'Root View for Employee Data'
    @Search.searchable: true
    @Metadata.allowExtensions: true
    define root view entity Z_C_EMP_DATA provider contract transactional_query
     as projection on Z_I_EMP_DATA as EmpView 
    {   @EndUserText.label: 'ID'
        key empid as Empid,
         @EndUserText.label: 'First Name'
         @Search.defaultSearchElement: true
        fname as Fname,
         @EndUserText.label: 'Last Name'
        lname as Lname,
         @EndUserText.label: 'Phone Number'
        phone as Phone
    }
    

     

    5. Behaviour Definition on Interface CDS View

    managed;// implementation in class zbp_i_emp_data unique;
    //strict ( 2 ); //Uncomment this line in order to enable strict mode 2. The strict mode has two variants (strict(1), strict(2)) and is prerequisite to be future proof regarding syntax and to be able to release your BO.
    
    define behavior for Z_I_EMP_DATA  alias EmpView
    implementation in class zbp_i_emp_data unique
    persistent table ZEMP_DATA
    lock master
    //authorization master ( instance )
    //etag master <field_name>
    {
    
    field(mandatory) empid, fname, lname, phone;
    create;
    update;
    delete;
    //static function DefaultForCreate result [1] $self;
    
    mapping for Zemp_data
    {
    empid = empid;
    fname = fname;
    lname = lname;
    phone = phone;
    }
    }

     

    6. Behaviour Definition on Consumption CDS View

    projection;
    //strict ( 2 ); //Uncomment this line in order to enable strict mode 2. The strict mode has two variants (strict(1), strict(2)) and is prerequisite to be future proof regarding syntax and to be able to release your BO.
    
    define behavior for Z_C_EMP_DATA alias EmpView
    use etag
    {
      use create;
      use update;
      use delete;
    }

     

    7. Service Definition

    @EndUserText.label: 'Service Definition for Employee Data'
    define service ZEMP_SRV {
      expose Z_C_EMP_DATA;
    }

     

    8. Service Binding

    Service Binding

    9. Fiori Application

    A. List Page

    Fiori List View

    B. Object Page

    Fiori Object View

    Tutorial Video

    You can watch the video below to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=oAphoD3o90s[/embedyt]
  • Delete an Entity using SAP OData

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    Delete operation is used when you want to remove a record from the database. For example, you have created one quotation and now you no longer want it. So you will delete the quotation using the DELETE request.

    This article describes the step-by-step procedure to implement and test delete operation in SAP OData.

    Context

    Delete entity can be implemented by redefining the DELETE_ENTITY method.

    Procedure

    1. Open *DPC_EXT class artifact of OData and redefine *DELETE_ENTITY method.
    2. Reimplement the delete method.
      Delete an Entity using SAP OData
      IT_KEY_TAB holds the values from the frontend.
    3. Activate the class and register the service.
    4. Execute and test the OData.
      1. Select Entity set
      2. Select DELETE option
      3. Add the key value to be deleted in the request URL
      4. Execute the request
        Delete an Entity using SAP OData Testing
      5. Status 204 represents success.
      6. Verify in the table the record is successfully deleted.

    Tutorial Video

    You can watch the below video to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=2rEZrFj2haE[/embedyt]
  • Update an Entity using SAP OData

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    Many times, we come across a scenario where we want to update the data records, for example, we want to update the phone number or address.

    This article describes the step-by-step procedure to implement and test update operations in SAP OData.

    Context

    Update entity can be implemented by the redefining UPDATE_ENTITY method.

    1. Using PUT HTTP method.
    2. Using PATCH HTTP method.

    Difference between PUT and PATCH HTTP method

    • PUT: The request body is considered as the updated version of the original data stored in the database. When using PUT, we need to send the full payload in our request.
    • PATCH: It is used for the partial modification of the resource. When using PATCH, we only send the data to be modified in the request body.

    Procedure

    1. Open *DPC_EXT class artifact of OData and redefine *UPDATE_ENTITY method.
    2. Reimplement the method for the update.
      UPDATE_ENTITY method
    3. Activate the class and register the service.
    4. Execute and test the OData.
      1. Select Entity set
      2. Get the data to be updated using the GET request
      3. Click on Use as Request to copy the HTTP response to HTTP request which works as input.
        Execute and test the OData
      4. Change the field value Carname and URL in HTTP Request
      5. Select PUT option
      6. Add the key value to be updated in the request URL
      7. Execute the request
        Execute and test the OData PUT Request
      8. Status code 204 represents success
        PUT Request response
      9. Verify-in the table data is successfully updated.
        verify the updated data

    Tutorial Video

    You can watch the below video to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=2rEZrFj2haE[/embedyt]
  • Create an Entity using SAP OData

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    Context

    Create entity can be implemented in two ways:

    1. Using CREATE_ENTITY method for single entity creation.
    2. Using CREATE_DEEP_ENTITY method to create a single entity as well as parent and child entity together.

    Procedure

    1. Open *DPC_EXT class artifact of OData and redefine *CREATE_ENTITY method.

    2. Reimplement the method.

    method PARTNERS_CREATE_ENTITY.
    
      data: lv_id                type          snwd_partner_id,
            ls_id                type          bapi_epm_bp_id,
            ls_header            type          bapi_epm_bp_header,
            lt_return            type 	      table of bapiret2,
            error_msg            type          string,
            ls_message           type          scx_t100key,
            lt_keys              type          /iwbep/t_mgw_tech_pairs,
            ls_snwd_bpa          type          snwd_bpa,
            lv_timestamp         type          timestamp.
    
      io_data_provider->read_entry_data( importing es_data = ls_header ).
    
      CALL FUNCTION 'BAPI_EPM_BP_CREATE'
        EXPORTING
          HEADERDATA        = ls_header " EPM: BP header data
        IMPORTING
          BUSINESSPARTNERID = ls_id
        TABLES
          RETURN     = lt_return.     
    
      if lt_return is not initial.
        loop at lt_return reference into data(lr_return).
          err_msg = lr_return->message .
        endloop.
    
        ls_message-msgid = 'SY'.
        ls_message-msgno = '002'.
        ls_message-attr1 = error_msg.
    
        raise exception type /iwbep/cx_mgw_busi_exception
          EXPORTING
            textid = ls_message.
      endif.
    
      CALL FUNCTION 'BAPI_EPM_BP_GET_DETAIL'
        EXPORTING
          BP_ID             = ls_id
        IMPORTING
          HEADERDATA        = er_entity
    endmethod. 
    

    The input data is passed in es_data structure and captured in ls_header. The structure ls_header is then used as the input parameter of BAPI ‘BAPI_EPM_BP_CREATE’ to create data in the database. Then BAPI ‘BAPI_EPM_BP_GET_DETAIL’ will retrieve the created data and capture it in er_entity which will be passed to the response body.

    3. Activate the class.

    4. Create Deep Entity (To create Header with Item): Redefine method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_DEEP_ENTITY

    5. Reimplement the method.

    method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_DEEP_ENTITY.
    
     types: ty_t_soitem type standard table of  zcl_z_epm_rkt_mpc=>ts_salesorderitem with default key.
     types: begin of ty_s_so.
              include type zcl_z_epm_rkt_mpc=>ts_salesorder.
               types: items type ty_t_soitem,
             end of ty_s_so.
    
      data: ls_sales_order     type ty_s_so,
            lv_compare_result  type /iwbep/if_mgw_odata_expand=>ty_e_compare_result.
    
      data: lv_so_id    type BAPI_EPM_SO_ID,
            ls_so_hdr    type BAPI_EPM_SO_HEADER,
            ls_so_hdr2   type BAPI_EPM_SO_HEADER,
            ls_so_item   type BAPI_EPM_SO_ITEM,
            lt_so_item   type standard table of BAPI_EPM_SO_ITEM,
            lt_so_item2  type standard table of BAPI_EPM_SO_ITEM,
            lt_return   type bapirettab,
            ls_return   TYPE bapiret2,
            ls_message  type scx_t100key,
            error_msg     type string.
    
      constants: lc_so_itm TYPE string VALUE 'Items'.
    
    * Validate whether data matches
      lv_compare_result = io_expand->compare_to( lc_so_itm ).
    
    * Access data from IO_DATA_PROVIDER
      if lv_compare_result EQ /iwbep/if_mgw_odata_expand=>gcs_compare_result-match_equals.
    io_data_provider->read_entry_data( IMPORTING es_data = ls_sales_order ).
    
    *   Move header Sales order data into BAPI structure
        move-corresponding ls_sales_order to ls_so_hdr.
    
    *   Move Sales Order items into BAPI table structure
        loop at ls_sales_order-items into ls_so_item.
           append ls_so_item to lt_so_item.
        endloop.
    
        CALL FUNCTION 'BAPI_EPM_SO_CREATE'
          EXPORTING
            HEADERDATA          = ls_so_hdr
          IMPORTING
            SALESORDERID        = lv_so_id
          TABLES
            ITEMDATA            = lt_so_item
            RETURN              = lt_return.
    
        if lt_return is not initial.
          loop at lt_return into ls_return.
            err_msg = ls_return-message .
          endloop.
    
          ls_message-msgid = 'SY'.
          ls_message-msgno = '002'.
          ls_message-attr1 = error_msg.
    
          raise exception type /iwbep/cx_mgw_busi_exception
            exporting
              textid = ls_message.
        else.
    
          CALL FUNCTION 'BAPI_EPM_SO_GET_DETAIL'
            EXPORTING
              SO_ID            = lv_so_id
            IMPORTING
              HEADERDATA       = ls_so_hdr2
            TABLES
              ITEMDATA         = lt_so_item2.
          move-corresponding ls_so_hdr2 to ls_sales_order.
          ls_sales_order-items = lt_so_item2.
    
          copy_data_to_ref(
          EXPORTING
            is_data = ls_sales_order
          CHANGING
            cr_data = er_deep_entity ).
        endif.
      endif.
    endmethod. 
    

    The structure of incoming data contains parent and child entity nested structure. This is defined with type ty_s_so.

    6. Activate the class

    7. Execute the Create request.

    • Select Entity Set
    • Select HTTP method as POST
    • Add the data in the request body
    • Click Execute

    Tutorial Video

    You can watch the below video to learn implementation:

    [embedyt] https://www.youtube.com/watch?v=2rEZrFj2haE[/embedyt]
  • Testing SAP OData CRUD operations using Postman

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    Introduction

    Postman is an API development tool that helps developers to create, test, share and document the APIs. It has various HTTP requests like GET, POST, PUT, PATCH and the ability to save the environment.

    In this article, we will learn how to set up the POSTMAN and then we will test OData CRUD operations using POSTMAN.

     

    Installing POSTMAN

    To install POSTMAN on your device you can use the link go.postman.co/home and download the latest version for your platform.

    For more details on installing and updating POSTMAN, you can refer to the link https://learning.postman.com/docs/getting-started/installation-and-updates/

     

    Components of POSTMAN

    Postman UI is made up of various components.
    Components of POSTMAN

    • Left sidebar provides the navigation to Collections, APIs, Environments, Mock Servers, Monitors and History.
    • Header provides the access to Workspace, Reports, and Search option.
    • Center area is where we work with requests.
    • Right sidebar provides the link to Comments, Request Info’s, Code and Documentations.

     

    Variables

    We will use the variables to store our data which will be reused multiple times.

    You can create variables by clicking ENVIRONMENT in the left panel and selecting GLOBAL.

    Variables in Postman

    Here you create variables and provide initial and current value. In case you need to change the value of the variable you only need to update the CURRENT VALUE field. This is the field from where the data is picked up.

    Scope of variables:

    Scope of variables

    • Global scope: Enable you to use data between the Collection, requests, test scripts and environment.
    • Collection: Enable you to use data in different requests under the same collection.
    • Environment: Enables to tailor the processing to different environments.
    • Data: Comes from external files like CSV, JSON.
    • Local: The scope is temporary and can only be used in the defined requests.

    Create variable

    1. Select data and click on Set as Variable.
      Create variable
    2. Select Set as new Variable.
      Set as new Variable
    3. Provide name, value and scope.
      Save Variable

     

    Format to use variables in request: {{variable_name}}

    Example:  .Example of variable in postman

     

    HTTP requests

    There are various HTTP methods available that are used to make a request to APIs. Some of the frequently used HTTP methods are:

    • GET: Used to retrieve data from APIs (Read scenario)
    • POST: Used to send new data to API (Create scenario)
    • PUT or PATCH: Used to update existing data (Update scenario). PUT request modifies the entire resource in the database whereas PATCH request modifies only the supplied resource. So, while using PUT we need to send the entire data in request URI and by using PATCH we need to send only the updatable field.
    • DELETE: Used to remove existing record (Delete scenario)

    It supports various addition methods. Refer to the below snip.
    HTTP requests in Postman

    Creating requests

    You can create a request by clicking on the NEW tab and selecting HTTP Request. Also, you can create a request by clicking + button.

    Creating requests

    After selecting HTTP Request, a screen will open. Provide relevant name, description to your HTTP request.

    Specify the relevant details for your requests (like HTTP method, URL, parameters, body data).

    Get request in Postman

    Click on SEND button to save your call. You can create a collection to save all your related requests under one folder.

     

    Collection

    A collection is a folder that groups the number of API requests. There can be n number of collections in Postman. Generally, an API request belonging to the same business object is saved under  the same Collection. You can even share your API requests with your team via collection.

    Authentication

    Authentication is verifying the client’s identity who is accessing the request whereas authorization is verifying the client’s action of permission. Some APIs require authorization details act.

    To provide authorization details, click on the Authorization tab and select auth Type. Provide the relevant details and SAVE.

    There are various auth types, for more details check out Authorizing requests.

    Authentication in Postman

    Instead of adding an authorization in each request individually, you can add your authorization details directly to your Collection.

    Steps:

    1. Select TYPE as Inherit auth from parent.
      Type of Authorization
    2. Click Collection and add authorization details there.
      Basic Authentication in Postman

    Sending requests

    GET request

    Steps to follow:

    1. Click on the NEW button and select HTTP request
      New GET request

     

    1. Select HTTP request GET and enter OData service URL in URL field
      Enter URL

     

    1. Click on the Send button
      Send Request

     

    At the bottom, you can see the output and status code.

     

    Fetch x-csrf-token

    An x-csrf-token is used to prevent cross-site request forgery attacks. While making a call for Create/Update/Delete we must need to send x-csrf-token value via Header.

    Steps to fetch the x-csrf-token value.

    1. Create a GET
    2. Add in HEADERS: key = x-csrf-token and value = fetch.
      Fetch x-csrf-token
    3. Execute the request by clicking on SEND
    4. Below you will get the result. In the Header section of the result you can find fetched x-csrf-token value. Get that value and paste it in HEADERS section of CUD requests.

     

    POST request

    1. Select HTTP request POST and enter OData service URL for create in URL field. (Do not provide the key field and its value in URI)
      POST request in Postman
    2. Provide x-csrf-token parameter in HEADERS (To fetch x-csrf-token refer How to fetch x-csrf-token?).
      Provide x-csrf-token
    3. Provide the data to be created in the BODY tab and select the relevant data type. Here, we have selected raw.
      Provide the data to be created in the BODY
    4. Save and click on Send to execute the request.

     

    PUT/PATCH request

    To know which request URI to use please read HTTP requests.

    1. Select HTTP request PUT/PATCH and enter OData service URL for create in URL field. ( Add key field and its value which is to be updated)
      Select HTTP request PUT
    2. Provide x-csrf-token parameter in HEADERS (To fetch x-csrf-token refer How to fetch x-csrf-token?).
      Provide x-csrf-token parameter in HEADERS tab
    3. Provide the data to be created in the BODY tab and select the relevant data type. Here, we have selected raw.
      For Put Provide the data to be created in the BODY tab
    4. Save and click on Send to execute the request.

     

    DELETE request

    1. Select HTTP request DELETE and enter OData service URL for create in URL field. ( Add key field and its value which is to be deleted)
      Select HTTP request DELETE
    2. Provide x-csrf-token parameter in HEADERS (To fetch x-csrf-token refer How to fetch x-csrf-token?).
      Provide x-csrf-token for Delete
    3. For DELETE requests we don’t have to provide any input in BODY.
      No body required for Delete
    4. Save and click on Send to execute the request.

    Sharing API requests

    To share your API requests with your team or other people follow the below steps.

    1. Save your requests in Collection.
    2. Click on Collection that you want to share.
    3. Click on the Share button
      Sharing API requests
    4. There are three ways you can share.
      Share Quota

    Best practices

    1. If a parameter or value is used at multiple places. Always try to create its variable in the Environment section and use the variable in your requests.
      Example: If api.getpostman.com is used in all your requests URL.
      Postmand Best practices 1
      Create a variable with value api.getpostman.com and use the variable everywhere.
      The positive aspect is in case your domain is changed, you only need to change the value in one place and all your requests will adapt it.
      Postmand Best practices 2
      Postmand Best practices 3

     

    1. If you are adding Authorization, never provide your password directly in your Request or Collection level.

    The mishappening is, if you provide your password directly at a collection level or in request and you share the collection with your team or other people, the password will also get shared with them. So, everyone with that collection will get to know your password.

    Postmand Best practices 4

    The best approach is to create a variable for your password in the environment section and use that variable in the password field. This way only the variable name will be shared and your password will be safe.

    Postmand Best practices 5

    1. Instead of fetching x-csrf-token value and adding it to request every time manually, you can create a variable for x-csrf-token in the environment and add a script code to automatically update the x-csrf-token value in the environment.
  • MIME handling in SAP OData (File Media handling)

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    This article will give a bare minimum to read and upload media files or MIME in SAP OData service.

    Procedure

    1. Create OData service
    2. Register service
    3. Execute service

    Steps

    1. Create OData
    2. Select EntityType and select checkbox ‘Media’
      Enable MIME in OData
    3. Generate runtime artifact. In MPC ext class redefine the DEFINE method.
      Generate MIME runtime artifact ODATA
    4. Redefine method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_STREAM .
      Create Stream
    5. Redefine method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_STREAM .
      Get Stream
    6. Redefine method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_STREAM .
      Update Stream

     

    1. Redefine method FILESET_GET_ENTITYSET.
      FILESET_GET_ENTITYSET
    2. Register OData service
    3. Execute
      1. GET_STREAM is used to download the media
      /sap/opu/odata/sap/ZMIMEFILE_SRV/File(Mandt=’100′,Filename=’mobile.jpg’)/$value.
      Download the media
       

      2. CREATE_STREAM is used to upload the media
      /sap/opu/odata/sap/ZMIMEFILE_SRV/File
      Upload the media

     

    Features

    List of supported MIME Types that can be stored in MIME Repository:

    Category/Subcategory File Extension Description
    texts text/css css CSS stylesheet file
    text/html html, htm HTML file
    text/javascript js JavaScript file
    text/plain txt, c, cc, g, h, hh, m, f90 Plain text file
    text/richtext rtx MIME rich text
    text/xml xml XML file
    Images image/gif gif GIF graphic
    image/ief ief Exchange Format
    image/jpeg jpeg, jpg, jpe JPEG graphic
    image/x-rgb rgb RBG graphic
    image/x-windowdump xwd X-Windows dump
    image/tiff tiff, tif TIFF graphic
    image/bmp bmp Icon
    image/ico ico Icon (Windows)
    Audio audio/basic au, snd AU and SND sound files
    audio/x-aiff aif, aiff, aifc AIFF sound file
    audio/x-aiff midi, mid MIDI file
    audio/x-pn-realaudio ram, ra RealAudio file
    audio/x-pn-realaudio-plugin rpm RealAudio plug-in file
    Video video/mpeg mpeg, mpg, mpe MPEG video
    video/x-msvideo avi Microsoft AVI video
    video/x-sgi-movie movie Microsoft SGI video
    video/quicktime qt, mov Quicktime video
    Applications application/acad (NCSA) dwg AutoCAD file
    application/dxf (CERN) dxf AutoCAD file
    application/mif mif Maker Interchange Format (Adobe FrameMaker)
    application/msword doc, dot MS Word file
    application/mspowerpoint ppt, ppz, pps, pot MS PowerPoint file
    application/msexcel xls, xla MS Excel file
    application/mshelp hlp, chm MS Windows help file
    application/octet-stream com, exe, bin, dll, class Executable file or program code file
    application/pdf pdf PDF file (Adobe Acrobat Exchange/Reader)
    application/postscript ai, eps, ps Postscript file (Adobe)
    application/rtf rtf RTF file (Microsoft)

     

  • $ORDERBY Query in SAP OData

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    In this article, we will learn how to use $orderby query in our SAP OData services.

    What is the use of $orderby query?

    There are many query options to control the amount and order of data. One of the query options provided is $orderby. It adds the sorting capability to OData services. You can order the collection based on the fields available.

    System version

    SAP NetWeaver Gateway Release 2.0 Support Package >=03

    Syntax

    http://<server>:<port>/sap/opu/odata/sap/<service_name>/EntitySet?$orderby=<fieldname> <sortorder>

    where,

    • <fieldname> :is the name of the field.
    • <sortorder>: desc/asc

     

    Business Example

    An OData service has retrieved all the Product details, but you want the details in some specified order say, you want the details in descending order by price. Here you can use the $orderby query to achieve the desired output.

    You want to fetch the Product details in order by its Price in descending.

    Implementation

    In this section, we will implement $orderby on our Product Entity Set.

    Step 1: After the creation of the OData service, right Click on Entity Set under Service Implementation, go to ABAP workbench.

    SAP OData Implementation

    Step 2:

    Adjust your code for $orderby query. The orderby query option is available in the method by accessing importing parameter IT_ORDER.

    $ORDERBY Query in SAP OData

     

    In the GetEntitySet method, first, we retrieve all the products and get orderby “fieldname”, “sortorder” and apply them to the BAPI result data to get the required sort order.

    Step 3:

    Execute the service. If we don’t add $orderby in our service URL, we will get all the results from the system. If we add $order by in-service URL we will get the result based on the sort order provided.

    Service URL: /sap/opu/odata/sap/ZDEMO_GW_SRV_SRV/ProductsSet?$orderby=Price asc’.

    $ORDERBY Query in SAP OData Output

  • $TOP and $SKIP Query in SAP OData

    Preface – This post is part of the SAP ABAP OData Tutorial series.

    In this article, we will learn how to use $top and $skip query in our OData services.

    What is the use of $top $skip query?

    The OData query $top and $skip are used to restrict the data from the backend.

    To achieve the client-side pagination, we can use $top = n query and $skip = m is used in coordination with $top. $top query fetches the top n records skipping first m records.

    System version

    SAP NetWeaver Gateway Release 2.0 Support Package >=03

    Syntax

    • http://<server>:<port>/sap/opu/odata/sap/<service_name>/EntitySet?$top=5
    • http://<server>:<port>/sap/opu/odata/sap/<service_name>/ EntitySet?$top=5&skip=3

     

    Business Example

    • You want the first 5 records of Products. Or we want the first 10 roll number students in our result.
    • Teach wants first 10 roll number students skipping first 5.

    Implementation

    In this section, we will implement $top and $skip on our Product Entity Set.

    Step 1: After the creation of OData service, right Click on Entity Set under Service Implementation, go to ABAP workbench.

    SAP OData Implementation

    Step 2:

    Adjust your code for $top and $skip query.

    $TOP and $SKIP Query in SAP OData

    In the above code, we retrieved all the product details and applied $top and $skip query to get the required output.

    Step 3:

    Add $top and $skip query in OData URL and execute the service.

    Service URL: /sap/opu/odata/sap/ZProduct_Srv/ProductsSet?$top=5

    $TOP and $SKIP Query in SAP OData Output