0
0
Postmantesting~8 mins

Collection variables in Postman - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Collection variables
Folder Structure of a Postman Collection Project
postman-project/
├── collections/
│   └── MyAPI.postman_collection.json
├── environments/
│   ├── dev.postman_environment.json
│   ├── staging.postman_environment.json
│   └── prod.postman_environment.json
├── scripts/
│   ├── pre-request-scripts.js
│   └── test-scripts.js
├── README.md
└── postman_globals.json
  
Test Framework Layers in Postman Collection
  • Collection Layer: Contains API requests grouped logically. Uses collection variables for shared values.
  • Environment Layer: Holds environment-specific variables like base URLs and credentials.
  • Scripts Layer: Includes pre-request and test scripts to run before or after requests.
  • Globals Layer: Stores global variables accessible across collections and environments.
  • Configuration Layer: Manages environment files and collection variables for flexible testing.
Configuration Patterns for Collection Variables

Collection variables are defined inside the Postman collection JSON or via the Postman app UI. They store values shared by all requests in the collection.

Use collection variables to hold values like API keys, tokens, or common parameters that do not change per environment.

For environment-specific values (like base URLs), use environment variables instead.

Example of setting a collection variable in a pre-request script:

pm.collectionVariables.set("api_key", "12345abcde");
  

To access a collection variable in a request URL or header, use {{variable_name}} syntax.

Test Reporting and CI/CD Integration

Postman collections can be run via Newman, the command-line runner.

Newman supports generating reports in formats like HTML, JSON, and JUnit XML.

Example Newman command with HTML report:

newman run collections/MyAPI.postman_collection.json \
  -e environments/dev.postman_environment.json \
  --reporters cli,html \
  --reporter-html-export reports/report.html
  

Integrate Newman runs into CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) to automate API testing on code changes.

Best Practices for Using Collection Variables
  • Use collection variables for values shared across all environments and requests, like API keys.
  • Keep sensitive data out of collection variables; use environment variables or secure vaults.
  • Use descriptive names for variables to improve readability and maintenance.
  • Document variable usage in README or collection description for team clarity.
  • Regularly review and clean unused variables to keep collections tidy.
Self-Check Question

Where in this Postman project structure would you add a new collection variable for an API token used by all requests?

Key Result
Use collection variables in Postman collections to share common values across all requests, improving maintainability and reusability.