Below is the link to reference/examples of using Azure API management policy
There’s an example there on how to Mask Asynchronous calls as Synchronous API however for my requirement it’s not enough.
The target API behaves as follow:
- All operations are POST and asynchronous.
- To get the results of any operation a second API needs to be called and it’s expecting the transaction id.
- API expects a payload in command manner (args parameter) instead of proper JSON name/value pair.
Requirement: API should return the results in synchronous manner.
Solution:
API Callout Policy in API Management.
Steps:
- Create a GET operation and via policy rewrite the operation to POST
- Create a JSON transformation logic in the inbound policy and execute the backend API.
- Create a JSON transformation logic in outbound policy and add a retry policy to execute the second API that returns the result passing the transaction id from #2
- Return the results from second API.
Policy Code:
application/json @{ var paramFromRequest = Uri.UnescapeDataString(context.Request.OriginalUrl.Query.GetValueOrDefault("paramFromRequest")); JObject transBody = new JObject(); transBody.Add("source", new JObject { {"someproperty", "fixvalue"}, {"someproperty2", "fixvalue2"}, }); //Add all json properties as arg transBody.Add("args", JToken.FromObject(new[] { paramFromRequest })); return transBody.ToString(); } @(context.Request.Body.As (true)) POST @{ var url = context.Api.ServiceUrl+ "{{SECONDBACKENDAPI_URL}}"; return url; } POST @(context.Variables.GetValueOrDefault ("authorization")) application/json @(context.Variables.GetValueOrDefault ("jsonPayload")) ())" /> @((context.Variables.GetValueOrDefault ("results")["{{PROPERTYNAME IN JSON OBJECT THAT CONTAINS THE RESULT}}"].ToString()))