Azure API Management | API Mocking

Posted by Andrew Wilson on Sunday, September 18, 2022

Problem Space:

I have been recently looking into setting up some APIs within API Management. I do not currently have any backing services to hook the API’s to and I would like to decouple development of the front end systems from the backend. Thankfully Azure API Management has provided the ability to create mocks for your API’s. In this post I will be walking through API mocking and how to achieve this within Bicep Templates for deployment.

Azure API Management mocking

Mocking APIs within APIM has been made super simple and configurable. The mocks that you setup will be split into two parts:

  1. Mock sample data and return type.
  2. Mock enablement.

The split has been made so that you can have multiple mock samples configured and then enable the ones that you wish to run. We will look into each component separately.

Setting up mock sample data

APIM will allow you to setup multiple mock responses but only one per response status code as the mocks samples are identified by their response status codes.

Currently, if you setup multiple samples, only the first sample will only ever be returned.

Mock Samples can be setup for each API within the Operation frontend. The Mock responses and samples can be found under Responses.

Enabling API mocks

Mocks are enabled within the APIM policy blocks:

  • Policy sections: inbound, outbound, on-error
  • Policy scopes: all scopes
    • Global - All APIs
    • Product
    • API - All Operations
    • API - Individual Operation

Policy Block Sample

        <base />
        <mock-response status-code="200" content-type="application/json" />
        <base />
        <base />
        <base />

Bicep Mock Sample and Enablement

The type of mocking that I wish to be setting up is enabled on the API operation scope and applied to the inbound policy section as shown above. The Bicep template for this would appear as follows:

// Configure the API Operation with the mock response sample
resource mockOperation 'Microsoft.ApiManagement/service/apis/operations@2021-08-01' = {
  name: 'apiOperationName'
  parent: apimService
  properties: {
    method: 'GET'
    urlTemplate: '/mockOperation'
    responses: [
        statusCode: 200
        description: 'Mock Request'
        representations: [
            contentType: 'application/json'
            examples: {
              default: {
                value: loadJsonContent('jsonMockSample.json')

// Configure the API Operation Policy with application/json 200 response
resource apiOperationPolicyDeploy 'Microsoft.ApiManagement/service/apis/operations/policies@2021-08-01' = {
  name: 'policy'
  parent: apiOperation
  properties: {
    format: 'xml'
    value: loadTextContent('policy.xml')

Happy Mocking