SAP CAP: Consume SAP API Hub Sandbox Data as an external service Part- 1

What: 

This blog post is about how to consume external services from BTP after deploying your service/application. Here we take Business Partner API for this example.

How:

Let’s not going into detail how to create CAP project. I am starting from importing the API_BUSINESS_PARTNER from api.sap.com.

Download the EDMX file from api hub and copy it to the main folder.

   

Now run cds import command

$ cds import API_BUSINESS_PARTNER.edmx

The API_BUSINESS_PARTNER.edmx has been imported to the folder srv/external, also it generates API_BUSINESS_PARTNER.csn file. This CSN file used by the CDS framework.

 

It updates the package.json file in cds requires section with the external service.

Now lets create a business-service.cds file to define our Service.

using { API_BUSINESS_PARTNER as abp } from './external/API_BUSINESS_PARTNER.csn'; service BusinessService { entity A_BusinessPartner as projection on abp.A_BusinessPartner { key BusinessPartner, Customer, BusinessPartnerFullName, BusinessPartnerGrouping, BusinessPartnerUUID, OrganizationBPName1 }
}

Create a custom handler business-service.js file to read our entity.

const cds = require('@sap/cds');
module.exports = cds.service.impl(async function() { const bp = await cds.connect.to('API_BUSINESS_PARTNER'); this.on('READ', 'A_BusinessPartner', async req => { return bp.run(req.query); });
});

For accessing Sandbox data from our project we need to provide the URL of the sandbox and do the changes in our package.json file

"cds": { "requires": { "API_BUSINESS_PARTNER": { "kind": "odata-v2", "model": "srv/external/API_BUSINESS_PARTNER", "credentials": { "url": "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER" } } } }

Let check our project –

$ cds watch

Click on A_BusinessPartner

Oops!! As we are accessing sandbox data. We need to provide the API key, which you will find in api.sap.com account. Which is unique api key. Copy the api key from api hub and make some changes in package.json file.

"credentials": { "url": "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_BUSINESS_PARTNER", "headers": { "APIKey": "<api-key>" } }

Now again check your service in browser

Data is coming from the sanbox api hub.

In this post we are able to get data from an external service sandbox api hub.