0
0
Postmantesting~8 mins

Setting variables from response in Postman - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Setting variables from response
Folder Structure
PostmanCollectionProject/
├── collections/
│   └── api-collection.json
├── environments/
│   ├── dev.postman_environment.json
│   ├── staging.postman_environment.json
│   └── prod.postman_environment.json
├── tests/
│   └── scripts/
│       └── setVariablesFromResponse.js
├── globals/
│   └── global-variables.json
└── README.md

This structure organizes Postman collections, environment files, test scripts, and global variables separately for clarity and reuse.

Test Framework Layers
  • Collections: Define API requests and workflows.
  • Environment Files: Store environment-specific variables like base URLs and credentials.
  • Test Scripts: JavaScript code to run after requests, used to extract data from responses and set variables.
  • Global Variables: Variables accessible across collections and environments.
  • Utilities: Helper scripts or functions to parse responses or handle common tasks.
Configuration Patterns
  • Environment Variables: Use environment files to switch between dev, staging, and prod settings easily.
  • Setting Variables from Response: Use pm.environment.set() or pm.collectionVariables.set() in test scripts to save values from API responses.
  • Secure Credentials: Store sensitive data in environment variables, not in collections.
  • Variable Scope: Use environment variables for environment-specific data, collection variables for shared data, and global variables sparingly.

Example test script to set a variable from JSON response:

const jsonData = pm.response.json();
pm.environment.set("userId", jsonData.id);
Test Reporting and CI/CD Integration
  • Use Newman (Postman CLI) to run collections in CI/CD pipelines.
  • Generate reports in formats like HTML or JSON using Newman reporters.
  • Integrate with CI tools (Jenkins, GitHub Actions, GitLab CI) to run tests on code changes.
  • Use environment variables in CI to inject credentials securely.
  • Review test run reports to verify variables were set correctly from responses.
Best Practices
  1. Use Clear Variable Names: Name variables to reflect their purpose, e.g., authToken, userId.
  2. Validate Response Before Setting: Check response status and data before setting variables to avoid errors.
  3. Limit Variable Scope: Use environment or collection variables appropriately to avoid conflicts.
  4. Keep Sensitive Data Secure: Never hardcode secrets in scripts; use environment variables.
  5. Document Variable Usage: Maintain README or comments explaining what variables are set and why.
Self Check

Where in this folder structure would you add a new script to extract and set a session token from an API response?

Key Result
Use Postman test scripts to extract data from API responses and set environment or collection variables for reuse in subsequent requests.