Sub topic 12
Consuming a Released API with CAP
This chapter shows how a side-by-side extension reads data from SAP S/4HANA through a released OData API, using the SAP Cloud Application Programming Model (CAP). It assumes you know the basics of OData and REST, understand OAuth 2.0 at a conceptual level, and can read simple Node.js code. It also assumes you have seen the earlier chapters on released APIs and on destinations.
The goal: read core data without copying it
A clean core extension should depend on stable contracts and leave business data in the core system. In CAP, this pattern is called a remote service. You import the API definition into your project, declare how to reach it, and forward requests to it at runtime.
The extension built here, called PartnerReview, shows a read-only list of business partners. The data stays in S/4HANA. The extension stores nothing and depends only on the released Business Partner API, API_BUSINESS_PARTNER.
The request flow looks like this:
Step 1: Import the API definition
CAP needs a model of the remote API. For a released SAP API, you download its specification from the SAP Business Accelerator Hub. For OData V2 APIs, this is an EDMX file (the XML description of entities and properties). Save it in the project, for example as API_BUSINESS_PARTNER.edmx.
Then import it with the CAP command line tool:
cds import ./API_BUSINESS_PARTNER.edmx --as cdsThe command generates srv/external/API_BUSINESS_PARTNER.cds. It also adds an entry for the service under cds.requires in package.json, with the model path filled in.
Some points about this step:
- The generated CDS file is an imported copy of the contract. Treat it as generated code and do not edit it by hand. If the API changes, import it again.
- The import includes every entity in the API, often hundreds of types. Your own service projects only the few you need.
- Check that the API is released for your S/4HANA edition (for example in the released objects list). Importing an unreleased or internal service technically works, but it breaks the clean core rule that the extension depends only on released contracts.
Step 2: Declare the remote service
The remote service is configured under cds.requires. The entry connects the model from step 1 to a destination:
{
"cds": {
"requires": {
"API_BUSINESS_PARTNER": {
"kind": "odata-v2",
"model": "srv/external/API_BUSINESS_PARTNER",
"credentials": {
"destination": "S4HC_BP",
"path": "/sap/opu/odata/sap/API_BUSINESS_PARTNER"
}
}
}
}
}Each field has a job:
| Field | Meaning |
|---|---|
| `API_BUSINESS_PARTNER` | The name you pass to `cds.connect.to()`. It matches the service name in the imported model. |
| `kind` | The protocol adapter. Use `odata-v2` for V2 APIs and `odata` (or `odata-v4`) for V4 APIs. |
| `model` | Path to the imported CDS model, without the file extension. |
| `credentials.destination` | Name of the destination in the BTP Destination service. The destination holds the host, authentication type, and secrets. |
| `credentials.path` | The service path appended to the destination URL. |
The configuration contains no host name, user, or password. Those live in the destination, so the same code runs against a development, test, and production system by changing only the destination.
Local development with a URL
During development you may not have a bound Destination service. CAP lets you define a development profile with a direct URL:
{
"cds": {
"requires": {
"API_BUSINESS_PARTNER": {
"kind": "odata-v2",
"model": "srv/external/API_BUSINESS_PARTNER",
"[development]": {
"credentials": {
"url": "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER",
"headers": { "APIKey": "<your-api-key>" }
}
},
"[production]": {
"credentials": {
"destination": "S4HC_BP",
"path": "/sap/opu/odata/sap/API_BUSINESS_PARTNER"
}
}
}
}
}
}Do not commit real API keys. Keep them in a git-ignored .cdsrc-private.json or in environment variables. The [development] and [production] blocks are CAP profiles, selected by NODE_ENV or the --profile option.
Step 3: Project only what you need
The service definition exposes a narrow view of the imported API:
using { API_BUSINESS_PARTNER as bp } from './external/API_BUSINESS_PARTNER';
service PartnerReview {
@readonly
entity BusinessPartners as projection on bp.A_BusinessPartner {
key BusinessPartner,
BusinessPartnerFullName,
BusinessPartnerIsBlocked
};
}This projection has three effects:
- Your API exposes three fields. Consumers do not see the other fields the S/4HANA API offers.
- CAP translates queries on
BusinessPartnersinto queries onA_BusinessPartner, so only the selected fields are requested from the core. @readonlyrejects create, update, and delete requests before they reach S/4HANA.
Because the entity is a projection on an external entity, CAP does not create a database table for it. This matters when you deploy. If you deploy a database schema, no table for BusinessPartners appears, and that is correct.
Step 4: Forward requests in a handler
A projection on an external entity has no data source of its own. CAP does not forward the request by default, so you must write a handler:
const cds = require('@sap/cds')
module.exports = class PartnerReview extends cds.ApplicationService {
async init() {
const bp = await cds.connect.to('API_BUSINESS_PARTNER')
this.on('READ', 'BusinessPartners', req => bp.run(req.query))
return super.init()
}
}The handler does three things:
cds.connect.to('API_BUSINESS_PARTNER')creates the remote service client from thecds.requiresentry. It resolves the destination at request time.this.on('READ', 'BusinessPartners', ...)registers a handler for read requests on the projected entity.bp.run(req.query)sends the CAP query to the remote service. CAP converts it into an OData V2 request, including$select,$filter,$top, and$orderbywhen the adapter supports them, and returns the result as the response.
Because the incoming query is passed through, paging and filtering done by the client reach S/4HANA. The extension does not load all partners and filter them in memory.
Name the file so CAP finds it
CAP matches a service implementation to a service definition by file name. If the definition is srv/partner-review.cds, put the handler in srv/partner-review.js. A mismatch produces a service that starts and answers with an error such as "no handler found" or returns an empty response, because the READ request has no handler to run.
Running and testing
Start the server in watch mode:
cds watchThen request data:
curl "http://localhost:4004/odata/v4/partner-review/BusinessPartners?\$top=5&\$select=BusinessPartner,BusinessPartnerFullName"You get an OData V4 response from your service, even though the upstream API uses OData V2. CAP maps between the two protocols. This is useful because your consumers see one consistent interface regardless of the protocol of the underlying API.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot find module` or the model is not found | The `model` path points to the wrong folder, or you included the extension. | Use the path without `.cds`, relative to the project root. |
| `Failed to load destination` or a 404 for the destination | The destination name does not exist in the subaccount, or the app is not bound to a Destination service instance. | Check the name, and bind the Destination and Connectivity services to the app. |
| 401 or 403 from S/4HANA | The technical user or the OAuth client lacks authorization for the API's communication scenario. | In S/4HANA, check the communication arrangement and its assigned scenario. |
| 404 on the API path | `credentials.path` does not match the service path, or the destination URL already includes the path. | Put the path in only one place. |
| Empty list from the service | No handler is registered, or the handler file name does not match the service. | Match the file names and check the entity name in `this.on`. |
| Write requests fail | The projection is `@readonly`, or the API does not allow the operation. | This is intended. Remove `@readonly` only if you need writes and the API supports them. |
Design considerations
- Forward or replicate. Forwarding keeps one source of truth and always shows current data. Replication, for example by consuming events and storing a copy, gives faster reads and independence from the core, but creates a second copy that can become stale. The later chapter on events covers the replication option.
- Authorization. The identity used against S/4HANA depends on the destination's authentication type. A technical user shows every user the same data. Principal propagation, covered in the authentication chapter, makes S/4HANA apply the real user's authorizations.
- Contract stability. Because you depend on a released API, SAP commits to compatibility rules for it. Even so, keep integration tests that call the API, so you notice changes in behavior early.
- Minimal projection. Every field you project is a field you depend on. Keep the list short.
Exercise
A teammate adds entity Orders as projection on sales.A_SalesOrder to a CAP service, imports the API, and configures cds.requires correctly. Requests to /Orders return an empty list although S/4HANA has orders. The service starts without errors. What is the most likely cause, and what is the fix?
Show answer
The projection is on an external entity, so CAP has no database table behind it and does not forward the request on its own. No READ handler is registered for Orders, or the handler file does not match the service file name. Add const sales = await cds.connect.to('API_SALES_ORDER_SRV') in init() and register this.on('READ', 'Orders', req => sales.run(req.query)), and name the file to match the service definition.
Exercise
Why does the package.json entry use a destination name instead of the S/4HANA host and credentials, and how does this help when moving from a test to a production system?
Show answer
The destination in the BTP subaccount stores the host, authentication type, and secrets. The code and configuration only reference its name, so no credentials appear in the source repository. To target another system, you create or change the destination with the same name in the other subaccount, and the application code stays the same.