DEV Community

Cover image for Switching Auth Method in Postman dinamically
Mark Kop
Mark Kop

Posted on

Switching Auth Method in Postman dinamically

We're using Postman's Mock Server feature to develop the endpoints and payloads for our new API and I came to the issue where I couldn't easily switch auth methods to use the same request to call the API itself or the Mock Server

The solution was creating a Pre-request script to the root folder that would detect the active environment and add the correct authentication method header and secret

if (pm.environment.name.toLowerCase().includes('mock')) {
    pm.request.headers.upsert({key: 'x-api-key', value: pm.environment.get('api-key')});
} else {
    pm.request.headers.upsert({key: 'Authorization', value: 'Bearer ' + pm.environment.get('accessToken')});
}
Enter fullscreen mode Exit fullscreen mode

Image description

Hope that helps anyone looking for something similar

Top comments (1)

Collapse
 
philip_zhang_854092d88473 profile image
Philip

Dynamically switching auth methods in Postman using pre-request scripts streamlines workflows, automating header updates based on the active environment. This approach ensures consistency and reduces manual effort when toggling between Mock Servers and live APIs. Tools like echoapi.io/ enhance this process by simplifying API mocking and environment management.