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

fool1241 86 Reputation points
2021-03-07T19:35:13.897+00:00

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://learn.microsoft.com/en-us/azure/api-management/api-management-sample-send-request

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,446 questions
{count} votes

Accepted answer
  1. MayankBargali-MSFT 70,936 Reputation points Moderator
    2021-03-16T10:11:40.63+00:00

    Hi @fool1241

    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.

    3 people found this answer helpful.

0 additional answers

Sort by: Most helpful

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.