How to fetch a JSON property in the response body through Azure APIM policies

Vijay Sharma 0 Reputation points
2023-04-29T20:06:42.33+00:00

Hi,

My requirement is to call an OAuth token URL, get the OAuth token in the response body and store it in a cache. The value from cache will be used in next API call. I am able to get the OAuth token via below code in the response body. However, I cannot fetch the token from response body to store it in cache store.

After setting the inbound set-body, I get the response as below. But I cannot figure out how can I fetch the value of access_token from this response body. Can anyone please help me out here?

{
	"access_token": "access_token_some_value",
	"expires_in": 86400,
	"token_type": "Bearer"
}
<policies>
    <inbound>
        <base />
        <set-body template="liquid">
           {
              "client_id": "{{ClientId-named-value}}",
              "client_secret": "{{clientsecret-named-value}}",
              "audience": "{{audience-named-value}}",
              "grant_type": "{{granttype-named-value}}"
            }
            </set-body>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <set-body>@{
			var response = context.Response.Body.As<JObject>();
	        return response.ToString();
      	}
		</set-body>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>
Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,455 questions
{count} votes

1 answer

Sort by: Most helpful
  1. MuthuKumaranMurugaachari-MSFT 22,441 Reputation points Moderator
    2023-05-01T15:43:22.67+00:00

    Vijay Sharma Thanks for posting your question in Microsoft Q&A. Based on your description, you got JSON response from API call and like to retrieve access_token from the response body.

    I used the sample response above and using set-body liquid template, you can set the body with access token as below:

    <outbound>
            <set-body template="liquid">
            {
                "access_token": "{{body.access_token}}"
          	}
            </set-body>
            <base />
        </outbound>
    

    Output:

    User's image

    If you are looking to set it in a variable for storing it in cache, you can try the below snippet:

    <outbound>
            <set-variable name="access-token-value" value="@{
                var response = context.Response.Body.As<JObject>();
                return response["access_token"];
            }" />
            <base />
        </outbound>
    

    Note, these are just code snippets, and you can customize it based on the need. I hope this helps with your question and let me know if you face any issues or have any additional questions.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.