How to set the request body via Postman's pre-request script?
Asked Answered
B

4

52

I use Postman 6.0 to send an HTTP request. To send a request, I use a pre-request script to get a token and put it into the environment so that it will be used in the succeeding requests.

The script below doesn't work because the body is not sent. Is there anything wrong with the script below?

const getTaxAccessToken={
  url: 'http://dev.xxx.com:4001/api/v1/portal/account/tax-login',
  method: "post",
  body: {
      'loginIdentity': 'admic',
      'password': 'abc123'
  },
  header: {
      'Content-Type': 'application/json'
  }
};
pm.sendRequest(getTaxAccessToken, function (err, response) {
  console.log("get accesstoken");
  console.log(response.access_Token);
  pm.environment.set("taxAccessToken", response.access_Token);
});
Burrussburry answered 6/6, 2018 at 8:21 Comment(0)
T
47

Try this.

  body: {
     mode: 'raw',
     raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
  }
Thistle answered 6/6, 2018 at 8:52 Comment(0)
S
89

If the request needs to be of type application/x-www-form-urlencoded:

const options = {
  url:  'http://some/url', 
  method: 'POST',
  header: {
    'Accept': '*/*',
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: {
    mode: 'urlencoded',
    urlencoded : [
      { key: 'loginIdentity', value: 'admic'},
      { key: 'password', value: 'abc123'},
    ]
  }
};

pm.sendRequest(options, function (err, res) {
  // Use the err and res 
  // ...
  pm.environment.set("my-token", res.json().access_token);
});

Postman Javascript API references:

Sylvester answered 8/4, 2021 at 6:15 Comment(4)
this is what I was looking for! thank you. I wasn't sure what the different modes are/were for the sendrequest.Peppergrass
Thanks this worked for me. Is there any reference where I can see all valid postman pre-request script example code or document ?Aquamarine
@Aquamarine There are no explicit examples, but I remember going through the Postman API docs for Request (postmanlabs.com/postman-collection/Request.html) and RequestBody (postmanlabs.com/postman-collection/RequestBody.html).Sylvester
@GinoMempin Thanks RequestBody is intuitive enough.Aquamarine
T
47

Try this.

  body: {
     mode: 'raw',
     raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
  }
Thistle answered 6/6, 2018 at 8:52 Comment(0)
S
16

For Postman >= v8.3.0

With Postman v8.3.0 the update() method was introduced which allows you to set the request body directly from the pre-request script.

For your use case you could simply use:

pm.request.body.update({
    mode: 'raw',
    raw: JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'})
});

or even shorter:

pm.request.body.update(JSON.stringify({'loginIdentity': 'admic', 'password': 'abc123'}));

Strings, form-data, urlencoded and other Content-Types

As the title is not specifically tailored to JSON request bodies I thought I'd add some examples for how to handle this for other data as many might find this page when searching on Google and run into this issue for other Content-Types.

Raw

raw in Postman expects a string and therefore you can transmit anything that can be expressed as a string e.g. plain text, HTML, XML, JSON etc. .

// plain text
pm.request.body.update(`Hello World!`);
// HTML
pm.request.body.update(`<html>...</html>`);
// XML
pm.request.body.update(`<?xml version="1.0" encoding="UTF-8"?>...`);
// JSON
pm.request.body.update(JSON.stringify({ key: `value` }));

URL-encoded

pm.request.body.update({
    mode: "urlencoded",
    urlencoded: [{
        key: "key",
        value: "value with spaces and special chars ?/ and umlaute öüä"
    }]
});

Form data

pm.request.body.update({
    mode: "formdata",
    formdata: [{
        key: "key",
        value: "value with spaces and special chars ?/ and umlaute öüä"
    }]
});

GraphQL

pm.request.body.update({
    mode: 'graphql',
    graphql: {
        query: `
            query {
                hero {
                    name
                    friends {
                        name
                    }
                }
            }`
    }
});

Example based on GraphQL Tutorial for Fields.

Files from local file system as form-data

pm.request.body.update({
    mode: "formdata",
    formdata: [
        {
            key: "file",  // does not need to be "file"
            type: "file", // MUST be "file"
            src: "/C:/Users/MyUser/Documents/myFile.zip"
        }
    ]
})

Please note: This will only work for files in your current working directory. Otherwise you will receive an error like this Form param 'file', file load error: PPERM: insecure file access outside working directory in the Postman console.

You can see where your working directory is when you go to Settings | General | Working Directory. There also is an option Allow reading files outside working directory which you can enable to read files from anywhere, but be aware that this can allow others to steal data from your computer e.g when you execute untrusted collections.

Postman settings for working directory

Syndetic answered 7/9, 2022 at 11:15 Comment(2)
this was so helpful! The urlencoded formatting was driving me crazy, and I couldn't find anything in the Postman docs around this. Thanks, friend!Desman
that's nice, thx man!Disrespectable
T
2

If you happen to be reading this, and you are looking for a solution to this problem when using MS Dynamics, then here's what I arrived at:

var token = pm.collectionVariables.get("oauth_token");
var expiredRaw = pm.collectionVariables.get("oauth_token_expires");
var fetchToken = (!token || !expiredRaw || (new Date(expiredRaw) < new Date()));
if (!fetchToken) {
    console.log("Not refreshing token");
    return;
}

pm.sendRequest({
      url:  "https://login.microsoftonline.com/common/oauth2/token",
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: {
        mode: 'urlencoded',
        urlencoded : [
            { key: 'grant_type', value: 'password'},
            { key: 'client_id', value: pm.environment.get("oauth_client_id")},
            { key: 'client_secret', value: pm.environment.get("oauth_client_secret")},
            { key: 'resource', value: pm.environment.get("oauth_resource")},
            { key: 'username', value: pm.environment.get("oauth_username")},
            { key: 'password', value: pm.environment.get("oauth_password")},
        ]
      }
  }, function (err, res) {
    pm.environment.set("oauth_token", res.json().access_token);
    var expires = new Date();
    var expiresIn = res.json().expires_in ? (+res.json().expires_in) - 10 : 300
    expires.setSeconds(expires.getSeconds() + expiresIn);
    console.log("Logging new expiry", expires);
    pm.collectionVariables.set("oauth_token_expires", expires.toISOString());
});

Just add oauth_token and oauth_token_expires collection variables, make sure you have your credentials in the oauth_* environment variables, paste this into your collection's Pre-request Scripts tab and this will work very nicely.

Tinge answered 1/5, 2023 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.