Mocking REST API Responses in Amazon API Gateway

It’s often the case that the team developing the services deployed behind an API Gateway setup is not the same as the one that’s consuming the APIs. It’s inevitable in such cases that the consuming team will start demanding functioning APIs from the services team as soon as possible, or they risk getting stalled. Of course, none of the services are developed yet. As such, the services team must mock all API responses so that the consumers can proceed accordingly.

In this article, we’ll see how to mock an API in Amazon API Gateway. We’ll implement the simplest, most straightforward use case wherein the GET method of the root resource of an API is supposed to return a JSON response with a single key-value pair. Our mock will always return an HTTP 200 OK status code. Once you get a hang of the basics, you can then build upon this knowledge to create complex mocks for APIs including conditional status codes based on request headers. The official AWS docs describe some of these.

Let’s start by creating an API from the API Gateway dashboard:

Add a GET method for the / resource:

Select Mock as Integration type:

Note that there’s already a Mapping Template defined for the application/json Content-Type in GET’s Integration Request:

So all we have to do to get our API working is to define a Mapping Template for the application/json Content-Type in GET’s Integration Response:

Testing the API now should give us the expected mock response:

Deploying this API & invoking it externally would also give us this response:

$ curl https://*.execute-api.us-east-2.amazonaws.com/mock

{
    "message": "Hello!"
}

That’s it! We have successfully mocked an API!

 

Harish KM is a Cloud Evangelist and a Full Stack Engineer at QloudX. Harish is very passionate about cloud native solutions and using the best tools for projects. This means that he is an expert in a multitude of application languages and is up to date with all the new offerings and services from cloud providers, especially AWS.

Leave a Reply

Your email address will not be published. Required fields are marked *