Sub topic 19
Reading and creating purchasing data through APIs
This chapter assumes you know the procure-to-pay flow from the earlier chapters: purchase order, goods receipt, invoice receipt, and document flow. It also assumes basic ABAP and that you can read a REST request. You will read purchase order data in three ways and create a purchase order with a BAPI.
Choosing an access method
SAP S/4HANA offers several ways to reach purchasing data. The right one depends on where your code runs and whether you read or write.
| Need | Typical choice | Runs where |
|---|---|---|
| Read data inside ABAP | ABAP SQL on tables or CDS views | In the system |
| Read data from outside | OData service such as API_PURCHASEORDER_PROCESS_SRV | Over HTTP |
| Create or change from ABAP | BAPI such as BAPI_PO_CREATE1 | In the system |
| Create or change from outside | OData service, or a BAPI exposed through a remote channel | Over HTTP or RFC |
The core rule is that writes should go through a released interface. Business logic, authority checks, number ranges and accounting postings run inside it. Do not insert rows into tables such as EKKO or EKPO directly.
Reading PO history with ABAP SQL
Purchase order history lives in table EKBE. Each row is one follow-on document for a PO item. The field VGABE (transaction/event type) tells you what kind it is: 1 is a goods receipt and 2 is an invoice receipt.
SELECT ebeln, ebelp, vgabe, belnr, buzei, menge
FROM ekbe
WHERE ebeln = @lv_ebeln
ORDER BY ebelp, belnr
INTO TABLE @DATA(lt_history).
LOOP AT lt_history INTO DATA(ls_hist).
" VGABE 1 = goods receipt, 2 = invoice receipt
WRITE: / ls_hist-ebelp, ls_hist-vgabe, ls_hist-belnr, ls_hist-menge.
ENDLOOP.The snippet assumes lv_ebeln is declared and filled with a PO number that exists. A few points to check:
- The host variable
@lv_ebelnuses the@escape required in the new ABAP SQL syntax. When you use it, every host variable in that statement needs it, and the field list needs commas. - Sorting by item and then document number gives a readable sequence, but it is not a strict time order. Use the posting date field if you need chronology.
- EKBE also holds other event types, such as delivery costs and subsequent debits. Filter on VGABE if you only want receipts.
- Quantity in EKBE is in the order unit. Check the unit before you compare it with the item quantity.
Reading through OData
An external application cannot run ABAP SQL. It calls an OData service instead. SAP delivers the service APIPURCHASEORDERPROCESS_SRV for purchase orders. The request below reads five orders and returns only four header fields.
GET /sap/opu/odata/sap/API_PURCHASEORDER_PROCESS_SRV/A_PurchaseOrder?$top=5&$select=PurchaseOrder,Supplier,PurchaseOrderType,CompanyCode HTTP/1.1
Accept: application/jsonThe two query options matter for performance:
$top=5limits the number of rows. Without it the service applies its own default, and a large system can return a lot of data.$selectlimits the columns. This keeps the payload small.
In real use you also send authentication, usually basic authentication or OAuth, and the host name. The user needs authorizations for the service and for the purchasing data itself. A 403 response usually means the service is not activated or the user lacks a role. Check the service in the Gateway service maintenance and the user's roles.
You can also follow relations. The entity APurchaseOrder has navigation properties such as `toPurchaseOrderItem. Use $expand=to_PurchaseOrderItem to fetch items with the header. Expanding makes responses larger, so combine it with $top and $select`.
Creating a PO with BAPI_PO_CREATE1
A BAPI (Business Application Programming Interface) is a function module that SAP supports as a stable entry point to a business object. BAPIPOCREATE1 creates a purchase order.
Two features of this BAPI cause most mistakes.
- Paired "X" structures. Each data structure has a twin, such as POHEADER and POHEADERX. The twin contains a flag for every field you supplied. A field without its flag is ignored, even if it has a value.
- No automatic commit. The BAPI prepares the document in memory. Your program must call BAPITRANSACTIONCOMMIT, or the PO is never saved.
DATA: lv_ebeln TYPE bapimepoheader-po_number,
lt_return TYPE STANDARD TABLE OF bapiret2 WITH EMPTY KEY,
lt_item TYPE STANDARD TABLE OF bapimepoitem WITH EMPTY KEY,
lt_itemx TYPE STANDARD TABLE OF bapimepoitemx WITH EMPTY KEY,
lt_sched TYPE STANDARD TABLE OF bapimeposchedule WITH EMPTY KEY,
lt_schedx TYPE STANDARD TABLE OF bapimeposchedulx WITH EMPTY KEY.
" Values below are placeholders; use data that exists in your system.
DATA(ls_header) = VALUE bapimepoheader(
comp_code = '1710' doc_type = 'NB' vendor = '0017300001'
purch_org = '1710' pur_group = '001' ).
DATA(ls_headerx) = VALUE bapimepoheaderx(
comp_code = abap_true doc_type = abap_true vendor = abap_true
purch_org = abap_true pur_group = abap_true ).
lt_item = VALUE #( ( po_item = '00010' material = 'TG11' plant = '1710' quantity = 10 ) ).
lt_itemx = VALUE #( ( po_item = '00010' po_itemx = abap_true material = abap_true
plant = abap_true quantity = abap_true ) ).
lt_sched = VALUE #( ( po_item = '00010' sched_line = '0001'
delivery_date = sy-datum + 14 quantity = 10 ) ).
lt_schedx = VALUE #( ( po_item = '00010' sched_line = '0001' po_itemx = abap_true
sched_linex = abap_true delivery_date = abap_true quantity = abap_true ) ).
CALL FUNCTION 'BAPI_PO_CREATE1'
EXPORTING
poheader = ls_header
poheaderx = ls_headerx
IMPORTING
exppurchaseorder = lv_ebeln
TABLES
return = lt_return
poitem = lt_item
poitemx = lt_itemx
poschedule = lt_sched
poschedulex = lt_schedx.
IF line_exists( lt_return[ type = 'E' ] ) OR line_exists( lt_return[ type = 'A' ] ).
CALL FUNCTION 'BAPI_TRANSACTION_ROLLBACK'.
ELSE.
CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' EXPORTING wait = abap_true.
ENDIF.The values for company code, vendor, material and plant are placeholders. They must exist in your system and be consistent with each other. The material must be extended to the plant, and the supplier must be usable for the purchasing organization.
Reading the RETURN table
Every BAPI reports problems in a table of type BAPIRET2 rather than raising an exception. The field TYPE holds the severity.
| TYPE | Meaning | What to do |
|---|---|---|
| S | Success | Continue |
| I | Information | Log it |
| W | Warning | Review, but the document may still be created |
| E | Error | Roll back |
| A | Abort | Roll back |
The example tests for E and A only. Warnings do not stop the commit, so decide in your own code whether any warning should. After a successful commit, lv_ebeln holds the new PO number. If the call failed, it is empty. Print the messages from lt_return, using the fields MESSAGE, ID and NUMBER, so a user can see why.
Common errors
- The PO is created with missing fields. The matching X flag was not set.
- The PO number is returned but the document does not exist. The program ended without a commit.
- Item errors that mention the schedule line. A PO item needs a schedule line with a delivery date and quantity, and the schedule X structure must flag both.
- Messages about account assignment. Items with an account assignment category need the account assignment tables, which this example leaves out.
- Different results in test mode. Pass
testrun = abap_trueto validate without saving, and do not commit afterwards.
Newer interfaces
BAPIs remain widely used, and they still work in S/4HANA. For new development, SAP promotes released APIs. These include the OData services shown above and, for in-system extension code, released ABAP classes and CDS views. Prefer a released API where one exists, because SAP keeps it stable across upgrades. For a given use case, check SAP's API catalog for the current state.
Exercise
A program calls BAPIPOCREATE1 with a full POHEADER and POITEM, gets back a PO number, and the RETURN table has no error. A colleague finds that the PO cannot be displayed, and the material and plant fields on the item are blank in a second test. Name two separate causes and the fix for each.
Show answer
First, the program may not have called BAPITRANSACTIONCOMMIT, so the number was allocated but the document was never saved; fix it by committing when RETURN has no E or A message. Second, the POITEMX structure may not flag material and plant with abap_true, so the BAPI ignored those values; fix it by setting the flag for every field supplied in POITEM.
Exercise
You need to show five purchase orders with supplier and company code in an external web app. Which access method fits, and which two query options keep the response small?
Show answer
Use the OData service APIPURCHASEORDERPROCESSSRV with a GET on APurchaseOrder. Add $top=5 to limit the rows and $select=PurchaseOrder,Supplier,CompanyCode to limit the columns.