Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
divyamary
Contributor
SAP Cloud Platform API Management enables you to manage the end to end lifecycle of your APIs, expose your APIs securely to your developer / partner ecosystem for omni-channel access.  Since the APIs are managed are SAP Cloud Platform API Management , it is easier to track whenever the target service endpoint is unavailable, detect any threat like a sudden spike in the number of API calls. SAP Cloud Platform Alert Notification enables providers to publish alerts and for consumers to subscribe to these alerts.  To know more about features, pricing and data center availability of SAP Cloud Platform Alert Notification service visit SAP Cloud Platform site.  Using SAP Cloud Platform Alert Notification service you can publish alerts from SAP Cloud Platform API Management to inform the consumer whenever such changes are detected.

In this blog series, we have showcased how to use the SAP Cloud Platform Alert Notification service to send alerts email, whenever the target service managed by SAP Cloud Platform API Management is unavailable. In the part 1 of the blog  the steps to configure a subscription in SAP Cloud Platform Alert Notification service, so that we can raise alerts whenever the target service managed by SAP Cloud Platform API Management is down was showcased. In this part 2 of the blog, we will learn the steps to publish alert to SAP Cloud Platform Alert Notification when the target service managed by SAP Cloud Platform API Management is unavailable.

Pre-requisite



To keep this blog simple,  we had used an existing API Proxy which is linked to an API Provider  which fetches the data from SAP Gateway ES5 system. To learn about creating API Provider, API Proxy on SAP Cloud Platform API Management visit us at developers.sap.com .

Logon to your SAP Cloud Platform trial and Navigate to the Neo Environment.



Navigate to the Services tab, search for API Management service tile and click to open SAP API Management service.



Click on link Access API Portal to open API Portal.

 



 

Store Alert Notification API credentials in Key Value map


 

In this section, we will learn how to store the API credentials generated from the SAP Cloud Platform Alert Notification service in the key value map store in secured way. This credentials can then be used later in the API Proxy execution flow to publish alerts via the Producer API from SAP Cloud Platform Alert Notification.

Navigate to Configure tab from the hamburger icon, then select Key Value Maps and click Create.



 

In the Create Key Value Map wizard, provide a name for the store say ANSCredentials, check the option Encrypt Key Value Map.  The name of the store would be used from the API Proxy Key value map policies and in case you would be providing a different name then use the same in the API Proxy policy as well.

Click on the Add button to add the following entries.

 















Key Value
user Client id generated by the SAP Cloud Platform Alert Notification
password Client Secret generated by the SAP Cloud Platform Alert Notification

 

Details to get your our own client id and secret from the SAP Cloud Platform Alert Notification is captured in this blog under section Acquiring API Access Credentials.

Note:-  The key field of the Entries would be used in the Key value map policies of the API Proxy and therefore in case you have provided a different key name then the same key name should be used in the policy.



Click on the Save button to persist the changes.


Update API Proxy to raise alert to SAP Cloud Platform Alert Notification


 

SAP Cloud Platform Alert Notification service provides producer API that can be used to raise custom alerts from SAP Cloud Platform API Management. The Producer API is a REST based API , which can be invoked either using Basic or OAuth authentication.  In this blog, we have used the basic authentication based approach.  To set the basic authentication header we will be using the Key value map policy to read the API credentials stored in the key value map named ANSCredentials and then later we will be using the BasicAuthentication policy to generate the credentials in Basic Auth format. To publish the alerts via the Producer API, we will be using a JavaScript policy.

In this section, you would learn how an existing API Proxy can be modified to raise alert to SAP Cloud Platform Alert Notification service  when the target service is down. To learn about creating API Provider, API Proxy on SAP Cloud Platform API Management visit us at developers.sap.com .

Navigate to Develop tab from the hamburger icon, then select the tab APIs and select any of your existing API Proxy.  In the blog we had used an API Proxy named SAPGatewayBasicDemo.



Click on the Policies to open up the Policy Designer



To enter the edit mode, click on the Edit button.



 

The policies to check for the target service unavailable would be attached to the proxy endpoint PostFlow response stream, so that we can read the status of the target service response. If the target server is down or un-available or the calls times out, it typically sets the response status as 503 .ie. Service Unavailable.

Select PostFlow from the ProxyEndPoint  section and then click on the + button next to the Key Value Map Policy available under the Mediation Policies segment.





In the Create policy screen specify the policy name say readANSCredentials, select Stream as Outgoing Response  and then click on the Add button.



 

Select the policy newly added readANSCredentials policy then add the following policy snippet to read the key value map from the map store named ANSCredentials and entries with key name user, password.
<KeyValueMapOperations mapIdentifier="ANSCredentials" async="true" continueOnError="false" enabled="true" xmlns="http://www.sap.com/apimgmt">
<Get assignTo="private.user" index="1">
<Key>
<Parameter>user</Parameter>
</Key>
</Get>
<Get assignTo="private.password" index="1">
<Key>
<Parameter>password</Parameter>
</Key>
</Get>
<Scope>environment</Scope>
</KeyValueMapOperations>

 

In the Condition String text box, enter the following snippet so that the Key Value map policy is executed only when the target response status code is 503, ie. service unavailable or the connection has timed out.
response.status.code = "503" or response.status.code = 503



 

Click on the + button next to the Basic Authentication Policy available under the Security Policies segment.

 



 

In the Create policy screen specify the policy name say setANSCredentials, select Stream as Outgoing Response  and then click on the Add button.



 

Select the policy newly added setANSCredentialspolicy then add the following policy snippet to encode the user, password read from the key value map policies into basic authentication format and store it a local flow variable named sapapim.anscredentials.
<BasicAuthentication async='true' continueOnError='false' enabled='true' xmlns='http://www.sap.com/apimgmt'>
<!-- Operation can be Encode or Decode -->
<Operation>Encode</Operation>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<User ref='private.user'></User>
<Password ref='private.password'></Password>
<AssignTo createNew="false">sapapim.anscredentials</AssignTo>
</BasicAuthentication>

In the Condition String text box, enter the following snippet so that the Basic Authentication map policy is executed only when the target response status code is 503, ie. service unavailable or the connection has timed out.
response.status.code = "503" or response.status.code = 503



 

Click on the + button next to the JavaScript Policy available under the Extension Policies segment.



 

In the Create policy screen specify the policy name say raiseAlerts, select Stream as Outgoing Response and then click on the Add button.



 

Select the policy newly added raiseAlert then add the following policy snippet to invoke the JavaScript named maincode.
<!-- this policy allows us to execute java script code during execution of an API Proxy -->
<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" xmlns='http://www.sap.com/apimgmt'>
<ResourceURL>jsc://maincode.js</ResourceURL>
</Javascript>

 

In the Condition String text box, enter the following snippet so that the Basic Authentication map policy is executed only when the target response status code is 503, ie. service unavailable or the connection has timed out.
response.status.code = "503" or response.status.code = 503

 



Click on the + button next to Scripts to add a new script named maincode.js

 



 

In the Create Script dialog, enter the name as maincode and then select Create for the Script dropdown. Click Add to add a Javascript named maincode.

 



 

Select the newly added JavaScript file maincode and in the Script Resource copy paste the following code snippet.
var headers = {
'Content-Type' : 'application/json;charset=utf-8',
'Accept' : 'application/json;charset=utf-8',
'Authorization' : context.getVariable("sapapim.anscredentials")
};

var payload = {
"eventType": "targetserviceunavailable",
"resource": {
"resourceName": context.getVariable("apiproxy.name"),
"resourceType": "app",
"tags": {
"env": "prod"
}
},
"severity": "FATAL",
"category": "ALERT",
"subject": "API Proxy " + context.getVariable("apiproxy.name") + " target server is down",
"body": "The target service for API Proxy is down. Logon to your API Portal dashboard for more information"
};

var myRequest = new Request("https://{your_sap_cloud_platform_alert_notification_producer_url}/v1/resource-events","POST",headers,JSON.stringify(payload));
var exchange = httpClient.send(myRequest);

 

Note :- The URL of the myRequest parameter of the above policy snippet would have to be changed to your SAP Cloud Platform Alert Notification producer API endpoint.



The policy snippet can be adjusted to custom the alert information based on your scenario. More about the producer APIs of SAP Cloud Platform Alert Notification is available in SAP API Business Hub.

Click on the update button to save all the policy changes



The default behavior of SAP Cloud Platform API Management is to ignore all the polices attached in the outgoing response stream in case of error received from the target server.  To process the polices in case of the target server response, the success.codes target endpoint properties can be set to 2xx,4xx,5xx. This would enable the policies to raise the alerts to SAP Cloud Platform Alert Notification service to be invoked in case of target server failure like service unavailable.  More details about the target endpoint properties is available in help documentation .

Navigate to the Target EndPoint Property tab, from the Target EndPoint Properties, click Add to enter the property as follows :-











Name Value
success.codes  2xx,4xx,5xx

 



Click on Save button to persist all the changes to API Proxy.

 



 

With this we have successfully updated the API Proxy to raise alert to SAP Cloud Platform Alert Notification service whenever the target service is unavailable.

Finally testing the flow


 

To simulate the service unavailable error, either we would have to bring the target service down or to simplify the testing, we can change the target endpoint to a target system that doesn't exist.  For testing the flow, API Provider was changed to a Provider named SAPGateway, which points to host or port that doesn’t exist.

Just invoke your API Proxy endpoint as show in the screenshot below

 



 

If the target service is not accessible or the connection times out you would receive an alert notification email to your subscribed email address provided in SAP Cloud Platform Alert Notification.

 



 

For more blogs on SAP Cloud Platform API Management visit us at SAP Community

 
1 Comment