Postman is a popular tool for developing, testing, and debugging APIs. It includes a feature called Pre-request Scripts, which allows you to run JavaScript code before sending an API request.
You can use pre-request scripts to generate authentication tokens, set request headers, create dynamic values, update request data, and automate tasks that would otherwise need to be performed manually.
In this guide, we’ll explain what a pre-request script is, how to add one in Postman, and how to use it to retrieve an authentication token before sending an API request. We’ll also look at a separate PHP cURL example for making an authenticated API request.
1. What Is a Pre-Request Script in Postman?
A pre-request script is a piece of JavaScript code that Postman executes before sending the request. You can add the script to an individual request, a folder, or a collection, depending on where you want the logic to run.
For example, imagine that an API requires a Bearer token in the Authorization header. Instead of manually generating and copying a token every time, you can use a pre-request script to call an authentication endpoint and prepare the token before the main request is sent.
Pre-request scripts are useful for tasks such as:
- Generating or retrieving authentication tokens.
- Adding or updating request headers.
- Creating dynamic timestamps and unique values.
- Setting environment or collection variables.
- Preparing request payloads.
- Performing setup requests before the main API request.
2. How to Add a Pre-Request Script in Postman
Follow these steps to add a pre-request script to a Postman request:
- Open Postman and select the API request you want to configure.
- Choose the Scripts tab.
- Select Pre-request.
- Enter your JavaScript code in the script editor.
- Save the request and send it.
Postman runs the pre-request script before sending the main request. You can also add scripts at the collection or folder level when you want to reuse the same setup logic across multiple requests.
3. Example: Get an Authentication Token Before Sending an API Request
Let’s look at a common example. Suppose an API provides an authentication endpoint that accepts a username and password and returns an access token.
You can use pm.sendRequest() to call the authentication endpoint from your pre-request script. After receiving the response, you can save the token in an environment variable and add it to the current request’s Authorization header.
Add the following JavaScript to the Pre-request Script editor:
pm.sendRequest({
url: 'https://api.example.com/auth',
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: {
mode: 'raw',
raw: JSON.stringify({
username: pm.environment.get('api_username'),
password: pm.environment.get('api_password')
})
}
}, function (err, response) {
if (err) {
console.error('Authentication request failed:', err);
throw new Error('Unable to retrieve API token.');
}
if (response.code < 200 || response.code >= 300) {
throw new Error(
'Authentication failed. HTTP status: ' + response.code
);
}
var responseData = response.json();
if (!responseData.token) {
throw new Error('The authentication response did not contain a token.');
}
// Save the token in the current environment.
pm.environment.set('access_token', responseData.token);
// Add the token to the request header.
pm.request.headers.upsert({
key: 'Authorization',
value: 'Bearer ' + responseData.token
});
});
Replace the example authentication URL and response property with the details provided by your API. This example assumes that the authentication response contains a property named token.
Before running the request, create these variables in your Postman environment:
api_username— your API username.api_password— your API password.access_token— the variable that will store the returned token.
Keep credentials in protected or sensitive environment variables where supported. Avoid hardcoding passwords or tokens in scripts that may be shared with other people.
When the authentication request succeeds, the script stores the token and adds the Bearer token to the current request. Make sure your API’s actual response structure and authentication requirements match the example.
4. Use the Token in Your API Request
After retrieving the token, you can use it to authenticate the main API request.
The Authorization header should have this format:
Authorization: Bearer YOUR_ACCESS_TOKEN
If you prefer to configure the header directly in Postman’s Headers tab, you can use the environment variable:
Key: Authorization
Value: Bearer {
{
access_token
}
}
Choose one approach for adding the Authorization header. If your pre-request script already uses pm.request.headers.upsert(), you do not need to add a duplicate header manually.
5. Retrieve and Display API Data Using PHP and cURL
Postman is useful for testing API requests, but you may also want to make the same type of request from a PHP application.
You can use PHP cURL to send an authenticated GET request to an API endpoint. The following example assumes that you already have a valid access token from your API provider.
<?php
$api_endpoint = 'https://api.example.com/data';
// Load the token from a secure server-side configuration.
$access_token = 'YOUR_ACCESS_TOKEN';
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $api_endpoint,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json',
'Authorization: Bearer ' . $access_token,
),
CURLOPT_TIMEOUT => 30,
)
);
$response = curl_exec( $ch );
if ( $response === false ) {
$error = curl_error( $ch );
curl_close( $ch );
exit( 'cURL Error: ' . $error );
}
$status_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
if ( $status_code < 200 || $status_code >= 300 ) {
exit( 'API request failed. HTTP status: ' . $status_code );
}
$data = json_decode( $response, true );
if ( json_last_error() !== JSON_ERROR_NONE ) {
exit( 'Invalid JSON response: ' . json_last_error_msg() );
}
// Display the returned data safely.
echo '<pre>';
echo htmlspecialchars(
print_r( $data, true ),
ENT_QUOTES,
'UTF-8'
);
echo '</pre>';
?>
Replace the sample endpoint and access token with the values provided by your API. In a production application, load the token from secure server-side storage rather than placing it directly in the PHP source code.
Important: A token stored in Postman’s environment is available to Postman, not automatically to your PHP application. Your PHP application must obtain its own token through the API’s authentication process or retrieve it from a secure server-side token store.
6. Important Things to Remember
- Use the correct script location: Add code to the Pre-request section when it needs to run before a request is sent.
- Check API responses: Handle authentication failures, missing tokens, and unsuccessful HTTP status codes.
- Protect credentials: Do not share passwords, client secrets, or access tokens in exported collections or public repositories.
- Use environment variables: Store values that change between development, testing, and production environments separately.
- Match the API format: Update the authentication URL, request body, and token response property to match your API.
- Keep PHP separate: Postman scripts run inside Postman. PHP cURL requests run independently on your server.
Conclusion
Pre-request scripts in Postman allow you to automate tasks before sending API requests. You can use JavaScript to retrieve authentication tokens, update headers, generate dynamic values, and prepare request data.
By combining pre-request scripts with environment variables, you can make API testing more efficient and reduce repetitive manual work. When you need to perform similar API operations from a website or application, PHP cURL provides a separate way to send authenticated requests from your server.