How to create a mock API for POST requests in Postman?
Why is mock API essential?
The word "mock" means dummy or fake. When working in an Agile team where the team needs to collaborate and give feedback quickly, mock APIs play an essential role. Whether you are integrating with external APIs or building internal APIs, UI(web or mobile) developers need to work parallelly with backend developers. The UI developers do not need to wait until the backend developers implement or integrate external APIs and provide API responses. To solve this challenge, MOCK API plays a crucial role.
Several tools are available to construct mock APIs—for example, Stoplight, Mockbin, Postman, and many more.
How To Setup your mock server in Postman?
You can check Postman Doc or the quick steps below to create a mock server.
For GET requests, you can add multiple examples and a query parameter so that the response will be different for different query parameter values. It would help if you had a bunch of test data for your mock APIs.
How to create a POST request mock API in Postman?
Let's create two samples for POST requests in the same collection as above.
Add the request body you want to send and the response you want to get in Samples 1 and 2.
Similarly, add another example called Sample 2.
Recommended by LinkedIn
Do you expect a specific request and response?
You will always get the last sample response if your request body does not match any of the samples have.
How to get a specific mock POST request and response?
When you have multiple examples for a POST request, you must send x-mock-match-request-body to true. It enables us to send you the exact response for the same body.
After that, you will get matched response for a specific request body.
Check other optional headers available in Postman, like x-mock-match-request-body.
Summary
Mock API accelerates development by providing desired API responses without writing code for API and plays a significant role in Agile development and the API-First approach.
For the mock API GET requests, you don't need to send the x-mock-match-request-body header, as the query parameter will solve the problem.
For the mock API POST request, you must send appropriate Postman optional headers to get matched responses for a request.