richard
richard

Reputation: 2053

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

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);
});

Upvotes: 55

Views: 79227

Answers (4)

Mushroomator
Mushroomator

Reputation: 9178

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

Upvotes: 16

Andrew Plank
Andrew Plank

Reputation: 1009

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.

Upvotes: 2

Gino Mempin
Gino Mempin

Reputation: 29600

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:

Upvotes: 94

Chatar Singh
Chatar Singh

Reputation: 1063

Try this.

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

Upvotes: 48

Related Questions