Reputation: 40
I just started learning about API an hour ago and wanted input on a little POST I wrote. My understanding of how all of this works is very wrong. More than anything, I would like to know how to pass a variable from script to the API request.
The body:
{
"bot_id" : "abc123",
"text" : words
}
And the pre-request script in javascript:
var num = Math.floor((Math.random() * 3) + 1);
switch(num)
{
case 1:
words = "Hello world!";
break;
case 2:
words = "Greetings Earthlings.";
break;
case 3:
words = "Goodbye cruel world!";
break;
}
This is the response I get when it fails (400 Bad Request):
{
"meta": {
"code": 400,
"errors": [
"Invalid bot_id"
]
},
"response": null
}
Upvotes: 0
Views: 1130
Reputation: 5220
The Response "errors": ["Invalid bot_id"]
tells you that the bot_id
(abc123
) is wrong. May be there is some validation on the backend?
Inside the pre-request script you have access to the postman
object. This object has the methods setGlobalVariable
, getGlobalVariable
, setEnvironmentVariable
and getEnvironmentVariable
.
Now with this methods you can read/write variables. In your case you want to use postman.setGlobalVariable('words', words)
. Inside the body you can use the variables by using curly braces {{variable}}
var num = Math.floor((Math.random() * 3) + 1);
var words = "";
switch(num) {
case 1:
words = "Hello world!";
break;
case 2:
words = "Greetings Earthlings.";
break;
case 3:
words = "Goodbye cruel world!";
break;
}
postman.setGlobalVariable('words', words)
{
"bot_id" : "abc123",
"text" : "{{words}}"
}
Upvotes: 1