azureazure-api-managementibm-api-management

Azure API Management returning 200 status without response body


I already have checked other solutions available on the forum and this one too REST API service when called from azure APIM returning empty response body with Status code 200

I'm trying to call an authentication service which returns status codes (200,401 and 404) If it returns 200 then I want my request to be forwarded to the backend otherwise return only status code back to the client.

This is what I added in my policy

<policies>
<inbound>
    <base />
    <check-header name="username" failed-check-httpcode="401" failed-check-error-message="unauthorised" ignore-case="true" />
    <cors>
        <allowed-origins>
            <origin>*</origin>
        </allowed-origins>
        <allowed-methods>
            <method>GET</method>
            <method>POST</method>
        </allowed-methods>
    </cors>
    <send-request mode="new" response-variable-name="receivedResp" timeout="20" ignore-error="true">
        <set-url>https://authenticate1.azurewebsites.net/auth</set-url>
        <set-method>GET</set-method>
        <set-header name="username" exists-action="override">
            <value>@(context.Request.Headers.GetValueOrDefault("username",""))</value>
        </set-header>
        <set-body />
    </send-request>
    <return-response response-variable-name="receivedResp" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

Now problem is return is returning received response in all cases, when i added a conditional policy i still was not able to return response received from backend.

Can anyone tell how to check status code and return response received from the server in case of 200 only?


Solution

  • The <send-request/> policy returns the response variable of type context.Response. So you can use the methods and variables available for that object. See the below reference to find it. https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions#ref-context-response

    In your case, you can add <choose/> policy and test the receivedResp.StatusCode != 200. Then you can return based on the response.

    Hope it helps