Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / RAP / Files, Custom Entities & Integration

Files, Custom Entities & Integration

RAP · ABAP Development ·

Open the interactive lesson →
  1. Large objects: the customer's PO as an attachment
  2. Uploading items from Excel or CSV
  3. Custom entities: delivery tracking from the carrier (R17)
  4. Virtual elements, abstract entities and other read-only tools
  5. Inbound: the CRM creates orders through a Web API (R18)
  6. Outbound: calling the carrier's service (R17)
  7. Released BOs: creating the standard sales order with I_SalesOrderTP (R18)
  8. RAP and CAP together
  9. Interview questions

This page connects the sales order BO to files and to other systems: the customer's PO as a PDF attachment and an Excel/CSV item upload (R16), live delivery tracking from a carrier through a custom entity (R17), and the external CRM that creates orders through a Web API, followed by the standard S/4HANA sales order created with the released BO I_SalesOrderTP (R18).

Part 1 – Large objects: the customer's PO as an attachment

R-ID

Requirement

Where on this page

R16

The customer's PO (PDF) is attached; items can be uploaded from a CSV/Excel file

Part 1 (attachment), Part 2 (upload action)

R17

Delivery tracking comes from a carrier's API (not stored in SAP)

Part 3 (custom entity), Part 6 (outbound call)

R18

An external CRM creates orders through an API; the standard S/4 sales order is created from it

Part 5 (Web API), Part 7 (I_SalesOrderTP)

Why first: a sales order is more than the fields the rep types. The customer sends a purchase order as a PDF, and big orders arrive as a spreadsheet with 200 lines. RAP handles both without any GUI upload function: a large object (LOB) stores a file in a field and is exposed as an OData stream, and an action with a file parameter reads an uploaded file and creates data from it.

R16, part 1 – the customer's PO (PDF) is attached to the order. One file per order is enough, so it is stored in three extra fields of the order header.

Attachment as OData stream: Fiori object page upload control sends the file to the stream property, RAP fills Attachment, MimeType and FileName in the draft table zsales_hdr_d, Activate copies it to zsales_hdr, download returns the file with its MIME type

1.1 Three fields and one annotation

SAP's RAP100 tutorial (exercise 2) uses exactly this pattern. Fiori elements shows upload, download and delete controls automatically once the annotation is there.

" 1. Table zsales_hdr AND draft table zsales_hdr_d: three more fields, same types in both
attachment            : abap.rawstring(0);
mime_type             : abap.char(128);
file_name             : abap.char(128);

" 2. Base view ZR_SalesOrder: annotate them
@Semantics.largeObject: { mimeType: 'MimeType',            " element names, case-sensitive
fileName: 'FileName',
acceptableMimeTypes: [ 'application/pdf' ],
contentDispositionPreference: #ATTACHMENT }
attachment            as Attachment,
@Semantics.mimeType: true
mime_type             as MimeType,
file_name             as FileName,
  • Then add the three elements to the projection view ZC_SalesOrder, the BDEF mapping and a field group or facet in the metadata extension (→ see 03 · Projection, UI, Access Control & Service).
  • With draft the upload lands in zsales_hdr_d first; the PDF reaches zsales_hdr only on Activate, and Discard throws it away (→ see 07 · Locking, Draft & Side Effects).
  • #ATTACHMENT = download as a file; #INLINE = open in the browser.
  • acceptableMimeTypes restricts the accepted file types – here only PDF, so an .exe or .xlsx is refused.
  • Several files per order: model a child entity (composition _Attachment) with its own key and the same three fields.
  • S/4HANA also has the Attachment Service (GOS/DMS reuse component) for standard documents; how it works with RAP draft apps depends on the release – check your release.

Common mistakes

  • Wrong element names in @Semantics.largeObject (they are case-sensitive) → the field shows as plain text instead of an upload control.
  • LOB fields missing in the draft table, or with other types → activation error or the file is lost while editing.

Part 2 – Uploading items from Excel or CSV

R16, part 2 – the rep uploads the customer's item list instead of typing it. On the order's object page a button Upload Items opens a dialog with a file picker; the action reads the sheet and creates the items through the BO, so validateQuantity, calculateTotal and the draft work exactly as for typed items. The file travels as a deep action parameter: an abstract entity with a large-object field.

R16 Excel upload: the user picks a file in the action dialog on order SO-0000001, the action uploadItems receives it as a deep parameter, XCO XLSX reads columns A to D from row 2, MODIFY ENTITIES IN LOCAL MODE CREATE BY _Item adds the items to the buffer; release note, fallback for older releases and the warning never to INSERT into zsales_itm

2.1 The parameter: two abstract entities

" Abstract entity 1: the file itself
@EndUserText.label: 'Excel file'
define root abstract entity ZD_UploadFile
{
@Semantics.largeObject: { mimeType: 'MimeType',
fileName: 'FileName',
contentDispositionPreference: #INLINE }
@EndUserText.label: 'Select Excel file'
Attachment : abap.rawstring(0);
@UI.hidden: true
MimeType   : abap.char(128);
@UI.hidden: true
FileName   : abap.char(128);
}

" Abstract entity 2: the action parameter, pointing to the file
@EndUserText.label: 'Upload items parameter'
define root abstract entity ZD_UploadItems
{
@UI.hidden: true
Dummy : abap_boolean;
_File : association [1] to ZD_UploadFile on 1 = 1;
}

2.2 Abstract BDEF, action and button

" Abstract BDEF for ZD_UploadItems - a deep parameter needs an abstract BDEF "with hierarchy"
abstract;
strict ( 2 );
with hierarchy;
define behavior for ZD_UploadItems
{
association _File with hierarchy;
}

" (ZD_UploadFile gets its own: abstract; strict ( 2 ); with hierarchy; define behavior for ZD_UploadFile { })

" Base BDEF ZR_SalesOrder
action ( features : instance ) uploadItems deep parameter ZD_UploadItems result [1] $self;

" Projection BDEF ZC_SalesOrder
use action uploadItems;

" Metadata extension: button on the object page
@UI.identification: [ { type: #FOR_ACTION, dataAction: 'uploadItems', label: 'Upload Items' } ]
  • features : instance lets get_instance_features offer the button only while the order has status N (→ see 06 · Feature Control, Authorization & Numbering).
  • Add action uploadItems affects entity _Item, field NetAmount; to the side effects so the items table and the total refresh at once (→ see 07 · Locking, Draft & Side Effects).

2.3 The handler: read the sheet, create the items with EML

METHOD uploadItems.
TYPES: BEGIN OF ty_row,                                 " columns A..D of the sheet, as text
item_no  TYPE string,
material TYPE string,
quantity TYPE string,
unit     TYPE string,
END OF ty_row.
DATA rows TYPE STANDARD TABLE OF ty_row WITH EMPTY KEY.

LOOP AT keys INTO DATA(key).
DATA(content) = key-%param-_File-Attachment.         " the uploaded bytes (xstring)

" Read the first worksheet from row 2 (row 1 = header) with the released XCO XLSX API
DATA(sheet) = xco_cp_xlsx=>document->for_file_content( content
)->read_access( )->get_workbook( )->worksheet->at_position( 1 ).
DATA(pattern) = xco_cp_xlsx_selection=>pattern_builder->simple_from_to(
)->from_column( xco_cp_xlsx=>coordinate->for_alphabetic_value( 'A' )
)->to_column( xco_cp_xlsx=>coordinate->for_alphabetic_value( 'D' )
)->from_row( xco_cp_xlsx=>coordinate->for_numeric_value( 2 )
)->get_pattern( ).
CLEAR rows.
sheet->select( pattern )->row_stream( )->operation->write_to( REF #( rows )
)->set_value_transformation( xco_cp_xlsx_read_access=>value_transformation->string_value
)->if_xco_xlsx_ra_operation~execute( ).

" Create the items through the BO, so validations and determinations run
MODIFY ENTITIES OF zr_salesorder IN LOCAL MODE
ENTITY SalesOrder
CREATE BY \_Item AUTO FILL CID
FIELDS ( ItemNo MaterialID Quantity Unit )
WITH VALUE #( ( %tky    = key-%tky                 " %tky keeps %is_draft: items go into the draft
%target = VALUE #( FOR row IN rows
( ItemNo     = row-item_no
MaterialID = row-material
Quantity   = row-quantity
Unit       = row-unit ) ) ) )
FAILED DATA(create_failed)
REPORTED DATA(create_reported).
reported = CORRESPONDING #( DEEP create_reported ).
ENDLOOP.

" return the order so the UI refreshes it
READ ENTITIES OF zr_salesorder IN LOCAL MODE
ENTITY SalesOrder ALL FIELDS WITH CORRESPONDING #( keys )
RESULT DATA(orders).
result = VALUE #( FOR order IN orders ( %tky = order-%tky  %param = order ) ).
ENDMETHOD.
  • The VALUE constructor converts the text cells to the field types. A cell like "abc" in the quantity column raises a conversion error, so check or convert the values first, and let validateQuantity catch quantities of 0 instead of trusting the file.
  • Release: a file picker in the action dialog needs a recent SAPUI5 version (around 1.135, 2025) and a recent ABAP release. It works on SAP Business AI Platform, ABAP environment; on S/4HANA on-premise 2023 the service metadata had issues – check your release.
  • Fallback for older releases: let the user upload the file into a large-object field (Part 1, e.g. on a child entity Upload), then an action importItems reads that field and does the same parsing.

CSV instead of Excel

" xstring -> string (released class), then split lines and columns
DATA(text) = cl_abap_conv_codepage=>create_in( codepage = `UTF-8` )->convert( content ).
REPLACE ALL OCCURRENCES OF cl_abap_char_utilities=>cr_lf IN text
WITH cl_abap_char_utilities=>newline.            " files from Windows end lines with CR LF
SPLIT text AT cl_abap_char_utilities=>newline INTO TABLE DATA(lines).
LOOP AT lines INTO DATA(line) FROM 2.                   " skip header line
SPLIT line AT ';' INTO DATA(item_no) DATA(material) DATA(quantity) DATA(unit).
" ... collect into rows as above
ENDLOOP.

Clean-core notes

  • In ABAP Cloud use released APIs only: XCO_CP_XLSX for Excel, CL_ABAP_CONV_CODEPAGE for text. Classic helpers such as CL_FDT_XL_SPREADSHEET or GUI upload functions are not released.
  • The open-source library abap2xlsx (Apache-2.0) is an option in classic ABAP; check your company's rules for open-source code.

Common mistake

  • Inserting the uploaded rows with SQL INSERT into zsales_itm – this bypasses validations, the total, draft and locks. Always go through EML (→ see 08 · EML).

Part 3 – Custom entities: delivery tracking from the carrier (R17)

Why: not everything on the order's object page lives in an SAP table. R17 – the delivery status comes from the carrier's API and must not be copied into SAP; it is read live whenever the user opens the order. A custom entity is a CDS entity without a SQL data source: the framework calls your ABAP class (the query provider) to get the rows.

R17 custom entity query flow: the Fiori list sends $top, $skip, $filter, $orderby and $count; RAP calls if_rap_query_provider~select; the class reads paging, filter and sort from io_request, fetches the carrier's data, and returns the count and one page through io_response; definition, typical bugs and the association from ZC_SalesOrder

3.1 Definition and query provider

@EndUserText.label: 'Delivery status (carrier)'
@ObjectModel.query.implementedBy: 'ABAP:ZCL_DELIVERY_STATUS_QUERY'
define custom entity ZCE_DeliveryStatus
{
key SalesOrderID   : zde_so_id;
Carrier        : abap.char(20);
TrackingNumber : abap.char(35);
DeliveryStatus : abap.char(20);
ShippedOn      : abap.dats;
}
CLASS zcl_delivery_status_query DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_rap_query_provider.
PRIVATE SECTION.
TYPES tt_status TYPE STANDARD TABLE OF zce_deliverystatus WITH EMPTY KEY.
METHODS get_from_carrier RETURNING VALUE(result) TYPE tt_status.
ENDCLASS.

CLASS zcl_delivery_status_query IMPLEMENTATION.
METHOD if_rap_query_provider~select.
" 1. What does the UI ask for?
DATA(top)  = io_request->get_paging( )->get_page_size( ).   " must be read when paging is requested
DATA(skip) = io_request->get_paging( )->get_offset( ).
DATA(sort) = io_request->get_sort_elements( ).
TRY.
DATA(filter) = io_request->get_filter( )->get_as_ranges( ).
CATCH cx_rap_query_filter_no_range.
" filter cannot be expressed as ranges (e.g. OR across fields) - use get_as_sql_string( ) or refuse
ENDTRY.

" 2. Get the data - normally a remote call (Part 6); here simulated
DATA(all) = get_from_carrier( ).

" 3. Filter
LOOP AT filter INTO DATA(f).
CASE f-name.                                        " element names in upper case
WHEN 'SALESORDERID'.   DELETE all WHERE SalesOrderID   NOT IN f-range.
WHEN 'CARRIER'.        DELETE all WHERE Carrier        NOT IN f-range.
WHEN 'DELIVERYSTATUS'. DELETE all WHERE DeliveryStatus NOT IN f-range.
ENDCASE.
ENDLOOP.

" 4. Sort
DATA(order_by) = VALUE abap_sortorder_tab( FOR s IN sort ( name       = s-element_name
descending = s-descending ) ).
IF order_by IS NOT INITIAL.
SORT all BY (order_by).
ENDIF.

" 5. Count ($count / "Delivery status (42)") - before paging
IF io_request->is_total_numb_of_rec_requested( ).
io_response->set_total_number_of_records( lines( all ) ).
ENDIF.

" 6. One page
IF io_request->is_data_requested( ).
DATA page TYPE tt_status.
DATA(last) = COND int8( WHEN top = if_rap_query_paging=>page_size_unlimited THEN lines( all )
ELSE skip + top ).
LOOP AT all INTO DATA(row) FROM skip + 1 TO last.
APPEND row TO page.
ENDLOOP.
io_response->set_data( page ).
ENDIF.
ENDMETHOD.

METHOD get_from_carrier.
result = VALUE #( ( SalesOrderID = 'SO-0000001' Carrier = 'DHL' TrackingNumber = '00340434160000000001'
DeliveryStatus = 'IN TRANSIT' )
( SalesOrderID = 'SO-0000002' Carrier = 'UPS' TrackingNumber = '1Z0000000000000002'
DeliveryStatus = 'DELIVERED' ) ).
ENDMETHOD.
ENDCLASS.

io_request method

OData part

Use

get_paging( )->get_page_size( ) / get_offset( )

$top / $skip

Return only one page; if_rap_query_paging=>page_size_unlimited = no $top

get_filter( )->get_as_ranges( ) / get_as_sql_string( )

$filter

Ranges per element or a SQL WHERE string (for a SELECT on a table)

get_sort_elements( )

$orderby

Element name + descending flag

get_search_expression( )

$search

Free-text search field

get_requested_elements( )

$select

Fetch only the columns the UI shows

is_total_numb_of_rec_requested( )

$count

Then call set_total_number_of_records( )

is_data_requested( )

–

Then call set_data( ); a count-only call wants no rows

3.2 Show it on the order

" Projection view ZC_SalesOrder: a new association to the custom entity
association [0..1] to ZCE_DeliveryStatus as _Delivery
on $projection.SalesOrderID = _Delivery.SalesOrderID
{
...
_Delivery
}

" Service definition ZUI_SalesOrder: expose the target too
expose ZCE_DeliveryStatus as DeliveryStatus;
  • When the user opens order SO-0000001, Fiori follows _Delivery; the query provider receives the filter SALESORDERID = SO-0000001 – that is why the filter loop handles it.
  • A custom entity is read-only here. It can also be made transactional with an unmanaged BDEF on top – rare, check your release.
  • SAP's RAP620 exercise builds a value help from a custom entity on a service consumption model in the same way.

Common mistakes

  • Not reading get_paging( ) (or the sort elements) in a query provider when the UI sends them → runtime error.
  • Applying paging before counting → "Delivery status (20)" although there are 42.
  • Building a custom entity for data that is in a table – a CDS view entity is simpler, faster and filterable by the database.

Part 4 – Virtual elements, abstract entities and other read-only tools

Besides custom entities, RAP has a tool for each kind of data that is only shown or only describes a structure:

Which read-only tool: data in DB tables → CDS view entity; one calculated field → virtual element; data from an API or complex ABAP → custom entity with query provider; only a structure → abstract entity; figures and hierarchies → analytical and hierarchy views

4.1 Virtual elements

A virtual element is one field of a projection view that ABAP calculates when the data is read through OData – e.g. "days open": how long an order has been waiting, useful for the approver (R7).

" Projection view ZC_SalesOrder
@ObjectModel.virtualElementCalculatedBy: 'ABAP:ZCL_SO_VIRTUAL_ELEMENTS'
@EndUserText.label: 'Days open'
virtual DaysOpen : abap.int4,
CLASS zcl_so_virtual_elements DEFINITION PUBLIC FINAL CREATE PUBLIC.
PUBLIC SECTION.
INTERFACES if_sadl_exit_calc_element_read.
ENDCLASS.

CLASS zcl_so_virtual_elements IMPLEMENTATION.
METHOD if_sadl_exit_calc_element_read~get_calculation_info.
" which real fields are needed to calculate the requested virtual ones?
IF line_exists( it_requested_calc_elements[ table_line = 'DAYSOPEN' ] ).
INSERT CONV #( 'ORDERDATE' ) INTO TABLE et_requested_orig_elements.
ENDIF.
ENDMETHOD.

METHOD if_sadl_exit_calc_element_read~calculate.
DATA orders TYPE STANDARD TABLE OF zc_salesorder WITH DEFAULT KEY.
orders = CORRESPONDING #( it_original_data ).
DATA(today) = cl_abap_context_info=>get_system_date( ).
LOOP AT orders ASSIGNING FIELD-SYMBOL(<order>).
<order>-DaysOpen = today - <order>-OrderDate.
ENDLOOP.
ct_calculated_data = CORRESPONDING #( orders ).
ENDMETHOD.
ENDCLASS.
  • Virtual elements are filled only for OData reads – not in EML READ ENTITIES, not in ABAP SQL, not in a CDS WHERE.
  • Filtering and sorting on them need extra exits (if_sadl_exit_filter_transform, if_sadl_exit_sort_transform). If the value can be computed in CDS (e.g. with dats_days_between), prefer a normal calculated element – faster and filterable.

4.2 Abstract entities

An abstract entity only describes a structure – no data, no database. RAP uses it wherever a "shape" is needed:

Use

Example

Action / function parameter

define abstract entity ZD_Discount { DiscountPercent : abap.int1; } → action applyDiscount parameter ZD_Discount result [1] $self;

Deep parameter (with a file)

ZD_UploadItems with _File (Part 2)

Event payload

event OrderApproved parameter <abstract entity>; (→ see 10 · Business Events & Event-Driven RAP)

Result of a remote call

The service consumption model generates abstract entities for the remote service (Part 6)

4.3 Analytical and hierarchy views in brief

  • Analytical: a cube view entity (@Analytics.dataCategory: #CUBE) with dimension views, and a query as define transient view entity ... provider contract analytical_query, exposed in a service binding of type InA for SAP Analytics Cloud and analytical Fiori apps (check your release).
  • Hierarchies: define hierarchy on a parent-child association (e.g. a sales organisation tree) can be shown as a tree table in Fiori elements; editable hierarchies are a newer RAP feature (check your release).
  • A read-only list report on normal CDS views needs no BDEF at all – just projection and service.

Part 5 – Inbound: the CRM creates orders through a Web API (R18)

Why: a RAP BO is not only for Fiori. R18 – the external CRM creates orders through an API. The same BO gets three doors: other systems call it as a Web API (inbound), it calls the carrier's service (outbound, Part 6), and our code creates SAP standard documents through SAP's released RAP BOs instead of BAPIs (Part 7).

Integration map for R17 and R18: inbound Web API from the external CRM through destination, communication arrangement and the ZAPI_SalesOrder_O4 binding into the RAP BO; outbound through a service consumption model, client proxy and outbound arrangement to the carrier's API; local EML call to I_SalesOrderTP; notes on events, CAP and never calling remote systems in the late save

5.1 A second binding on the same service

A Web API service binding has no UI-specific behavior and is meant for system-to-system calls. The Fiori app keeps its UI binding ZUI_SalesOrder_O4; the CRM gets its own binding:

  • Service definition ZUI_SalesOrder (or a separate API service definition that exposes ZC_SalesOrder / ZC_SalesOrderItem, or a projection made for the API).
  • Service binding ZAPI_SalesOrder_O4, binding type OData V4 – Web API, then publish.

Step

SAP Business AI Platform, ABAP environment / S/4HANA Cloud

S/4HANA on-premise / private cloud

Who may call?

Communication scenario (ADT, inbound): add the inbound service of the binding; for OData V2 its ID ends with _IWSG. Its authorization defaults give the caller e.g. ZAO_SO

Service published in the gateway (/IWFND/V4_ADMIN service group for V4, or the ADT Publish button), PFCG role with S_SERVICE and ZAO_SO

Technical user

Communication user (app *Maintain Communication Users*)

System user (SU01) with the role from the line above

Connection

Communication system + communication arrangement for the scenario → shows the service URL

Gateway URL /sap/opu/odata4/...

Checks in the BO

Same validations, authorization and feature control as for Fiori users

Same as on the left

POST https://<host>/sap/opu/odata4/sap/zapi_salesorder_o4/srvd_a2x/sap/zui_salesorder/0001/SalesOrder
Content-Type: application/json

{ "CustomerID": "0010100001", "OrderDate": "2026-11-21", "Currency": "EUR",
"_Item": [ { "ItemNo": "000010", "MaterialID": "MAT-001", "Quantity": 5, "Unit": "ST",
"NetPrice": 10.00, "Currency": "EUR" } ] }
  • srvd_a2x in the URL marks a Web API service (a UI service has srvd). Copy the exact URL from the binding or the communication arrangement.
  • The request runs through the same interaction phase and save sequence as Fiori: setInitialStatus (R4), calculateTotal (R5), validateCustomer (R6) and the number assigned on save (R9) all apply. The CRM works on active data; draft is meant for UI services.
  • A deep insert (header + _Item in one POST) works because of the composition.
  • The CRM never sees a password in code: it authenticates as the communication user, and the BO's authorization checks run for that user.

Part 6 – Outbound: calling the carrier's service (R17)

The query provider of Part 3 needs real data. If the carrier offers an OData service, import its metadata into a service consumption model – ADT generates abstract entities and a proxy model, and you call it through a client proxy.

  • 1. Get the $metadata (EDMX) file of the carrier's service.
  • 2. ADT: New → *Service Consumption Model* → OData → import the EDMX; ADT generates abstract entities (e.g. ZSC_DELIVERY with ZA_DeliveryStatus) and shows sample code.
  • 3. Cloud: outbound communication scenario + outbound service, then a communication arrangement with the carrier's URL and credentials (on-premise: an HTTP destination in SM59).
  • 4. Call it from the query provider, an action or a background job.
" Read delivery data from the carrier's OData V4 service (service consumption model ZSC_DELIVERY)
DATA deliveries TYPE STANDARD TABLE OF za_deliverystatus WITH EMPTY KEY.
TRY.
DATA(destination) = cl_http_destination_provider=>create_by_comm_arrangement(
comm_scenario = 'ZDELIVERY_OUT'
service_id    = 'ZDELIVERY_OUT_REST' ).
DATA(http_client) = cl_web_http_client_manager=>create_by_http_destination( destination ).

DATA(proxy) = /iwbep/cl_cp_factory_remote=>create_v4_remote_proxy(
is_proxy_model_key       = VALUE #( repository_id       = 'DEFAULT'
proxy_model_id      = 'ZSC_DELIVERY'
proxy_model_version = '0001' )
io_http_client           = http_client
iv_relative_service_root = '/sap/opu/odata4/carrier/delivery/0001/' ).

DATA(request) = proxy->create_resource_for_entity_set( 'DELIVERYSTATUS' )->create_request_for_read( ).
request->set_top( 50 )->set_skip( 0 ).
DATA(response) = request->execute( ).
response->get_business_data( IMPORTING et_business_data = deliveries ).
CATCH cx_http_dest_provider_error cx_web_http_client_error /iwbep/cx_gateway INTO DATA(error).
" log error->get_text( ) and return a message
ENDTRY.

Inside the query provider, pass paging, count and filter on to the carrier instead of loading everything:

METHOD if_rap_query_provider~select.
DATA(request) = proxy->create_resource_for_entity_set( 'DELIVERYSTATUS' )->create_request_for_read( ).

DATA(top)  = io_request->get_paging( )->get_page_size( ).
DATA(skip) = io_request->get_paging( )->get_offset( ).
IF top <> if_rap_query_paging=>page_size_unlimited.
request->set_top( top ).
ENDIF.
request->set_skip( skip ).
" filter: build one with request->create_filter_factory( )
"         from io_request->get_filter( )->get_as_ranges( )
IF io_request->is_total_numb_of_rec_requested( ).
request->request_count( ).
ENDIF.

DATA(response) = request->execute( ).
DATA remote TYPE STANDARD TABLE OF za_deliverystatus WITH EMPTY KEY.
response->get_business_data( IMPORTING et_business_data = remote ).

IF io_request->is_total_numb_of_rec_requested( ).
io_response->set_total_number_of_records( response->get_count( ) ).
ENDIF.
IF io_request->is_data_requested( ).
io_response->set_data( CORRESPONDING tt_status( remote ) ).   " remote fields -> custom entity fields
ENDIF.
ENDMETHOD.
  • ADT's sample code in the service consumption model shows the exact entity set name and proxy key – copy from there. For an OData V2 service the generated sample uses cl_web_odata_client_factory=>create_v2_remote_proxy.
  • Wrap the calls in TRY ... CATCH and raise an exception based on cx_rap_query_provider so Fiori shows a message instead of a dump.
  • Many carriers offer plain REST/JSON instead of OData: call it with cl_web_http_client_manager directly and parse the JSON with a released JSON API (check which one your release offers). SOAP works through a consumption model for WSDL.
  • Never hard-code URLs or passwords – the communication arrangement (or SM59 destination) holds them.
  • Never call a remote service in the late save. Read in the interaction phase (as here), or send changes asynchronously (events → 10 · Business Events & Event-Driven RAP, bgPF → 09 · Unmanaged Scenario & Save Variants).

Part 7 – Released BOs: creating the standard sales order with I_SalesOrderTP (R18)

R18, part 2 – once our order is approved, the standard S/4HANA sales order (VBAK/VBAP) must be created from it. SAP releases many business objects as RAP BO interfaces – I_SalesOrderTP, I_PurchaseOrderTP_2, I_BusinessPartnerTP_3 and others. For clean core, creating a standard sales order from custom code means EML on I_SalesOrderTP, not BAPI_SALESORDER_CREATEFROMDAT2.

BAPI_SALESORDER_CREATEFROMDAT2 with structures, RETURN table and BAPI_TRANSACTION_COMMIT compared with MODIFY ENTITIES OF I_SalesOrderTP, FAILED and REPORTED, COMMIT ENTITIES BEGIN, CONVERT KEY from %pid and COMMIT ENTITIES END
" Create a standard sales order (header + item) from our approved order with the released RAP BO
MODIFY ENTITIES OF i_salesordertp
ENTITY SalesOrder
CREATE FIELDS ( SalesOrderType SalesOrganization DistributionChannel OrganizationDivision SoldToParty )
WITH VALUE #( ( %cid                 = 'SO1'
SalesOrderType       = 'TA'
SalesOrganization    = '1010'
DistributionChannel  = '10'
OrganizationDivision = '00'
SoldToParty          = '0010100001' ) )   " CustomerID of our order
CREATE BY \_Item FIELDS ( Product RequestedQuantity )
WITH VALUE #( ( %cid_ref = 'SO1'
%target  = VALUE #( ( %cid              = 'IT1'
Product           = 'MAT-001'
RequestedQuantity = 5 ) ) ) )
MAPPED   DATA(so_mapped)
FAILED   DATA(so_failed)
REPORTED DATA(so_reported).

IF so_failed IS INITIAL.
" I_SalesOrderTP uses late numbering: MAPPED has only a %pid - convert it inside the commit scope
COMMIT ENTITIES BEGIN RESPONSE OF i_salesordertp
FAILED   DATA(save_failed)
REPORTED DATA(save_reported).
CONVERT KEY OF i_salesordertp
FROM so_mapped-salesorder[ 1 ]-%pid
TO DATA(so_key).                                      " so_key-SalesOrder = the new SD order number
COMMIT ENTITIES END.
ENDIF.

COMMIT ENTITIES, the commit scope and CONVERT KEY are explained once on 08 · EML; here only what is special about a released SAP BO.

BAPI

Released RAP BO (EML)

Call

CALL FUNCTION 'BAPI_SALESORDER_CREATEFROMDAT2' with header/item/partner structures and X-flag structures

MODIFY ENTITIES OF i_salesordertp; FIELDS ( ... ) sets %control

Errors

RETURN table – you scan for type E/A

FAILED + REPORTED per entity

Commit

BAPI_TRANSACTION_COMMIT / ROLLBACK

COMMIT ENTITIES / ROLLBACK ENTITIES

New number

Exporting parameter SALESDOCUMENT

CONVERT KEY from %pid inside COMMIT ENTITIES BEGIN ... END

ABAP Cloud / clean core

Not released for ABAP Cloud – a classic API (clean core level B)

Released (C1 contract), upgrade-stable – level A

Same checks as the Fiori app

Partly

Yes – the same BO behind SAP's standard Fiori apps

7.1 Where to call it in the scenario

  • Inside our own behavior pool (e.g. in approve): run only the MODIFY ENTITIES OF i_salesordertp – no COMMIT ENTITIES. Both BOs are then saved together when our transaction commits, but an SD error blocks the approval, and the SD number is known only after the save.
  • After the approval, in its own transaction: the code above with COMMIT ENTITIES and CONVERT KEY, started from the consumer of the event OrderApproved (→ 10 · Business Events & Event-Driven RAP) or from a background operation (bgPF → 09 · Unmanaged Scenario & Save Variants). The approval is never blocked by SD, and the new number is available at once. Which EML statements are allowed in such a handler depends on the release – check your release.
  • Field and entity names: check them in ADT (open I_SalesOrderTP, look at the BDEF and the *API State* tab) or on the SAP Business Accelerator Hub (Business Object Interfaces). Mandatory fields depend on your SD customizing.
  • Find released BOs in ADT: project explorer → *Released Objects*, or filter by API state *Released*.
  • A C1-released BO interface whose view has @ObjectModel.supportedCapabilities: [#UI_PROVIDER_PROJECTION_SOURCE] can even be the base of your own UI service (a projection on SAP's BO) – check your release.

Common mistakes

  • Expecting the SD order number in MAPPED → it holds only the %pid; use CONVERT KEY.
  • Calling BAPI_TRANSACTION_COMMIT or COMMIT WORK after EML → use COMMIT ENTITIES, and never inside a behavior pool.

Part 8 – RAP and CAP together

Many BTP landscapes have both: RAP in S/4HANA or the ABAP environment, and CAP (SAP Cloud Application Programming Model, Node.js or Java) for side-by-side apps – the external CRM integration of R18 could be one. They talk OData to each other, in both directions:

Direction

How

Key objects

CAP → RAP (a CAP app reads or creates sales orders)

CAP imports the RAP Web API's $metadata (cds import) and calls it as a remote service

BTP destination (URL + communication user) → communication arrangement → ZAPI_SalesOrder_O4 → BO → HANA

RAP → CAP (RAP reads data owned by a CAP app)

RAP imports the CAP service's $metadata into a service consumption model and calls it via the client proxy (Part 6), e.g. in a custom entity

Outbound communication scenario + arrangement to the CAP app's URL

Asynchronous, both ways

Business events (RAP RAISE ENTITY EVENT → Event Mesh → CAP handler, or a CAP event → RAP event consumption model)

→ see 10 · Business Events & Event-Driven RAP

  • Authentication between them is technical: a communication user or OAuth client – never a personal user or a password in code.
  • Keep the UI binding for the Fiori app and the Web API binding for systems – they serve different consumers, and mixing them up is a common mistake.

Part 9 – Interview questions

Q1. How do you handle attachments in RAP?

As large objects: a RAWSTRING field annotated with @Semantics.largeObject (pointing to a MIME type and a file name field) becomes an OData stream, and Fiori elements shows upload and download automatically. In a draft BO the draft table needs the same fields. For several files per order I model a child entity; for mass data from a file I use an action with a file parameter.

Q2. How would you build an Excel upload for order items?

An action uploadItems with a deep parameter: an abstract entity with a large-object field, described by an abstract BDEF with hierarchy. The handler reads the sheet with the released XCO_CP_XLSX API and creates the items with MODIFY ENTITIES ... IN LOCAL MODE CREATE BY \_Item, so validations, the total and draft work as for typed items. Never INSERT into the table directly. On older releases the file goes into a LOB field first and an action parses it.

Q3. What is a custom entity and what must its query provider do?

A CDS entity without SQL data source; its rows come from an ABAP class implementing if_rap_query_provider – an unmanaged query, used for remote or computed read-only data such as a carrier's delivery status. The class must handle paging, filter, sort and count itself, read paging and sort when they are requested, and count before paging.

Q4. Virtual element or calculated CDS element?

A calculated CDS element is computed by the database, so it is fast and can be filtered and sorted. A virtual element is calculated in ABAP after the read (if_sadl_exit_calc_element_read), only for OData requests – not in EML or ABAP SQL. I use a virtual element only when the logic can't be expressed in CDS.

Q5. How do you expose a RAP BO as a Web API?

A second service binding of type OData V4 – Web API (ZAPI_SalesOrder_O4) on the same or an API-specific service definition. In the cloud: a communication scenario with the service as inbound service, then a communication system, communication user and communication arrangement; the caller authenticates as that user. On-premise the service is published and protected with roles (S_SERVICE). The same validations and authorization run as for the Fiori app.

Q6. How do you call a remote OData service from RAP?

Import its $metadata into a service consumption model, which generates abstract entities and a proxy model. At runtime: destination from the communication arrangement, HTTP client, client proxy, read request with top/skip/filter, get_business_data. Typically inside a custom entity's query provider. Never with hard-coded URLs or passwords, and never in the late save.

Q7. How do you create a sales order in S/4HANA Cloud from custom code?

With EML on the released RAP BO interface I_SalesOrderTP: MODIFY ENTITIES with header and CREATE BY \_Item, check FAILED and REPORTED, then COMMIT ENTITIES BEGIN, CONVERT KEY to turn the %pid into the late-numbered order number, COMMIT ENTITIES END. BAPIs are not released for ABAP Cloud. Inside my own behavior pool I only call MODIFY and let the framework commit both BOs.

Q8. Why must a RAP BO never call a remote system in the save sequence?

After the point of no return the save must not fail, and a remote call can be slow or fail at any time; it also cannot be rolled back with the database. So I read remote data in the interaction phase (e.g. in a query provider) and send changes asynchronously – with a business event or bgPF after the commit.

🏠 Start Here · ◀ 10 · Business Events · 12 · Extensibility & Testing ▶ · 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 | EHS ABAP | HR ABAP | BW | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP