Sending requests from scripts
Send other requests from a script and use their responses.
Overview
Sometimes a request needs something from another endpoint first, such as a fresh token, a CSRF value or the ID of a record to work on. relay.sendRequest, also available as pm.sendRequest, sends another request from a script and gives you its response, which has the same methods as relay.response.
Requests a script sends don't appear in history, and they're sent exactly as the script describes them.
Send a request and wait for the response
Pass a URL, or an object that describes the request, and await the result:
const response = await relay.sendRequest("https://api.example.com/status");
console.log(response.code, response.json().status);Because each script runs inside an async function, you can use await anywhere in it. The script, and the request it belongs to, waits until the response arrives.
If you prefer callbacks, as in many Postman scripts, pass a function as the second argument. It receives an error and the response:
relay.sendRequest("https://api.example.com/status", (error, response) => {
if (error) {
console.error(error.message);
return;
}
console.log(response.code);
});Relay waits for the callback too, even though the script doesn't await anything.
Describe the request
For anything other than a GET, pass an object with the URL, the method, the headers and the body:
const response = await relay.sendRequest({
url: "https://api.example.com/orders",
method: "POST",
header: {
"Content-Type": "application/json",
Authorization: relay.variables.replaceIn("Bearer {{token}}")
},
body: {
mode: "raw",
raw: JSON.stringify({ sku: "TEA-001", quantity: 2 })
}
});
relay.environment.set("orderId", response.json().id);The body's mode decides its kind:
- raw: Text in
raw. With aContent-Type: application/jsonheader, oroptions: { raw: { language: "json" } }, it's sent as JSON. - urlencoded: Form fields in
urlencoded, as a list of{ key, value }objects. - formdata: Multipart form fields in
formdata, as a list of{ key, value }objects. - graphql: A GraphQL operation in
graphql, with itsqueryand optionalvariablesandoperationName.
For example, to get a token with the OAuth 2.0 client credentials grant:
const response = await relay.sendRequest({
url: relay.variables.replaceIn("{{authUrl}}/oauth/token"),
method: "POST",
body: {
mode: "urlencoded",
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
{ key: "client_id", value: relay.environment.get("clientId") },
{ key: "client_secret", value: relay.environment.get("clientSecret") }
]
}
});
relay.environment.set("token", response.json().access_token);For every property a request can have, see relay.sendRequest.
Add variables and authentication yourself
Relay sends a script's request as written. It doesn't replace {{name}} tokens in it, and it doesn't apply the authentication of the request, its collection or its workspace. To use variables, expand them with relay.variables.replaceIn(); to authenticate, add the header yourself, as the examples above do.
The request does use the settings of the request whose script sent it, such as its timeout, redirects, proxy and certificates. Unless cookies are turned off for the workspace, it sends the cookies in the workspace's cookie jar, and cookies its response sets are added to the jar.
Handle failures
The error argument is set, or the promise rejects, only when there's no response at all, such as when the host can't be found or the request times out. A response with a status such as 401 or 500 is still a response, so check its code:
try {
const response = await relay.sendRequest(relay.variables.replaceIn("{{baseUrl}}/me"));
if (response.code !== 200) {
console.warn("Profile request returned", response.code);
}
} catch (error) {
console.error("Couldn't reach the server:", error.message);
}An error you don't catch in a pre-request script stops the send, as any other script error does.
Keep scripts within their limits
A script can send up to 50 requests in each phase. The time they take counts toward the Script Timeout in Relay > Settings > Requests, which is 30 seconds by default, so a slow endpoint can make a script run out of time. To send several requests at once rather than one after another, start them together and wait for all of them:
const [user, settings] = await Promise.all([
relay.sendRequest(relay.variables.replaceIn("{{baseUrl}}/me")),
relay.sendRequest(relay.variables.replaceIn("{{baseUrl}}/me/settings"))
]);See Also
- relay.sendRequest: A function that sends another request from a script and passes back its response.
- Reading and writing variables in scripts: Read variables and set new values from pre-request and post-response scripts.
- Running scripts before and after requests: Add pre-request and post-response scripts to requests, folders and collections.
- Managing cookies: View, add and edit the cookies a workspace sends and receives.