Illustration by Postman
If you ever worked in any front-end or mobile application, you may know the struggle of being dependent on one to several APIs to do your tasks. Form time to time you may notice that:
- The feature is not ready: The API endpoint might not be ready to support your requests because the logic behind that is not developed yet.
- The server is down: The back-end might be under maintenance or unavailable at the moment.
- Incomplete data set: The endpoint is up and running but data you wanted to work with is not there. Like working with user credentials that don’t have enough authorization, for example.
A mock API —a.k.a. mock server— is a simple solution to these problems. As the name suggests it can imitate real API responses based on realistic cases.
But not only developers can benefit from a mock API, it also can help test engineers. A mock server can be hooked up to a pipeline so test scenarios of a CI can run entirely isolated from an actual back-end.
How to create a mock server with Postman?
You can simply create mock data by taking a static JSON
object and use it as an API end-point response. And to make it more subtle and feasible you can use JSON Server. But Postman made it even simpler.
For the purpose of this article we are going to use the Github public API https://api.github.com/ as our actual API.
First, you need to launch your Postman client and go to your desired workspace. You also need to create a collection that contains the mock requests.
Creating request using GUI
In the sidebar click on Collections and create a new one. Right click on it and select Add Request.
Specify a name for the API call, this is not the endpoint, rather a description to understand at glance what the API call is for (e.g. Get user info).
Select the method and also provide the actual URL of the request you would like to mock. We are going to use https://api.github.com/users/defunkt
for the URL.
You may also want to fill in Params, Authorization, Headers, and Body as needed.
Once you are done, click on Save.
Creating request using cURL (recommended)
Using the GUI to create a request can be too time consuming, especially if the request Headers and Body are needed for the call. Using cURL, on the other hand, is way easier.
Go to your favorite browser and then navigate to the Network tab in the Inspect mode. Right click on any request you wish to clone and then select Copy > Copy as cURL (bash) in Chrome or Copy > Copy as cURL (POSIX) in Firefox.
Go back to the Postman client and click on Import on top left and select the Raw text tab. Paste the data in the provided box and click Continue, and finally Import.
Click on Save on top right and choose the collection you’ve previously created for mocking purposes to save the request into.
Creating response example
This is the easy part, once you have your request ready from the previous steps (GUI or cURL) you should be able to try it. Click on Send and if that’s the response you expected to see click Save Response > Save as example.
Note: the example you have just created will be used as mock data to any mock server its collection is bound to. So any modification made to the response would also affect the result of the mock server response. This includes Headers, Body and Status Code of the response.
Creating the mock server
To create the mock server, click on New on the top left and select Mock Server.
Next click on Select an existing collection and select the collection from the panel below. Give your mock server a name and finally click on Create Mock Server.
From now on the collection and the mock server are bound to each other. Meaning any request added to the collection with at least one saved response example will be used by the mock server.
Your mock server is now ready and you should be able to see a random URL generated by Postman. On this page, you will see the history of all incoming requests when you start using the mock server. This is a great place to troubleshoot your server and its relative mock collection.
Note: The provided mock URL is the base URL of your mock server. So, for example, if you had mocked the following API end-point https://api.github.com/users/defunkt
and saved its example, your mock endpoint for the same request would be https://some-random-id.mock.pstmn.io/users/defunkt
.
How to version control your mock server?
Like any other Git project that you have worked with, the Postman mock server can be version controlled. But you have to keep in mind that you can’t version control the mock server itself, but rather the collection it is linked to.
Create fork
Right click on the collection you wish to be forked and select Create a fork. Give the newly created collection a Fork label and specify the Workspace you would like to save it to. And click Fork Collection.
But we are not done yet. As mentioned before you can not fork a mock server in Postman, but only its collection and since you have created (forked) a new collection you have to create a new mock server to correspond with it. So go ahead and create a new mock server following the steps from before but make sure to select the forked collection this time.
By now you should be able to create a pull request based on your changes compared to the master collection, even approve or decline a pull request just like regular git common practices. If you would like to learn more about Postman mock server version control you can read it here https://learning.postman.com/docs/collaborating-in-postman/version-control.
Tips and troubleshooting
Mocking GraphQL calls
Postman, by default, does not check the body of the saved example which means any incoming request in your mock server would be served by the first saved example that has the same URL and method. Obviously this is not what we want for GQL calls.
To overcome this issue, don’t create your request manually (GUI) but rather use the import method (cURL). Also make sure to pass the x-mock-match-request-body
header with a value of true
when sending a request to the mock server URL. SO for example, if you are using apolo library you should add x-mock-match-request-body: true
to the header of all outgoing requests to the mock server.
CORS issue
In the official document of Postman, it’s mentioned that:
CORS is enabled for Postman mock servers. As a result, you can stub your web apps with mocked data using the mock endpoints. Development or production web apps can then make requests to your Postman mock endpoint and receive example responses.
But you may still see that your browser is still blocking your incoming responses from your mock server. If that happens, you can either
- Add these two items to the headers of your saved examples:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://your-local-url:port
- Or install any CORS handling extension in your browser. In the case of cypress, refer to this guide: https://docs.cypress.io/guides/guides/web-security#Set-chromeWebSecurity-to-false
Dynamic values
You may want to have your mock end-point to respond with random data, instead of static values. In order to do that you can use dynamic variables in your example’s response body.
Dynamic variables are resolved as part of the mock server response and replaced with random data. Dynamic variables are useful for generating random data when mocking an API, and you can use them for exploratory testing and writing rich, data-driven tests.
For instance, if you set these variables in your example response body:
{
"name": "{{$randomFullName}}",
"userName": "{{$randomUserName}}"
}
You would get:
{
"name": "Cielo McClure",
"userName": "Aurelie.Lockman",
}
Conclusion
Having a mock server, especially in service oriented systems, is as necessary as having a good IDE for development. Not having it won’t stop you from doing the actual work, but it certainly can speed up the process. Plus, launching a mock server in Postman can be as simple as clicking some buttons. So give it a try!
About me
I’m Ashkan, a full-stack engineer in Techspire Netherlands. I have 10 years of experience and am specialized in NodeJS. I crave new technologies and I am eager to learn them. I love what I do and love sharing my knowledge even more.
I also play video games in my spare time and if I can’t, I watch other people’s streams on Twitch.