Skip to lesson

Postman collections and environments

Your ShopLite requests sit in twenty loose tabs. Moving from your laptop to the live server means editing every URL, and a new teammate cannot reuse a single request.

Collections and folders to organise an API's requests

A collection is a saved, named group of requests for one API. Folders inside it group the requests, usually one folder per resource: Auth, Categories, Products.

Name a collection after the API, add one folder per resource and drag the requests into order. The runner later sends them from top to bottom.

Example 1 · A collection with two folders, run top to bottom

Text
ShopLite API                      Authorization: Basic Auth  {{adminEmail}} / {{adminPassword}}|-- Categories|   `-- GET     List categories             {{baseUrl}}/categories`-- Products    |-- GET     List accessories by price   {{baseUrl}}/products?categoryId=4&sort=price,asc    |-- POST    Create product              {{baseUrl}}/products    |-- GET     Get product                 {{baseUrl}}/products/{{productId}}    `-- DELETE  Delete product              {{baseUrl}}/products/{{productId}}
Sample output (a Newman run; Newman is the command-line runner from the next lesson)
$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var adminPassword=admin123
newman

ShopLite API

□ Categories
└ List categories
  GET http://localhost:8080/api/v1/categories [200 OK, 455B, 581ms]

□ Products
└ List accessories by price
  GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 28ms]

└ Create product
  POST http://localhost:8080/api/v1/products [201 Created, 296B, 49ms]

└ Get product
  GET http://localhost:8080/api/v1/products/16 [200 OK, 260B, 17ms]

└ Delete product
  DELETE http://localhost:8080/api/v1/products/16 [204 No Content, 111B, 37ms]

┌─────────────────────────┬────────────────────┬────────────────────┐
│                         │           executed │             failed │
├─────────────────────────┼────────────────────┼────────────────────┤
│              iterations │                  1 │                  0 │
├─────────────────────────┼────────────────────┼────────────────────┤
│                requests │                  5 │                  0 │
├─────────────────────────┼────────────────────┼────────────────────┤
│            test-scripts │                  1 │                  0 │
├─────────────────────────┼────────────────────┼────────────────────┤
│      prerequest-scripts │                  0 │                  0 │
├─────────────────────────┼────────────────────┼────────────────────┤
│              assertions │                  0 │                  0 │
├─────────────────────────┴────────────────────┴────────────────────┤
│ total run duration: 1603ms                                        │
├───────────────────────────────────────────────────────────────────┤
│ total data received: 914B (approx)                                │
├───────────────────────────────────────────────────────────────────┤
│ average response time: 142ms [min: 17ms, max: 581ms, s.d.: 219ms] │
└───────────────────────────────────────────────────────────────────┘

What this code does

  • The tree is the Collections sidebar: one collection, a folder per resource, and the method and URL of each request. The collection's Basic Auth is inherited by every request.
  • The run sends the five requests in sidebar order and prints each status. Create product returned id 16, and the next two requests used it.

Create one from the Collections sidebar with + (or New → Collection), then use the collection's ... menu → Add folder and Add request. Without a collection you have twenty unnamed tabs; with one, a new teammate opens it and sees every endpoint, already working.

A collection also holds settings that every request inside can share: an Authorization tab (requests set to Inherit auth from parent use it), Variables and scripts. Set the login once on the collection instead of on fifteen requests.

Find the bug

Find the request that breaks

Click the line that causes the problem.

The collection logs in with a token. One request gets a 401. Which one?

Round 1 of 2

Variables: {{baseUrl}}, collection versus environment scope

A variable is a named value written as {{name}} inside a URL, header or body. Postman swaps in the value just before the request is sent.

Write the server address once as {{baseUrl}} and every URL follows it. The example shows which value wins when two scopes set the same name.

Example 2 · Which baseUrl wins?

Text
Request URL:              {{baseUrl}}/categoriesCollection variable       baseUrl = https://api.shoplite.example.com/api/v1Environment ShopLite Local baseUrl = http://localhost:8080/api/v1Run 1: no environment selectedRun 2: ShopLite Local selectedRun 3: a copy of the collection with no baseUrl anywhere
Sample output
1) No environment selected:
$ newman run shoplite-api.postman_collection.json --folder Categories --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API

□ Categories
└ List categories
  GET https://api.shoplite.example.com/api/v1/categories [errored]
     getaddrinfo ENOTFOUND api.shoplite.example.com

  #  failure  detail                                         
                                                             
 1.  Error                                                   
              getaddrinfo ENOTFOUND api.shoplite.example.com 
              at request                                     
              inside ""                                      

2) Environment ShopLite Local selected:
$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --folder Categories --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API

□ Categories
└ List categories
  GET http://localhost:8080/api/v1/categories [200 OK, 455B, 360ms]

3) baseUrl defined nowhere:
$ newman run broken.postman_collection.json --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API

→ Get product 6
  GET {{baseUrl}}/products/6 [errored]
     getaddrinfo ENOTFOUND {{baseurl}}

  #  failure  detail                            
                                                
 1.  Error                                      
              getaddrinfo ENOTFOUND {{baseurl}} 
              at request                        
              inside ""

What this code does

  • With no environment, the collection variable is used and the request goes to the production address, which does not exist in this practice setup. Selecting ShopLite Local overrides it, because the environment scope is narrower.
  • With baseUrl defined nowhere, {{baseUrl}} is sent as plain text and fails with ENOTFOUND {{baseurl}}: the clearest sign of a missing or misspelt variable.

{{baseUrl}}/products/6 becomes http://localhost:8080/api/v1/products/6. Without variables, moving to another server means editing every URL by hand and missing one. The same name can be set in several scopes, and the narrower one wins: local (set by a script for one run) beats data (from a runner file), which beats environment, which beats collection, which beats global. A collection variable is a sensible default that travels with the collection; an environment variable overrides it for one target.

An undefined variable is not an error in Postman: {{baseUrl}} stays as plain text, and the request fails with getaddrinfo ENOTFOUND {{baseurl}}. Hover over a variable in the URL bar: an unresolved one shows in red with "Unresolved Variable". Names are case-sensitive, so {{baseURL}} is a different, empty variable.

Predict the output

Which value is sent?

Read the setup and pick the URL Postman sends.

Round 1 of 2

Collection variable baseUrl = http://localhost:8080/api/v1
Environment selected: ShopLite Production
baseUrl = https://api.shoplite.example/v1
Request URL: {{baseUrl}}/products

Local and production environments, and secret values kept out of exports

An environment is a named set of variables for one target, such as ShopLite Local or ShopLite Production. Pick one in the dropdown at the top right and every request switches target at once.

Make one environment per target and keep secrets in the current value only. The example shows an exported environment with an empty secret.

Example 3 · An exported environment, and what an empty secret does

JSON
{	"id": "a3c9e2d4-1f6b-4a8e-b0d2-7c5e9f1a2b30",	"name": "ShopLite Local",	"values": [		{			"key": "baseUrl",			"value": "http://localhost:8080/api/v1",			"type": "default",			"enabled": true		},		{			"key": "adminEmail",			"value": "admin@shoplite.test",			"type": "default",			"enabled": true		},		{			"key": "adminPassword",			"value": "",			"type": "secret",			"enabled": true		}	],	"_postman_variable_scope": "environment"}
Sample output (adminPassword has no current value yet)
$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --folder Products --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API

□ Products
└ List accessories by price
  GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 128ms]

└ Create product
  POST http://localhost:8080/api/v1/products [401 Unauthorized, 340B, 10ms]

└ Get product
  GET http://localhost:8080/api/v1/products/null [400 Bad Request, 309B, 6ms]

└ Delete product
  DELETE http://localhost:8080/api/v1/products/null [400 Bad Request, 309B, 5ms]

What this code does

  • This is the exported ShopLite Local file. adminPassword has type secret and an empty value, so the password never left the author's computer.
  • Run on a computer where nobody set a current value, the Basic Auth password is empty: Create product gets 401. The chain then breaks: no id was saved, so the next requests go to /products/null.

Create environments under Environments in the sidebar. Each variable has a type and two values. Type secret hides the value as dots. The initial value is saved in the workspace and goes into exports and to teammates; the current value stays only on your computer and is what Postman sends. Put passwords, tokens and API keys only in the current value. Postman Vault ({{vault:name}}) is another way to keep a secret only on your machine.

The classic leak is a real password typed into the initial value, exported and pushed to GitHub, where bots scan public repositories for secrets within minutes. Before you export, check that every secret's initial value is empty.

An exported environment with an empty secret needs the value again on each computer: type it as your current value, or pass it at run time from the command line.

Passing an id from one response to the next request

Chaining means one request saves a value from its response into a variable, and later requests use that variable. The new id of a created product flows into the Get and Delete requests.

A short script after Create product stores the new id, and Get and Delete use it in their URL. The picture shows the flow.

A collection runs four requests in order. Login saves the variable token. Create product sends the token and saves the variable productId. Get product and Delete product send the token and use productId in their URL.

Example 4 · The created id flows into the next requests

Text
POST    {{baseUrl}}/products                 Create product        Scripts -> Post-response:        pm.collectionVariables.set("productId", pm.response.json().id);GET     {{baseUrl}}/products/{{productId}}   Get productDELETE  {{baseUrl}}/products/{{productId}}   Delete productadminPassword supplied for this run
Sample output
$ newman run shoplite-api.postman_collection.json -e local.postman_environment.json --env-var adminPassword=admin123 --folder Products --reporter-cli-no-summary --reporter-cli-no-banner
ShopLite API

□ Products
└ List accessories by price
  GET http://localhost:8080/api/v1/products?categoryId=4&sort=price,asc [200 OK, 563B, 253ms]

└ Create product
  POST http://localhost:8080/api/v1/products [201 Created, 296B, 50ms]

└ Get product
  GET http://localhost:8080/api/v1/products/16 [200 OK, 260B, 71ms]

└ Delete product
  DELETE http://localhost:8080/api/v1/products/16 [204 No Content, 111B, 6ms]

What this code does

  • With the password supplied, the create works and the script stores 16 in the collection variable productId.
  • Get and Delete then go to /products/16 with no copying by hand. On a busier database the id differs, and the same collection still works.

After Create product, a one-line script in the Scripts tab, under Post-response, stores the new id: pm.collectionVariables.set("productId", pm.response.json().id);. Then Get product and Delete product use {{baseUrl}}/products/{{productId}}. Without chaining you copy the id by hand after every create, and a test suite cannot run on its own. With it, the same requests work on a fresh database, where the new id might be 16, or on a busy one, where it is 9416.

Chains break in a cascade. If the create fails, the script stores nothing useful and every later request goes to /products/null, failing with a confusing 400. Always fix the first failure in a chain; the next lesson adds tests that make it obvious.

Exporting a collection to commit it with the project

Export writes a collection or environment to a JSON file, so it can be committed with the project and imported on another computer.

Export the collection and each environment into a postman/ folder, rename the files to short names, and commit them.

Example 5 · Export, rename and commit

Terminal
mkdir postmancp ~/Downloads/"ShopLite API.postman_collection.json" postman/shoplite-api.postman_collection.jsoncp ~/Downloads/"ShopLite Local.postman_environment.json" postman/local.postman_environment.jsoncp ~/Downloads/"ShopLite Production.postman_environment.json" postman/production.postman_environment.jsongrep -A1 "\"key\"" postman/local.postman_environment.jsongit add postmangit status --shortgit commit -m "Add Postman collection and environments"
Sample output (your commit id differs)
$ mkdir postman
$ cp ~/Downloads/"ShopLite API.postman_collection.json" postman/shoplite-api.postman_collection.json
$ cp ~/Downloads/"ShopLite Local.postman_environment.json" postman/local.postman_environment.json
$ cp ~/Downloads/"ShopLite Production.postman_environment.json" postman/production.postman_environment.json
$ grep -A1 "\"key\"" postman/local.postman_environment.json
			"key": "baseUrl",
			"value": "http://localhost:8080/api/v1",
--
			"key": "adminEmail",
			"value": "admin@shoplite.test",
--
			"key": "adminPassword",
			"value": "",
$ git add postman
$ git status --short
A  postman/local.postman_environment.json
A  postman/production.postman_environment.json
A  postman/shoplite-api.postman_collection.json
$ git commit -m "Add Postman collection and environments"
[main a071161] Add Postman collection and environments
 3 files changed, 214 insertions(+)
 create mode 100644 postman/local.postman_environment.json
 create mode 100644 postman/production.postman_environment.json
 create mode 100644 postman/shoplite-api.postman_collection.json

What this code does

  • The three exported files are copied from Downloads into the project with short names. On Windows, run the same commands in Git Bash, or copy the files in File Explorer.
  • The grep is a last check before committing: every value is safe to publish, and adminPassword is empty.

Use the collection's ... menu → Export → Collection v2.1 → Export, and the environment's ... menu → Export. In Git, the API's requests are reviewed and versioned next to its code. A teammate brings the files back with Import (drag them into Postman).

Postman names files after the collection, with spaces: ShopLite API.postman_collection.json. Rename them to short names without spaces, such as shoplite-api.postman_collection.json; they are easier to type in commands. Commit the collection and the environments, never a file with a real secret in it, and commit again whenever requests change, so the collection in Git always matches the API.

Next step

Check your understanding

12 quick questions