Azure API Management

Inside scoop from the API Management team

How to mock responses in API Management

Mocking provides a way for APIs to return sample responses even when their backend isn’t capable of providing one. This enables app developers to proceed with implementation and testing and can be useful in a number of scenarios:

  • When the API façade is designed first, and the backend implementation comes later or is worked upon in parallel
  • When the backend is temporarily not operational or not able to scale

Setting up mocking is pretty simple with the return-response policy. It would halt the execution of the API pipeline,  return a response code as specified and send an optional set of headers and a body to the caller. Here is the format of the policy:

<return-response response-variable-name="existing response variable">
    <set-status code="code" reason="reason" />
    <set-header name="header name" exists-action="override | skip | append | delete">
        <value>value</value> <!-- for multiple headers with the same name add additional value elements -->
    </set-header>
    <set-body>new body value as text</set-body>
</return-response>

When mocking, the policy should be used in the inbound section so as to prevent an unnecessary call to the backend. To return 200 OK you can use an abbreviated version of the policy that looks like this:

<return-response/>

Here’s a short video showing mocking in action: