Using Postman to Build Mock Servers for Collaboration
Sign up for a free student license: https://www.postman.com/company/student-program/
Introduction Creating a Workspace Environments Using Variables Creating Collections Saving Request Examples Making a Mock Server Making Documentation
Postman started as a web and desktop application for testing APIs by making GET and POST requests. It does so much more now, with a growing list of features that allow teams to share environment settings, collections of endpoint requests, testing tools, monitoring tools, and centralizing your documentation.
The company also builds and maintains a growing list of APIs, and companies have been adopting Postman as standard tool to promote their APIs to developers around the world.
As a tool for building and testing APIs, Postman allows you to save content from one request to manipulate and send to other requests. It also allows you to write test code in JavaScript using the Chai library, and access a number of built-in libraries such as Faker, Lodash, Moment, and some NoseJS modules like assert
and events
. You can see our list of libraries on this page.
Today we are not going to go throughe very feature of Postman, but we will focusing on two areas. We are going to be learning about how Postman can help front-end and back-end students collaborate in the application to design their API contracts using Collections, and how to build and run Mock Servers.
Postman can also generate documentation for your API too!!
Before we get started, it is worth noting two important things about other things Postman can offer:
If you want more inspiration for your project, or looking for a fun API to integrate into your project, you can use our "Explore" link to "view all" categories by clicking here or looking at our Spotlight page for APIs we are helping to promote from our business partners.
If your team wishes to use GraphQL instead of a more RESTful API approach, you can choose to do so.
The web application is always up to date with features. The desktop application will need occasional downloads to stay updated, which is less convenient.
The desktop application will allow you to work offline, and also allow access to "localhost" URLs, or URLs on private networks (such as a home or school network), where the web application can only access API endpoints which are publicly available. (you CAN work around this with tools like ngrok or other "tunneling" software, but that is outside of the scope of this workshop)
One person will need to make a PUBLIC team workspace and add others in their team. You can change the name of the workspace later so if the name of your project changes, it will not cause a problem.
1. Give it a Name
1. Give it a Summary
1. Set the visibility to Public
The person who creates the workspace will need to add other team members, and make them owners of the workspace as well so they have permission to add/edit data.
1. Click on the "Workspace Settings" icon
1. Click on the "Invite" button
1. Click on the "Copy Invite Link" link at the bottom
1. Send the link to your team members
1. Be sure to set everyone to "admin" permissions
(it might also be good to add your instructors/mentors as well)
Next we will set up an Environment for our settings.
The nice thing about setting up Postman Environments is that you can make a list of settings for your local development, and another copy of those settings where the values point to a production system instead. With just a few clicks, you can test your work in an alternate enironment to make sure everything is working correctly.
To get started, click on the "Environments" icon on the left side of the application, click "Create Environment", and give it a name like "Development". Add some variables here like "baseUrl" and set the "type" to "default", and set the "initial value" to "http://localhost:3000" which will also copy that to the "current value" field.
If you "persist" the variable, it will copy your "current" value to overwrite your "initial" value, and then sync that to servers at Postman, and your team will have access to your settings. When one teammate updates a setting, it will sync for all other team members. Your "current value" is stored locally, so you can change your own "current" value, and that will NOT sync to everyone else. If you log out of Postman, your "current" values will be cleared as a security feature.
Have one team member create an environment, and other teammates should be able to see this when they refresh their interface.
Have each team member create an environment variable with a unique name, and set the value. When the team refreshes their environment, they should see these changes appear on their local systems.
Even if you set a variable type to "secret", any initial value you set can be exposed by anyone else viewing your Workspace Environment. We recommend storing API keys as a "secret" type, and ONLY setting the "current value" NOT the "initial value" and do NOT perist that to the Postman servers.
Next, click on the Environments icon again, and next to your Development environment, click the "..." three dots icon, select "duplicate" and call this new copy "Production".
All of your data is copied to the new Production environment settings, but you can change the "baseUrl" variable to something else later on.
If you later decide to change your variable from "baseUrl" to "backendUrl", you will need to change the variable name in your environment and everywhere else you use it. Once you save the environments, they will sync to the Postman servers, and your teammates can refresh their copy to see the change.
Generally speaking, you want to set variables in your environment that have to do with where and how you access your API, such as hostnames or IP addresses, and API keys. You should not store EVERYTHING here. Use your best judgement once you learn more about variables and collections below!
Within Postman, you can use these variables by using two curly braces around the name of the variable, such as {{baseUrl}}
. We will show this more when we talk about Collections next.
The exception is when writing JavaScript code in the Pre-request Scripts and Test scripts, you will need to use a Postman library call based on the type of variable, and there are get
and set
methods.
To read an Environment variable, you can use code like this:
let baseUrl = pm.environment.get("baseUrl")
The pm
is the Postman library, and the environment
object has a .get()
method which takes a string argument of the name of the variable that it is trying to access. It will return an undefined
type if the variable is not found.
To set an environment variable, we can use this code:
let myName = "Ian Douglas"
pm.environment.set("authorName", myName)
This will create, or overwrite, a variable called authorName
with the string "Ian Douglas". If the variable already existed, the "initial" value will remain, but the "current" value will reflect this change. If the variable is being created, it will set both the "initial" and "current" values.
Complex data types like arrays and objects will need to be stored as strings, and parsed back into arrays/objects:
let oldArray = [1,2,3,4,5]
let oldObject = { "greeting": "hello world!" }
pm.environment.set("myList", JSON.stringify(oldArray))
pm.environment.set("myObject", JSON.stringify(oldObject))
// and parsed back from a string to its original form
let newArray = JSON.parse(pm.environment.get("myList"))
let newObject = JSON.parse(pm.environment.get("myObject"))
Now that you have a workspace where you can collaborate, and understand how variables can get made and recalled in code, your team members have the ability to work together in real-time on collections and requests. As with other areas of the application, Postman will synchronize changes to collections as it is saved.
Collections can contain nested folders as well to help you group your API calls. Talk to your team about how you want to organize your collections.
Click on the "Create Collection" button in the left panel. You can change the name of the collection near the top of the interface.
You should see a link to "add a new request" or you can click on the "..." three dots next to the collection name in the left panel and select "add request" from the list.
Call this request "get echo", and make sure that the HTTP method is set to "GET". The request URL will be `https://postman-echo.com/get".
Click on the "Params" tab below the request URL, and add parameters, and notice how the GET request address automatically updates. You can change the request URL directly and see your parameters change too.
Click on the Send button and the response body should show your parameters as an "args" block in the JSON response.
This is where you can write JavaScript to retrieve data or modify anything before the request is made. This might be where you use a "local" variable instead of an "environment" variable.
pm.variables.set("parameterValue", "hello world")
Change a parameter in your request to set its value to {{parameterValue}}
-- you might notice if you hover over this that Postman says the value is "unresolved". The pre-request script has not executed yet, and so no variable has been create, but it WILL be built dynamically when you Send the request. Click Send and see what the response body contains.
This is where Postman really shines! When the request has finished receiving its response, the code in Tests will execute next, and we can set up test expectations/assertions.
Check out the "snippets" on the right side of the code editor to see how you can get variables, check a status code, even check how quickly the response returned!
Like most testing libraries, if you set up multiple assertions, the code execution will halt as soon as any assertion fails.
You have access to console.log()
in the Pre-request Script and Tests areas. The Console can be opened with a button in the bottom left corner of the interface.
We are getting close to creating our Mock Server!
On the right side of the body response output, you will see a drop down that says "Save Response". Save this response as an "example" by choosing "Save as example". The "example" opens a new area of the interface where you can give this example a name. Call it "Hello World".
In the Params area, remove any parameters we were previously passing. If you hover over the right side of the interface, a small "X" should appear to delete the parameters.
Change the entire response body to this:
{
"greeting": "hello world"
}
You can also alter the status code on the right side of the interface if you like, but leave it as "200 OK" for now.
Now our URL should just be "https://postman-echo.com/get" with our simpler JSON body.
Remember the "/get" URI path, you will need that in a moment!
Click the "Save" button to save our changes.
Work with your team to create as many of these example endpoints, save their response, and edit them based on whatever "API Contract" you decide on as a team. Set appropriate status codes as well for error conditions.
Okay, planning is all fun and everything, but how will this help our team?
Find your Collection name in the left panel (you might need to click on the Collections icon if you were in a different area).
Click on the "..." three dots next to your collection name and choose "Mock Collection" from the list.
Give your mock server a unique name. You probably cannot change the Collection selection unless you and your team have sync'd other collections. The "Tag" will be CURRENT. For "Environment", choose your team's "Development" environment.
Leave the checkbox enabled to "save the mock server URL as an environment variable". We are going to use this soon. Click on the button that says "Create Mock Server".
You should see a success page with a button to "Copy Mock URL" to your clipboard.
Open a new browser tab, paste in that URL, and add "/get" to the end, since that was the URI path from our "get echo" request.
In your browser, you should see the "greeting" and "hello world" that we made in the saved response.
You've just created a mock server. You can go back to your collection, make as many requests as you like with different URI paths and saved responses and status codes, and your mock server URL will serve all of them in your browser.
Your mock server URL was saved in your environment called "url". You can use this in any other requests you make by changing the URL from https://postman-echo.com
to {{url}}
and the request will send to your mock server! This is another example of how variables can be used in Postman. When you hover over {{url}}
you should see that it is "scoped" from the Environment, and show you the value.
How do you test PUT, POST, DELETE, etc.?
Those will need additional scripting in your application.
Go back to Collections, click on your collection name, find your "get echo" request, and click the "..." three dots next to it, and select "duplicate" from the list. Change the name from "get echo Copy" to "post echo"
Change the method from GET to POST and change the URL to https://postman-echo.com/post
.
Click on Body under the request URL, select "raw" from the list and at the end of that row you should see "Text" as a dropdown. Click the dropdown and select "JSON" from the list. Set this as your body:
{
"example": "sending this to Postman"
}
Save your changes and click Send. Notice in the response that the data we sent to Postman shows up in a "data" attribute and a "json" attribute. Save this reponse as an example. (you can delete the other example that was duplicated)
Now on the right edge of the interface, you should see an icon that looks like a closing HTML tag, like </>
, click on that.
Here, Postman will create code snippets in several programming languages and associated libraries such as the JavaScript fetch library and Python requests library.
You will need to input your mock server URL instead of https://postman-echo.com
.
Generating API documentation is an easy-to-follow 500-step process.
Just kidding!
- Click on your collection name and click on the "..." three dots next to it.
- Select "View Documentation".
- Click on the "Publish" icon at the top right corner of the interface.
- Choose your "Production" environment from the list
- Click "Save and publish" at the bottom of the page
- Open the link to your published documentation in a new browser tab.
The documentation will update within a minute or so whenever you save changes to your work.
Note that your documentation page also has a "run in postman" button at the top right where others can import this collection immediately into their own workspace.
Most of the content covered in this workshop can be practiced in smaller portions using the "30 Days of Postman" workspace. Make a new private workspace and "fork" the following collections for continued practice:
https://www.postman.com/postman/workspace/30-days-of-postman-for-developers/overview
- Day 2: Collections and Environments
- Day 3: Setting Request Details
- Day 5: Variables
- Day 6: Tests
- Day 8: Runng all requests in a Collection
- Day 9: More Scripting
- Day 10: Mock Services
- Day 19: GraphQL
- Day 24: Using libraries like moment.js
- Day 25: Dynamic request bodies