0
0
Postmantesting~8 mins

Bearer token in Postman - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Bearer token
Folder Structure
postman-project/
├── collections/
│   └── api-requests.postman_collection.json
├── environments/
│   ├── dev.postman_environment.json
│   ├── staging.postman_environment.json
│   └── prod.postman_environment.json
├── scripts/
│   ├── pre-request-scripts.js
│   └── test-scripts.js
├── globals.json
└── README.md
    

This structure organizes API requests, environment configs, and scripts separately for clarity.

Test Framework Layers
  • Collections: Group of API requests, each can use Bearer token for authorization.
  • Environments: Store variables like bearer_token for different stages (dev, staging, prod).
  • Pre-request Scripts: Scripts that run before requests to set or refresh Bearer tokens dynamically.
  • Tests: Scripts that run after requests to validate responses and token usage.
  • Globals: Variables accessible across collections if needed.
Configuration Patterns

Use environment variables to manage Bearer tokens securely and flexibly:

  • Store the token in environment variable bearer_token.
  • In the request Authorization tab, select Bearer Token and use {{bearer_token}} as the token value.
  • Use pre-request scripts to refresh or update the token automatically if expired.
  • Keep sensitive tokens out of collections by using environment files and .gitignore for security.

Example pre-request script snippet to set token:

// Example: Set Bearer token from environment variable
pm.environment.set('bearer_token', 'your_actual_token_here');
    
Test Reporting and CI/CD Integration
  • Use Newman (Postman CLI) to run collections in CI/CD pipelines.
  • Newman supports exporting test run reports in formats like JSON, HTML, JUnit XML.
  • Integrate Newman runs in CI tools (GitHub Actions, Jenkins, GitLab CI) to automate API tests with Bearer token authentication.
  • Use environment variables or secrets in CI to inject Bearer tokens securely during runs.
  • Reports help track pass/fail status of API tests that require Bearer tokens.
Best Practices
  1. Use environment variables to store Bearer tokens, never hard-code tokens in collections.
  2. Automate token refresh in pre-request scripts to avoid manual updates.
  3. Secure tokens by excluding environment files with tokens from version control.
  4. Use descriptive names for environment variables like bearer_token for clarity.
  5. Validate token usage in test scripts by checking response status codes and error messages.
Self Check

Where in this folder structure would you add a new pre-request script to automatically refresh the Bearer token before API calls?

Key Result
Use environment variables and pre-request scripts in Postman to manage Bearer tokens securely and efficiently.