I'm programmatically creating Postman collections and want to provide a default JSON request body to make requests easier.
I've looked through the spec can can't see how to specify it. Does anyone have any ideas? Could this be done with JavaScript, which I've used to automatically set headers and environment variables.
Here's the Postman Collection spec definition I'm working with, v2.1.0 draft 4:
A request is specified by #/definitions/request
.
The body
is specified as one of the following. JSON isn't listed so raw
is typically used. Here's an excerpt which appears shows that raw
is a string
type but there's no property to include a default value for the request body.
{
"body":{
"oneOf":[
{
"type":"object",
"description":"This field contains the data usually contained in the request body.",
"properties":{
"mode":{
"description":"Postman stores the type of data associated with this request in this field.",
"enum":[
"raw",
"urlencoded",
"formdata",
"file",
"graphql"
]
},
"raw":{
"type":"string"
}
}
}
]
}
}
Is anyone aware of Postman being able to specify an example for the JSON request body with a pre-created example, using the collection directly or via JavaScript?
The following YouTube video shows on the body can be set dynamically with JavaScript using the following.
const body = {
"productId": 1234
};
pm.globals.set("body", JSON.Stringify(body));
https://www.youtube.com/watch?v=hSX7Dcjy000
Using this approach, it seems the next thing to figure out is if the Postman Collection can import and access custom properties, e.g. x-properties
, or if there's some other way to load the example content by overloading an existing property. It seems this can be done by loading a lot of environment variables, one for each request. The final step may be to be to automatically load the correct environment variable value into the example body when the user first brings up the endpoint.
Here's more information on a similar topic:
The link you added is scripting withing postman test and pre request section , not for programmatically creating json.
You can open postman and click the inverted hamburger menu of collection to export the collection json. You can use this as reference.
In the generated json request is defined as : (Only url , method and body part not full )
"method": "DELETE",
"header": [],
"body": {
"mode": "raw",
"raw": "{{requestbody}}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{url}}/resource1/resource2",
"host": [
"{{url}}"
],
"path": [
"resource1",
"resource2"
]
}
This is the json created from postman.