question

fool1241-6686 avatar image
0 Votes"
fool1241-6686 asked MayankBargali-MSFT edited

How to customize the response body when the API cannot be executed in Azure APIM?

I'm wondering if APIM can respond with its own response body if it fails to execute the API as below when executing the API in Azure APIM.

  1. Execute API with HTTP method that is not imported into APIM and get Not Found error

  2. Subscription key authentication fails with an error

Is it possible to use APIM's return-response to make a unique error response for each case?

https://docs.microsoft.com/en-us/azure/api-management/api-management-sample-send-request

azure-api-management
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @fool1241-6686

I am looking into it and will share my analysis.

1 Vote 1 ·

1 Answer

MayankBargali-MSFT avatar image
1 Vote"
MayankBargali-MSFT answered MayankBargali-MSFT edited

Hi @fool1241-6686

Apology for the delay.
I have tested the scenario and you can leverage predefine errors for built in steps. You can define the policy in the global level or according to your need.
For the below policy, I am checking whether the subscription key is valid or not (SubscriptionKeyInvalid) and customize the message as per your need. Similarly, you can use "OperationNotFound" to match incoming request to an operation.

     <on-error>
         <choose>
             <when condition="@(context.LastError.Reason == "SubscriptionKeyInvalid")">
                 <return-response>
                     <set-status code="401" />
                     <set-header name="Content-Type" exists-action="override">
                         <value>application/json</value>
                     </set-header>
                     <set-body>{
                         "statusCode": 401,
                         "message": "The key enter is incorrect"
                 }</set-body>
                 </return-response>
             </when>
         </choose>
     </on-error>

Feel free to get back to me if you need any assistance.

Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you
That's exactly what I wanted to do.

0 Votes 0 ·

@fool1241-6686 Thanks for your response. Glad to know that it helped. Feel free to reach out to us in Microsoft Q&A if you need any assistance in the future.

0 Votes 0 ·