Prototyping your Frontend: How to mock responses in API Management?

Sometimes the best option to create a REST API and provide something for to the partners to try it out (documentation or starting to developer their side), especially if the requirements are not completely defined, is not to start coding your backend API, which takes more time to develop and which sometimes will be subjected to constant changes, becoming in many cases an inglorious work and a complete waste of time (… sometimes) but instead to prototype your API in your frontend system. So in this post, I will address the question: How to mock responses in API Management?

API Management provides different, powerful and easy ways to mock your API’s to return static or dynamic sample responses even when there is no functional backends service capable of providing them. Mocking can be very useful in several scenarios like:

  • Create proof of concepts or demos
  • Test Driven Development approach: 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.
  • When a specific operation is not yet implemented.
  • And so on…

Despite being pretty simple to set up a mock, at the moment there are several ways to archive this in API Management, some of them more simple and static and others more complex and dynamic. So, let’s see all the options.

Options 1) Using the return-response policy in the “old” Publisher portal

Using the return-response policy, it would halt the execution of the API pipeline (… if it exists) and return a response code as specified. You can also send an optional set of headers and a body to the caller.

mock responses in API Management: return-response policy overview

(Picture from https://www.youtube.com/watch?v=SDyUw93hx1w)

Note: One of the beautiful things on using this policy, comparing with the mock-response policy that we will describe in option 3, is that the mock can be implemented in a very dynamic way if you combine this policy with expressions.

To accomplish that we need to:

  • Access to the “old” Publisher portal, by accessing you API Management resource in Azure Portal and then click “Publisher portal” button

mock responses in API Management: Azure Portal Publisher Portal option

  • On the Publisher portal, select the option “Policies” from the left menu

mock responses in API Management: Publisher Portal Policies

    • Note: Policies can be configured globally or at the scope of a Product, API or Operation.
  • The next step is to define the scope of the policy, in our sample, we will be selecting a particular operation. To do that you need to select you API from the “API” drop box and then the specific operation from the “Operation” drop box.
  • And then on the “Policy definition” click “ADD POLICY”

mock responses in API Management: Publisher Portal Policy scope

  • Add a return-response policy in the inbound section by:
    • Focus the cursor in the inbound section and then from the Policy statements toolbox click in the option

mock responses in API Management: Publisher Portal add return response policy

    • TIP: When mocking, the policy should always be used in the inbound section to prevent an unnecessary call to the backend.
  • This will add the default template format of the policy to the policy definition, that you will need to set up according to your needs:

mock responses in API Management: return-response policy template

  • To simplify our case, we just need to return a 200-status code with a static JSON response and for that, we need to apply the following policy:
<return-response response-variable-name="existing response variable">
     <set-status code="200" reason="OK" />
     <set-header name="Content-Type" exists-action="override">
         <value>application/json</value>
     </set-header>
     <set-body>{
                 "success": true,
                 "data": {
                    "cards": [
                       {
                          "id": 28,
                          "Name": "Sandro Pereira"
                       },
                       {
                          "id": 56,
                          "Name": "Carolina Pereira"
                       },
                       {
                          "id": 89,
                          "Name": "José Pereira"
                       }
                    ]
                 }
     }</set-body>
</return-response>
  • Save the policy to take effect next time a call is made to the operation.

Of course, this policy can be used in many different ways, for example, if you only want to return a 200 OK without body response, you can use an abbreviated version of the policy that will be represented like this:

<return-response/>

But as I told you earlier that this also can be very dynamic as you can see in the “Mocking response in Azure API Management” tutorial provided by Microsoft where they are mocking an “Add two integers” operation in which the policy will look like this:

<return-response response-variable-name="existing response variable">
     <set-status code="200" reason="OK" />
     <set-header name="Content-Type" exists-action="override">
         <value>application/json</value>
     </set-header>
     <set-body>{
          "success": true,
          "data": "@((Convert.ToInt32(context.Request.Url.Query.GetValueOrDefault("a", "0")) + Convert.ToInt32(context.Request.Url.Query.GetValueOrDefault("b", "0"))).ToString())"
     }</set-body>
</return-response>

Here, I am taking the actual query parameters provided in the request and implementing the all the operation logic of my backend API dynamically inside my policy… pretty cool!

Options 2) Using the return-response policy in the Azure Portal.

This second option is exactly the same as the previous one, but instead of doing in the “old” Publisher portal, we will accomplish the same goal using the “new” API Management capabilities/functionalities embedded in the Azure portal.

To accomplish that you need to:

  • Access your API Management resource in Azure Portal and then click “APIs” option under “API Management” section from the left menu

mock responses in API Management: Azure Portal APIs

  • Select the API from the API list, then from the operation list select the correct operation and then click the edit button on the “Inbound processing” policies

mock responses in API Management: Azure Portal create or edit operation policy

  • Click in “</> Code View” to view or edit your policies as explained earlier in the first option

mock responses in API Management: Azure Portal create or edit operation policy code view

  • You will find the same experience as the “old” Publisher portal while editing the rules

mock responses in API Management: Azure Portal create or edit operation policy code view result

Both option 1 and 2 are the same, the only difference between them is that in the first option we are using the Publisher portal (this portal still exists because not all functionalities have yet been migrated for the Azure Portal) and in the second we are using the Azure Portal UI.

Options 3) Using the Mock-Response policy

The first two options, that in fact use the same rule are very useful in several distinct scenarios, especially if you want to implement some intelligence (dynamic responses) in you mock.

But what if you want to combine your mocking cases against our API specifications that we used while creating our operations? Fortunately for us, Microsoft released a few months ago a new policy to perform this task in an easier way and you can now use the Mock-Response policy to achieve this effect and it is fully supported through the UI in the Azure Portal.

Note: this policy can also be used in the “old” Publisher portal but I will not address that.

TIP: Once again, you can apply this policy to every section, but its typical usage scenario is on the inbound path to provide a response instead of the backend service and also to prevent unnecessary calls to the backend.

To configure this policy from the Azure Portal you need to:

  • Access your API Management instance, under “API Management” section click “APIs”, select the API from the API list, then from the operation list select the correct operation and then click the edit button on the “Inbound processing” policies to open the Inbound processing editor

mock responses in API Management: Azure Portal Mocking

  • You will now notice that a tab titled “Mocking” is available, in which you can configure the desired static response back to your caller by:
    • Selecting the “Static responses” option
    • And what response status should be returned by configuring the “API Management will return the following response” drop box

mock responses in API Management: Azure Portal enable Mocking

Are you wondering where you can define the response?

If you look at the description of this policy in the documentation it says: “… as the name implies, is used to mock APIs and operations. It aborts normal pipeline execution and returns a mocked response to the caller. The policy always tries to return responses of highest fidelity. It prefers response content examples, whenever available. It generates sample responses from schemas, when schemas are provided and examples are not. If neither examples or schemas are found, responses with no content are returned.”

So, in other words, when designing the operation specification:

  • if you provide expected response types and samples:

mock responses in API Management: Azure Portal Mocking Frontend Response types

    • The mock-response policy will take this sample response that you defined as the response to be delivered to the caller

Note: If there are already response status codes, with or without content types, examples and schemas defined, configured on that particular operation (as shown in the figure above), these HTTP status codes will be listed at the top of the “API Management will return the following response” drop box on the mocking section.

mock responses in API Management: Azure Portal Mocking user defined responses

  • if you instead provide a response schema instead of samples, the mock-response policy will generate a sample response from the schema provided
  • If you don’t define samples or schemas, the policy will return a 200 OK response with no content return.

Normally, the policy template (or signature) is:

<mock-response status-code="code" content-type="media type"/>

However, as similar with the return-response policy, you can use an abbreviated version of the policy that looks like this:

<mock-response/>

And again, it will return a 200 OK status code and the response body will be based on an example or schema, if provided for this status code. The first content type found will be used and if no example or schema is found, a response with no content will be returned.

Conclusion

Both mock-response and return-response policies can be used on API Management for prototyping your API frontend. Although at first glance they may have similar behaviors, both policies have advantages and disadvantages and can be used in different scenarios/context.

But I will probably say for mocking propose I will use or advice to use the mock-response policy just because it is simpler and will take advantage from the API specification to generate the mock response which also “force” the developers (or admins in charge of your frontend) to properly document the APIs.

Author: Sandro Pereira

Sandro Pereira lives in Portugal and works as a consultant at DevScope. In the past years, he has been working on implementing Integration scenarios both on-premises and cloud for various clients, each with different scenarios from a technical point of view, size, and criticality, using Microsoft Azure, Microsoft BizTalk Server and different technologies like AS2, EDI, RosettaNet, SAP, TIBCO etc. He is a regular blogger, international speaker, and technical reviewer of several BizTalk books all focused on Integration. He is also the author of the book “BizTalk Mapping Patterns & Best Practices”. He has been awarded MVP since 2011 for his contributions to the integration community.

One Platform Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

One Platform - Operations, Monitoring and Analytics Software
BizTalk360

microsoft biztalk

Learn more

Over 500 customers across 30+ countries depend on BizTalk360

One Platform - Operations, Monitoring and Analytics Software
ServiceBus360

Azure service bus

Learn more

Start managing your Azure Service Bus namespaces in minutes

Back to Top