QA Interview Hub · Knowledge base · Quizzes · Українська

API

Postman: structure and variables

Collections, environments and variables

A collection says what to request and an environment says where and with what values, so one collection runs on dev, stage and prod. The host and data are written as {{baseUrl}}, with values kept in the environment, switched from a list. Dynamic variables such as {{$guid}} give a new value on every substitution, so a value also needed in an assertion is fixed with a script.

API · Postman: structure and variables

Same requests, different environments. How do you avoid a collection copy for dev, stage and prod?

The same API lives on dev, stage and prod. The simplest move is to copy the collection three times and replace the host in every request. Within a month the copies drift apart: one got a fixed request body, the second did not, the third still has a stage account. Postman solves it by splitting the roles: the collection describes what to ask and the environment says where and with which values. This lesson covers how they combine and where a variable can let you down.

How it works and why it is designed so

A collection is a set of requests for one API, laid out in folders (Auth, Accounts, Transfers). It also carries shared settings: authorization, scripts, variables, a description. Folders and requests inherit them, so the token and baseUrl are configured once and not in every request (more in the lesson on collection structure).

An environment is a named set of variables for a specific stand. One collection, three environments, and the stand is switched from the list in the top right corner. Before sending, Postman substitutes variable values into the URL, params, headers, body and authorization: everything written as {{name}}. Substitution happens at send time, so changing the environment affects the next request without editing the collection.

One collection, three environments

GET {{baseUrl}}/accounts selected environment devbaseUrl = dev.example.test stagebaseUrl = stage.example.test prodbaseUrl = example.test
Figure 1. The request stays the same: the selected environment substitutes its own baseUrl.

Example: before and after

Before: three sets of requests with hard-coded hosts.

# Three copies of the collection, a different host in every request
GET https://dev.example.test/accounts/acc-1001
GET https://stage.example.test/accounts/acc-1001
GET https://example.test/accounts/acc-1001

After: the host and the identifier are variables and the values live in the environment.

# One collection, only the selected environment changes
GET {{baseUrl}}/accounts/{{accountId}}

An environment is stored as JSON and can be exported. Here is a simplified stage example (a real file has more service fields and identifiers):

{
  "name": "stage",
  "values": [
    { "key": "baseUrl", "value": "https://stage.example.test",
      "type": "default", "enabled": true },
    { "key": "accountId", "value": "acc-1001",
      "type": "default", "enabled": true }
  ],
  "_postman_variable_scope": "environment"
}

Dynamic variables generate data at run time: {{$guid}}, {{$timestamp}}, {{$randomInt}}, {{$randomEmail}}. They are needed when every run must create a unique user or key, so it does not hit a 409 on a duplicate. The trap: the value is generated during substitution, so you cannot read it back later. If the email is needed both in the body and in a check, fix it with a script through pm.variables.replaceIn:

// Pre-request: one email for the request body and for the check
const email = pm.variables.replaceIn('{{$randomEmail}}');
pm.variables.set('email', email);
// request body: { "email": "{{email}}" }

// Post-response of the same request
pm.test('The email in the response is the one we sent', () => {
  pm.expect(pm.response.json().email).to.eql(pm.variables.get('email'));
});

Limits and alternatives

An environment answers "where", but not "who": test logins and tokens are often put into variables too, and that is where the topic of secrets starts (see the lesson on variable scopes and secrets). To change behaviour inside one stand (different roles, different plans) environments are not enough: use data in the Runner or separate folders. Do not confuse an environment with collection copies on branches: one collection with several environments keeps one version of the logic.

Common mistakes

  • No environment selected. Variables are not substituted, a literal {{baseUrl}} stays in the URL and the request never reaches the server;
  • A host typed into a request. On another stand the test quietly hits the old host;
  • Prod data in the dev environment and vice versa. Name the variables the same and keep the values apart, and check which environment is active before a run;
  • A dynamic variable instead of stable data. A "find the created one" test cannot find it because each substitution gives a new value;
  • Exporting an environment into the repository with real keys. Export only non-secret values.

Check yourself

A request goes to an address with a literal {{baseUrl}} and fails. Which two causes should you check first?

Answer

First, whether an environment is selected (with "No environment" the variable does not exist). Second, whether baseUrl exists in the active environment and the name has no typo (case matters).

Why is one collection and three environments better than three collections?

Answer

The request and check logic is the same, so it is edited in one place. Three copies drift apart and a bug fixed in one stays in the others. Only values differ (host, account) and they live in the environment.

In an interview. Junior: A collection is the requests and an environment is a set of variables for a stand. I write the host as {{baseUrl}} and switch dev, stage, prod from the list without copying requests. Middle/Senior: One collection is one version of the logic; environments carry only the values that differ between stands. I fix dynamic variables with a script when the value is needed in a check, and keep secrets out of shared values and exports.

Variable scopes and secrets

A Postman variable lives in a scope (Global, Collection, Environment, Data, Local), and with equal names the narrowest wins. Secrets are not put in a Shared value, because it syncs with the team and reaches exports and git: they are kept in a Local value or Postman Vault, and in CI come from the pipeline's secret store. A secret that reached a Shared value or a repository is treated as compromised.

API · Postman: structure and variables

A token sits in an environment variable and a teammate sees it in their Postman. Where is it stored?

There are two stories about variables. In the first, a same-named baseUrl exists in both the collection and the environment, and the request goes not where it was expected. In the second, a tester pasted a token into an environment variable, shared the environment with the team, and the token landed with everyone in the workspace and then in an export. Both stories are about the same thing: a variable lives in a particular scope with a particular visibility. This lesson lays out the scopes by priority and by who sees the value.

How it works and why it is designed so

Scopes go from wide to narrow. If names match, the narrow one wins: a shared value can be overridden precisely without touching the rest.

ScopeWhere it appliesTypical useIn a script
GlobalThe whole workspaceRarely; better avoidedpm.globals
CollectionOne collectionAPI version, constantspm.collectionVariables
EnvironmentThe active environmentbaseUrl, test loginspm.environment
DataOne Runner iterationA CSV or JSON rowpm.iterationData
LocalOne request run or a collection runTemporary valuespm.variables

Scripts read a variable in two ways: pm.variables.get returns the value from the scope that won, while pm.environment.get or pm.collectionVariables.get look only in their own scope. So the same code in two places can give different values if the variable is also set in a narrower scope.

Shared and Local value. A variable in an environment has two values. The Local value lives only on your machine: it is the one substituted into requests and it is not synced to the Postman Cloud. The Shared value is synced with the team when you share it. In older Postman versions these were called initial and current value, so you meet those names in older materials.

Where the token lives

Risky

Token in the Shared value

It is synced to the team, goes into the environment export and can end up in git.

Better

Token in the Local value or Vault

It stays on your machine: it does not reach the shared workspace or an export.

Figure 1. The same value in different places: the difference is who can see it.

Example: who wins, and where the secret lives

One name in three scopes. The request takes the value from the narrowest one present:

collection   baseUrl = https://a.example.test
environment  baseUrl = https://b.example.test
data row     baseUrl = https://c.example.test

with a data file    -> https://c.example.test
without a data file -> https://b.example.test
without environment -> https://a.example.test
pm.variables.get('baseUrl');            // the winner of all scopes
pm.environment.get('baseUrl');          // the environment only
pm.collectionVariables.get('baseUrl');  // the collection only

Secrets have three levels of protection, from simple to solid. A secure variable is stored encrypted and masked in the interface. Postman Vault keeps secrets encrypted (the local vault stays on your machine, the shared vault lives in the Postman Cloud), and they are referenced as {{vault:name}} or read in a script asynchronously through await pm.vault.get('name'). In CI the secret comes from the pipeline store and is passed on the command line:

# In CI the secret comes from the pipeline store, not from a file
newman run api.postman_collection.json \
  -e stage.postman_environment.json \
  --env-var "password=$API_PASSWORD"

Limits and alternatives

The Vault and your laptop's Local value are unavailable to CI and to a cloud monitor: only values passed explicitly apply there (details in the lesson on secrets, mock servers and monitors). The Global scope looks convenient, but a variable without a collection is available to every collection in the workspace and quickly becomes a source of odd name clashes: keep values in an environment or a collection. If a secret does reach a Shared value or a repository, treat it as compromised and reissue it.

Common mistakes

  • A token or password in a Shared value. Everyone with access to the workspace sees it, it goes into an export and can reach git;
  • Same-named variables in several scopes. Someone edits the collection while the request takes the value from the environment. Give variables unique names or check which scope wins;
  • Global for everything. A value becomes shared by all collections and lingers from old projects;
  • Deleted a secret from the variable and relaxed. It stayed in history or an export: the key must be reissued.

Check yourself

baseUrl exists in the collection, in the active environment and in a CSV row in the Runner. Which value goes into the request and why?

Answer

The CSV row one: the data scope is narrower than environment, and environment is narrower than collection. Without a data file the environment would win.

Why is a token not put into the Shared value?

Answer

The Shared value is synced to the team, goes into the environment export and can end up in git. A token is kept in the Local value or the Vault, and in CI it comes from the secret store.

In an interview. Junior: Variable scopes are Global, Collection, Environment, Data and Local; for the same names the narrower wins. I keep secrets only in a Local value or the Postman Vault so they do not reach a shared workspace or an export. Middle/Senior: For predictable behaviour I give variables unique names and choose the scope by lifecycle: the stand in the environment, a constant in the collection, a case row in data. A secret that reached a Shared value or git I treat as compromised and reissue, and in CI I pass it from the pipeline store.

Collection structure: folders, inheritance, documentation

A collection is a tree: authorization and shared scripts are set at collection or folder level, and requests inherit them from the parent. Folders have no variables. The authorization scheme is then changed in one place, and an exception such as GET /health gets No Auth on the request. Requests are named as action, resource and expectation, and saved examples and Markdown descriptions become documentation.

API · Postman: structure and variables

A collection of 80 requests with the token set in each one. How do you do it once?

A collection of 80 requests laid out "as it happened" becomes unmaintainable within a month. The token is typed into every request, so when the authorization scheme changes there are eighty places to edit. Names like "Request 37" say nothing in a Runner report. Collection structure is not aesthetics: it decides how many times you must configure authorization, variables and scripts and how easy the result is to read.

How it works and why it is designed so

The collection, a folder and a request form a tree, and settings travel downwards. Authorization and scripts are set at the collection or folder level, variables at the collection level, and a request takes them from its "parent". For authorization this is the Inherit auth from parent mode, the default for a new request. To make one request (say GET /health) go without a token, choose No Auth in it and the rest does not change. Scripts run in the order collection, folder, request, so shared logic (an environment check, a token refresh, a general response-time check) is written once at the top.

Inheritance in a collection

Collection authorization, variables, scripts inherits Transfers folder its own auth and scripts if needed inherits POST /transfers Inherit auth from parent
Figure 1. A setting is made once at the top and the request takes it from its parent.

Two kinds of folders. There is no single right scheme: these are two tools for different jobs, and a mature collection has both.

A resource folder or a scenario folder

By resource

Accounts, Transfers

CRUD and negative checks of one resource. Handy for exploring the API and for documentation.

By scenario

Transfer: start to finish

A chain with data, an action, a check and cleanup. Runs as a whole folder in the Runner or Newman.

Figure 2. Both are legitimate: the choice depends on what you do, exploring the API or running regression.

Example: a structure that reads well

Request names follow "action + resource + expectation": a Runner report shows at once what failed and you do not need to open the request.

Bank API                     <- auth, variables, shared scripts
  Auth
  Accounts                    <- a resource folder
    GET /accounts - 200 list
    GET /accounts/{id} - 404 foreign id
  Transfers
    POST /transfers - 201 created
    POST /transfers - 422 amount 0
  Scenarios
    Transfer: from creation to debit
      1 create an account
      2 POST /transfers
      3 check the balance
      4 clean up the data
// Pre-request at the COLLECTION level: runs before every request
// (then the folder script, then the request's own)
if (!pm.environment.get('baseUrl')) {
  throw new Error('No environment selected: baseUrl is empty');
}

Response examples. A saved "request and response" pair documents the expected behaviour and is the basis for a mock server. Negative responses (400, 404, 422) are worth saving as examples too. Documentation. A Markdown description exists on the collection, folder and request: purpose, required fields, error codes. Postman builds the Documentation page from it, which can be published for a team or partners. Teamwork. A team works in a shared workspace; changes are proposed through a collection fork and a pull request. For review in git the collection is exported to JSON (format v2.1) and stored in the repository next to the code; the newer Postman format with separate YAML files per request reads better in a diff.

Limits and alternatives

Inheritance eases maintenance but hides where behaviour comes from: a request "just fails with 401" while the cause is a collection script or the folder's authorization mode. When something is unclear, check the Authorization tab and scripts at all three levels. An overly nested structure (a folder in a folder in a folder) hurts too: two or three levels is usually enough. For a large regression set with logic, data factories and review in git, code (Playwright request and similar) is more convenient: see the lesson on Postman's limits.

Common mistakes

  • Authorization in every request. A scheme change means edits in dozens of places. Set it on the collection;
  • Nameless requests. "New Request" and "Copy of …" say nothing in a report;
  • A hidden folder script. A request behaves oddly because a higher-level script ran before it;
  • Negative cases without an example. The documentation shows only success and nobody knows what happens on 422;
  • A scenario without cleanup. The folder creates data and leaves it, so the second run hits a 409.

Check yourself

All requests of the collection go with a token, but GET /health must go without it. How do you set that up without copying the collection?

Answer

Authorization is set on the collection and in the /health request you choose No Auth instead of Inherit auth from parent. The other requests stay on the inherited token.

When do you use a resource folder and when a scenario folder?

Answer

A resource folder for CRUD and negative checks of one resource and for documentation. A scenario folder for an end-to-end chain (create, act, check, clean up) that is run as a whole folder in the Runner or Newman.

In an interview. Junior: I keep authorization and shared scripts at the collection level, make folders by resource, and name requests as "action, resource, expectation". Every request has a response example and a description. Middle/Senior: I move scenarios into separate folders for the Runner and Newman and keep resource folders for exploration and documentation. For odd behaviour I check inheritance and scripts at all three levels, and for review I keep the collection in the repository.

Secrets, mock servers and monitors in Postman

Secrets do not belong in a Shared value, because it is synced to the team and exported: secure variables, Local values and Postman Vault exist for them. A mock server answers with saved examples but does not prove the real server works. A cloud monitor sees only Shared values and, without Private API Monitoring, cannot reach localhost or a VPN; its requests must be safe and repeatable.

API · Postman: structure and variables

The collection is green locally but the cloud monitor gets 401. What can it not see?

A collection passed locally and gets switched on as a monitor. The very first run sends an email that everything failed with 401. Nothing changed in the backend; one thing did: the monitor runs in the Postman cloud and does not see what lies on your laptop. This lesson is about three tools around a collection: secrets, a mock server and a monitor. Each has its limits, and the limits are what gets asked in interviews.

How it works and why it is designed so

Secrets. A password, API key or token is not for a Shared value: it is synced to the team, goes into the environment export and can end up in git. There are several levels. A secure variable is stored encrypted and masked in the interface. A value can be kept in the Local value, which stays on the machine. The Postman Vault stores secrets encrypted, they are referenced as {{vault:name}} and read in scripts through await pm.vault.get('name') (the method is asynchronous; the pm.vault methods do not work in Newman, the Postman CLI or monitors). In CI secrets come from the pipeline store and are passed to Newman through --env-var. If a secret reached a Shared value or a repository, it is treated as compromised: the key is reissued, not just deleted from the variable.

A mock server is created from a collection and answers with saved examples: Postman picks an example by method and path (the body only raises the match score; strict body and header matching is turned on in the mock settings or with the x-mock-match-request-body and x-mock-match-request-headers headers). It is needed when the backend is not ready: the frontend, a mobile client or consumer tests work against the mock while the contract is already fixed in OpenAPI or the collection.

A monitor runs a collection on a schedule in the Postman cloud from selected regions and sends a notification when tests fail. It watches availability and the contract of staging or production, and does not check every commit.

The same request locally and in a monitor

Good

Local run

Shared and Local values exist: the token is substituted, the response is 200.

Bad

Cloud monitor

Only Shared values exist: there is no token, the response is 401.

Figure 1. A green local run says nothing about the monitor: the cloud cannot see Local values.

Example: a mock and a monitor in practice

A specific mock example can be chosen with the x-mock-response-name or x-mock-response-code header. That is handy for negative scenarios that are hard to reproduce on a real backend:

POST {{mockUrl}}/transfers
Content-Type: application/json
# pick a saved example by its name
x-mock-response-name: Insufficient funds

{ "amount": 999999, "currency": "UAH" }

A request in a monitor must be safe and repeatable: it runs constantly, so it must not create garbage or move money. A typical health check:

// Post-response for a request in a monitor: a safe, repeatable check
pm.test('Service health', () => {
  pm.response.to.have.status(200);
  pm.expect(pm.response.responseTime).to.be.below(1500);
});

Limits and alternatives

  • A mock from a collection has no logic: it returns only what is saved (code-based mocks in JavaScript can have logic and state). No mock proves the real server works, so the contract should be checked separately;
  • Only Shared values apply in the cloud; Local values and the Vault from your computer do not get there. That is why everything is green locally and the monitor gets 401;
  • A cloud monitor does not see localhost or a network behind a VPN. For internal APIs the collection is run on a schedule through Newman or the Postman CLI in your own CI (check what your plan allows);
  • The per-commit pipeline runs through Newman in CI and the monitor complements it: it notices that an endpoint broke without any deploy (a certificate, a dependent service, configuration).

Common mistakes

  • A secret in a Shared value. Everyone sees it and it goes into the export;
  • A monitor with a request that creates data. Garbage piles up each night or it fails with 409;
  • Trusting a mock as proof. The frontend is green on the mock while the real backend returns another field;
  • A monitor for an internal API. The cloud cannot see it and the failure alerts are false;
  • A mock without negative examples. The frontend cannot check 4xx and 5xx errors.

Check yourself

The collection is green locally while the cloud monitor gets 401. What is the most likely cause?

Answer

The token lives in a Local value or the local Vault while the cloud sees only Shared values (and, on Enterprise, Shared Vault secrets linked to an external vault). The fix: obtain the token with a separate auth request in a pre-request, using a monitor-only test account whose credentials come through a protected mechanism the monitor supports, and do not put the real key into a Shared value.

When is a mock server useful and what does it not prove?

Answer

When the backend is not ready and the frontend or consumer tests must work against an already fixed contract. It does not prove the real server works and returns the same: that needs contract checks against the real API.

In an interview. Junior: I do not put secrets into a Shared value and in CI I pass them from the secret store. I use a mock for parallel development and a monitor for regular checks of a live API. Middle/Senior: I remember the limits: a monitor sees only Shared values and cannot see localhost or a VPN, and a collection mock without logic proves nothing about the real server. So I combine a mock with a contract check and keep the monitor on safe repeatable requests next to CI.