I am sending raw POST request with application/json data to server in Postman. I need to work with this JSON object and append some data in pre-request script. However I can only find how to access environmental variables, not request body. Anybody knows, please? Thanks!
"I can only find how to access environmental variables, not request body"
You can access request body in Pre-request Script via pm.request.body.
Unfortunately, you cannot change it through script (at least not supported in Jul. 2018). Please check this thread for some previous discussion.
However, there is a workaround: you can make the whole request body use environment variable, such as {{reqBody}}, and edit that variable in Pre-request Script panel. For example:
var defaultReqBody = {
a: 42
};
//Edit defaultReqBody ...
pm.environment.set("reqBody", JSON.stringify(defaultReqBody));
Related
I want to chain some requests in order to always have an up to date variable containing a JWT for access.
Now i am new to scripting in Postman, i figured this can be done in pre-request scripts. There i can access (global / environment) variables, but i wonder can i also access a saved request from a collection in a script?
The saved request has body and header set, partially with environment vars.
Environment and collection variables can be accessed like this, i know:
pm.environment.get('some_var')
pm.collectionVariables.get('name')
This is the snippet provided by Postman
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
Is there a way so i can do something like
pm.collection.url.get('obtain_jwt')
if i have a request called 'obtain_jwt' in a collection?
Or do i have to store the URL as a variable as well and again fill body and header in the script? (which i want to avoid)
I don't think it's supported in Postman the way that you're thinking, it's a feature that's been an ask for a long time:
https://github.com/postmanlabs/postman-app-support/issues/4193
You'll need to fully construct the request in the pre-request script or you might be able to leverage setNextRequest
I have a login request that returns a token that gets saved to environment variables via the following script added in Postman - Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token_abc", jsonData.access_token);
Another request uses that token in the Authorization header as Bearer {{token_abc}}.
But, it seems the token is valid only for one-time use: after request #2 is sent, the value of token_abc is reset to null in Environment variables - Current value.
What could be causing this? Because this is not how the application usually behaves - the token should be valid for 24 hours. Is there a Postman setting I'm not seeing somewhere? I'm using Postman 8.6.1.
For some reason unknown to me there are 2 "postman" object in the postman sandbox that you can use to set environment variables.
postman
pm
Both can call a function for setting variables on the variable scopes in postman. From what I gathered on forums discussing various postman problems, the usage of the postman object gets discouraged in favor of pm.
See if this helps:
//check if you get the value you expected first
console.log(jsonData.access_token)
pm.environment.set('token_abc', jsonData.access_token)
Since your variable gets reset somewhere, there must be code in your script responsible for that. You mention the variable gets reset after request #2, so the first place to look is in the "Tests" tab of your second request. You can use console.log(value) to output the value of that variable to console on various places in that script in order to further pinpoint the exact location in code where it gets reset.
I need to restrict some of the HTTP Methods like PUT, POST and DELETE for my one of the environment. Is it possible in POSTMAN ?
This will help me in avoiding mistakes of doing POST,PUT or DELETE on my one of the environment.
You could add a variable to the Method dropdown - Add {{METHOD}} to the field and than add the same variable name in your environment file with the value you want?
You could also just delete the Methods you don't want to use from the dropdown, these can just be added in after, if you need it again.
https://learning.postman.com/docs/postman/customizing-postman/#customizing-request-methods
Postman does not provide any in-built functionality like this. However, you can use pre-request scripts for this. Write this in your pre-request script of the API you want to limit certain request methods-
var request = pm.request;
if(request.method.includes("POST") || request.method.includes("PUT")){
console.error("Inavlid request method");
throw new Error("Invalid request method");
}
The drawback of this approach is that you need to copy-paste this in every API's pre-request script. If you want to bypass that, you can cache this entire code into a postman variable and just eval that variable in every API. Steps-
Create an environment variable in your postman with this name as "my-script" and value as-
() => { var request = pm.request;
if(request.method.includes("POST") || request.method.includes("PUT")){
console.error("Inavlid request method"); throw new
Error("Invalid request method"); }}
Now just copy and paste this line in every pre-request script in your collection-
eval(pm.environment.get('my-script'))();
I need to be able to delete cookies automatically in between requests when they I run my collection of requests in Newman and Postman Runner (mainly Newman).
I followed the suggestion given in this comment by a person from Postman: https://github.com/postmanlabs/postman-app-support/issues/3312#issuecomment-516965288.
But it is not working.
The answer to these two SO questions also tell the same way to go about doing this: Postman: How do you delete cookies in the pre-request script?
Deleting cookies in postman programmatically
Here is the code that I use that the sources above suggest to place in the pre-request script:
const jar = pm.cookies.jar();
jar.clear(pm.request.url, function (error) {
console.log("Error: ");
console.log(error);
//handle error
});
[Note: error is logged as null when I run this code]
I have tried this code many times and also many different modifications of that code. I do white-list the domain too. But I always get the wrong response in the request. When I clear the cookies manually (using the cookie Manager UI dialogue box), the request gives the right response. I need help in determining where the problem could be for me in deleting cookies programmatically.
I also tried this to see what the cookies that I am deleting are:
jar.getAll(pm.request.url, function (error, cookies) {
console.log("Cookies:");
console.log(cookies);
console.log("Error: ");
console.log(error);
});
Here cookies is an empty array. Perhaps that is the problem. But that is very weird since when I check Cookie Manager manually, there are many cookies shown. And once I delete the cookies manually the requests return the right responses.
Another question I had was: What is the purpose of the callback functions that take 'cookies' and 'error' as arguments in the code above. Are these functions called everytime or only under certain conditions? Could not find the purpose of the callback functions in the postman documentation: https://learning.postman.com/docs/postman/sending-api-requests/cookies/
Thank you
If the cookie has "httpOnly" or "secure" header, you can't delete them via script in postman. jar.clear clears all the cookies except these httpOnly and secure ones.
I think this is a bug and needs to be fixed by Postman. If this is intended, there should be a setting in Postman to activate or disable it.
Problem is that I'm trying to change the settings of the website with POST and would like to confirm that the settings changed with a new GET request after the change, but as I'm running the collection it's just running the tests but not the POST itself, POST does not have any response so there's nothing to check there.
I hope that I was clear enough explaining my problem.
Thanks Guys!
If I'm understanding this correctly:
You have two requests and want to run the GET immediately after the POST. This can simply be done by using environment variables and SetNextRequest.
Be careful of entering an infinite loop because Collections run top down; if your GET request was before the POST request. It may be better to duplicate your GET request and place it below the POST.
A Post to {{base_url}}/website
Within the Pre-request Script set your new settings to your environment
pm.environment.set("setting1", "newValue");
Within the Body if your sending raw json for example use that variable
{
"setting1": "{{setting1}}"
}
Postman still runs the Test section you don't need a pm.test it's essentially a Post-request Script. Tell Postman to run the GET request next:
postman.setNextRequest("Get Website Settings");
From your Get request within Tests section validate the setting is correct
pm.test("Setting has been updated to" + {setting1}, function() {
var actualSetting = pm.response.json().setting1;
pm.expect(actualSetting).is.eql({setting1});
});