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.