How to Run One Request from Another in Postman: Automate OAuth Token Retrieval with Pre-request Scripts for Single-Click Authenticated Requests

APIs are the backbone of modern software, but many require authentication—often via OAuth 2.0—to ensure secure access. A common workflow involves first retrieving an OAuth access token (via a dedicated token endpoint) and then using that token to authenticate subsequent API requests. Manually repeating this process (copy-pasting tokens, re-running token requests) is tedious, error-prone, and slows down testing.

Postman, the popular API testing tool, solves this with pre-request scripts—code snippets that run before a request executes. In this guide, we’ll automate OAuth token retrieval by running a token request from within another request using pre-request scripts. The result? Single-click authenticated API requests, no manual token handling required.

Table of Contents#

  1. Prerequisites
  2. Understanding the Workflow
  3. Step 1: Set Up the OAuth Token Request
  4. Step 2: Store the Token in an Environment Variable
  5. Step 3: Create the Authenticated API Request
  6. Step 4: Write the Pre-request Script to Run the Token Request
  7. Step 5: Test the Automated Flow
  8. Troubleshooting Common Issues
  9. Best Practices
  10. Conclusion
  11. References

Prerequisites#

Before starting, ensure you have:

  • Postman installed (v9.0+ recommended; download from postman.com).
  • Basic familiarity with APIs (HTTP methods, request/response structure).
  • An OAuth-protected API endpoint to test (e.g., a backend service requiring Bearer token authentication).
  • OAuth credentials from your API provider:
    • client_id and client_secret (for client credentials flow).
    • OAuth token endpoint URL (e.g., https://auth.example.com/oauth/token).
    • Optional: scope (if required by the API).

Understanding the Workflow#

The manual workflow for authenticated API testing looks like this:

  1. Manually send a request to the OAuth token endpoint to get an access_token.
  2. Copy the access_token from the response.
  3. Paste the token into the “Bearer Token” field of your main API request.
  4. Run the main request.

This is repetitive and error-prone. With Postman pre-request scripts, we automate step 1–3:

Automated Workflow:

  1. When you run your main API request, its pre-request script automatically triggers the OAuth token request.
  2. The token request fetches a new access_token and saves it to an environment variable.
  3. The main request uses the saved access_token from the environment variable to authenticate.

Step 1: Set Up the OAuth Token Request#

First, create a dedicated request in Postman to fetch the OAuth token. We’ll use the Client Credentials Flow (common for server-to-server communication) as an example. Adjustments for other flows (e.g., Password Flow) are noted later.

1.1 Create a New Request#

  • Open Postman → Click “New” → Select “Request” → Name it “Get OAuth Token” (or similar) → Add to a collection (e.g., “My API Collection”).

1.2 Configure the Token Request#

  • Method: Set to POST (most OAuth token endpoints use POST).
  • URL: Enter your OAuth token endpoint (e.g., https://auth.example.com/oauth/token).

1.3 Define the Request Body#

OAuth token endpoints typically expect form-encoded data. In Postman:

  • Go to the Body tab → Select “x-www-form-urlencoded”.
  • Add the following key-value pairs (adjust based on your API’s requirements):
KeyValueDescription
grant_typeclient_credentialsRequired for Client Credentials Flow. Use password for Password Flow.
client_id{{clientId}}Your OAuth client ID (stored in an environment variable for security).
client_secret{{clientSecret}}Your OAuth client secret (also stored in an environment variable).
scoperead write (optional)Space-separated scopes (e.g., api:read). Required if your API enforces scopes.

Example Body:
Token Request Body
(Note: Replace {{clientId}} and {{clientSecret}} with your actual credentials, or store them in environment variables first—see Step 1.4.)

1.4 Store Sensitive Data in Environment Variables#

To avoid hard-coding client_id and client_secret (a security risk), store them in an environment variable:

  • Create an Environment:
    • Click the “Environment” dropdown (top-right) → “Add” → Name it (e.g., “My API Env”) → Add variables:
      • clientId: Your actual client ID.
      • clientSecret: Your actual client secret.
    • Click “Save” → Select the environment from the dropdown to activate it.

Step 2: Storing the Token in an Environment Variable#

After fetching the token, we need to save access_token (from the response) to an environment variable so the main request can access it.

2.1 Extract and Save the Token#

In Postman, use the Tests tab of the “Get OAuth Token” request to automate saving the token.

  • Go to the Tests tab of the token request → Add the following script:
// Parse the JSON response from the token endpoint
const responseJson = pm.response.json();
 
// Check if access_token exists in the response
if (responseJson.access_token) {
  // Save the access token to the environment variable "accessToken"
  pm.environment.set("accessToken", responseJson.access_token);
  console.log("Successfully saved access token to environment variable.");
} else {
  // Throw an error if the token is missing (helps debug failed requests)
  throw new Error("Failed to retrieve access token. Response: " + JSON.stringify(responseJson));
}

2.2 Test the Token Request#

  • Run the “Get OAuth Token” request → Check the response. If successful, you’ll see a JSON object like:
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "read write"
}
  • Verify the accessToken variable is set: Go to the environment (top-right) → Click the eye icon → Check that accessToken has a value.

Step 3: Create the Authenticated Request#

Now, create your main API request (the one you want to automate). This request will use the accessToken variable for authentication.

3.1 Configure the Main Request#

  • Create a new request (e.g., “Get User Data”) → Add to the same collection as the token request.
  • URL: Enter your main API endpoint (e.g., https://api.example.com/users).
  • Method: Set to GET (or your API’s required method).

3.2 Set Up Bearer Token Authentication#

  • Go to the Authorization tab → Select “Bearer Token” → In the “Token” field, enter {{accessToken}}.

    Postman will replace {{accessToken}} with the value stored in your environment variable.

Step 4: Write the Pre-request Script to Run the Token Request#

The final step is to link the main request to the token request using a pre-request script. This script runs before the main request executes and triggers the token request.

4.1 Access the Token Request in the Pre-request Script#

To run the “Get OAuth Token” request automatically, reference it in the main request’s pre-request script. Use Postman’s pm.sendRequest function to programmatically send requests.

If the “Get OAuth Token” request is saved in your collection, fetch it by name and send it:

  1. In your main request, go to the Pre-request Script tab.
  2. Add the following script:
// Find the "Get OAuth Token" request in the collection
const tokenRequest = pm.collection.items.find(
  (item) => item.name === "Get OAuth Token" // Match the name of your token request
);
 
// If the token request exists, send it
if (tokenRequest) {
  pm.sendRequest(tokenRequest, (err, response) => {
    if (err) {
      console.error("Error fetching token:", err);
      throw new Error("Failed to retrieve OAuth token.");
    } else {
      console.log("Token request successful. Token saved to environment.");
    }
  });
} else {
  throw new Error("Token request not found in collection.");
}

Option B: Embed Token Request Details (Alternative)#

If you prefer not to save the token request separately, embed its details directly in the pre-request script:

// Define the token request details
const tokenRequest = {
  url: pm.environment.get("tokenUrl"), // e.g., "https://auth.example.com/oauth/token"
  method: "POST",
  header: "Content-Type: application/x-www-form-urlencoded",
  body: {
    mode: "urlencoded",
    urlencoded: [
      { key: "grant_type", value: "client_credentials" },
      { key: "client_id", value: pm.environment.get("clientId") },
      { key: "client_secret", value: pm.environment.get("clientSecret") },
      { key: "scope", value: "read write" }
    ]
  }
};
 
// Send the token request
pm.sendRequest(tokenRequest, (err, response) => {
  if (err) {
    console.error("Error fetching token:", err);
    throw new Error("Failed to retrieve OAuth token.");
  } else {
    // Save the access token to the environment
    const accessToken = response.json().access_token;
    pm.environment.set("accessToken", accessToken);
    console.log("Token saved:", accessToken);
  }
});

4.2 Handle Token Expiry (Advanced)#

To avoid using expired tokens, check if accessToken is still valid before fetching a new one. Extend the pre-request script to:

  1. Track when the token was saved (tokenExpiryTime).
  2. Only fetch a new token if it’s expired.

Add this to your pre-request script:

// Get current time and token expiry time from environment
const currentTime = new Date().getTime() / 1000; // Convert to seconds
const tokenExpiryTime = pm.environment.get("tokenExpiryTime");
 
// If token is missing or expired, fetch a new one
if (!tokenExpiryTime || currentTime >= tokenExpiryTime) {
  console.log("Token missing or expired. Fetching new token...");
  // (Insert token request logic from Option A or B here)
} else {
  console.log("Using existing valid token.");
}

Update the token request’s Tests tab to save the expiry time:

const responseJson = pm.response.json();
pm.environment.set("accessToken", responseJson.access_token);
 
// Calculate expiry time (current time + expires_in seconds)
const expiryTime = Math.floor(Date.now() / 1000) + responseJson.expires_in;
pm.environment.set("tokenExpiryTime", expiryTime); // Save expiry time

Step 5: Test the Automated Flow#

Now, run the main request and verify the automation works:

5.1 Run the Main Request#

  • Select your environment (top-right) → Click “Send” on the main request.

5.2 Verify the Flow#

Check the Postman Console (View → Show Postman Console) to debug:

  • The pre-request script logs “Fetching new token...” (or “Using existing token”).
  • The token request runs and logs the response.
  • The main request uses {{accessToken}} and runs successfully (status 200 OK).

5.3 Troubleshoot Failed Requests#

If the main request returns a 401 Unauthorized error:

  • Check the Postman Console for token request errors (e.g., invalid credentials).
  • Verify accessToken is set in the environment (eye icon → environment variables).
  • Ensure the token request’s Tests tab correctly extracts access_token.

Troubleshooting Common Issues#

IssueSolution
Token request returns 400 Bad RequestCheck the grant_type, client_id, and client_secret in the token request body. Ensure the token URL is correct.
accessToken is undefinedIn the token request’s Tests tab, verify pm.response.json().access_token matches the JSON path in the token response (e.g., some APIs use accessToken instead of access_token).
Environment variables not loadingEnsure the correct environment is selected (top-right dropdown).
Pre-request script errorsUse console.log() in scripts to debug variables (e.g., console.log(pm.environment.get("clientId"))).
Token expires too quicklyExtend the expiry time logic (Step 4.2) to fetch a new token before it expires.

Best Practices#

1. Secure Sensitive Data#

Store client_id, client_secret, and accessToken in environment variables (never hard-code them in scripts). Use Postman’s “Secret” variable type (click the lock icon) to mask values.

2. Version Control Collections#

Export your Postman Collection (File → Export) and store it in Git for team collaboration.

3. Handle Edge Cases#

  • Add error handling in pre-request scripts (e.g., try/catch blocks) to fail gracefully.
  • For Password Flow, add username and password as environment variables (use with caution—avoid storing user passwords in plaintext).

4. Document the Workflow#

Add comments to scripts and a README in your collection to explain the automation to team members.

Conclusion#

By automating OAuth token retrieval with Postman pre-request scripts, you eliminate manual steps, reduce errors, and streamline API testing. This workflow works for any authentication method requiring pre-request setup (e.g., API key rotation, JWT generation). With environment variables and pm.sendRequest, you can extend this to complex scenarios like token expiry handling or multi-step authentication flows.

References#