Executing simple REST requests with SAP CAP applications
The original version is maintained here.
Executing simple REST requests is easy with the SAP Cloud Application Programming Model. All you need to know is the required configuration. In this post, we will explore a simple example using a placeholder api with Todos. Let’s get started.
The first step to using the REST service is to define it. You can do the configuration in several places, but for simplicity, I will use the package.json. First, you need to configure a destination, which you can do with a code block like this:
Note that this is a simple example, i.e., we are not using the destination service available on the SAP BTP, nor any abstractions that might be desirable. It is just a static URL that we are pointing to.
Defining the CAP service
Next, we will define the service. We use this service, take the request data and pass it to the external rest service. We then take the response from the external rest service and return it to the user of our service.
The service definition has nothing to do with performing the REST request with your CAP application. Still, since we’re simply going to pass the input and return the output of our service to the external service, you might want to see the service definition. So here it is:
Making the REST request
Since we are using a function and an action, we need to create an implementation for them. Within this implementation, there are two steps you need to do to execute the request. First, you need to connect to the external rest service. This returns a promise that resolves to an appropriate service instance. Then you can execute your requests on this service instance. The implementation might look like this:
Again, there may be better options if you don’t work with the external data at all.
Testing the service
Now we can use exploratory tests to test our implementation. For the function, we could open the URL http://localhost:4004/task/getTodos() in our browser. We’ll use a REST client here. You will see the response:
It would help if you used a rest client for the action. Executing a post on http://localhost:4004/task/createTodo results in the response:
Making REST calls with CAP is easy
Now, this was a minimal example, with no authentication or abstraction. The reality is always more complex than these example models. Now you know how to get started with external rest services and as you’ve seen, it’s not that hard.
Stay curious and enjoy the process!