I need to hash my credentials to get access to api like this sha2(app-secret:SALT:timestamp)
I set this in the header as authtoken which should have this hashed value auth-token: api.hashify.net/hash/sha256/{{appSecret}}:{{SALT}}:{{timestamp}}
Can you please advise if the usage is correct I mean if adding thisapi.hashify.net/hash/sha256/ in front of the keys will get me what I need
it will be send just as a string it won't call to that endpoint , so instead call that endpoint in pre- request script, and store response value to a variable and use it in auth header :
// Example with a plain string URL
pm.sendRequest(`https://api.hashify.net/hash/sha256/${pm.environment.get('appSecret')}:${pm.environment.get('SALT')}:${pm.environment.get('timestamp')}`, (error, response) => {
if (error) {
console.log(error);
} else {
console.log(response.json()); // or response.text() if parse error
}
});
inside else statement write logic to get the value and use pm.environment.set("auth-token",value)
now in header auth-token:{{auth-token}}
Related
I need to make requests to an API that accepts authentication tokens and I want to be able to use a dynamically generated token by running cmd.exe /c GenerateToken.bat instead of having to run my program and then manually paste the value in Postman every time.
I imagine something that looks like this:
How can I set the value of a HTTP header to contain the stdout output of a program or a batch file?
Short answer is, you can't. This is deliberate, both pre-request and test scripts (the only way, other than a collection runner, to make your environment dynamic) run in the postman sandbox, which has limited functionality.
More information of what is available is in the postman-sandbox Github repository page and in postman docs (scroll to the bottom to see what libraries you can import)
You do have a few options, as described in comments - postman allows sending requests and parsing the response in scripts, so you can automate this way. You do need a server to handle the requests and execute your script (simplest option is probably a small server suporting CGI - I won't detail it here as I feel it's too big of a scope for this answer. Other options are also available, such as a small PHP or Node server)
Once you do have a server, the pre-request script is very simple:
const requestOptions = {
url: `your_server_endpoint`,
method: 'GET'
}
pm.sendRequest(requestOptions, function (err, res) {
if (err) {
throw new Error(err);
} else if (res.code != 200) {
throw new Error(`Non-200 response when fetching token: ${res.code} ${res.status}`);
} else {
var token = res.text();
pm.environment.set("my_token", token);
}
});
You can then set the header as {{my_token}} in the "Headers" tab, and it will be updated once the script runs.
You can do something similar to this from Pre-request Scripts at the collection level.
This is available in postman for 9 different authorization and authentication methods.
this is a sample code taken from this article, that show how to do this in Pre-request Scripts for OAuth2
// Refresh the OAuth token if necessary
var tokenDate = new Date(2010,1,1);
var tokenTimestamp = pm.environment.get("OAuth_Timestamp");
if(tokenTimestamp){
tokenDate = Date.parse(tokenTimestamp);
}
var expiresInTime = pm.environment.get("ExpiresInTime");
if(!expiresInTime){
expiresInTime = 300000; // Set default expiration time to 5 minutes
}
if((new Date() - tokenDate) >= expiresInTime)
{
pm.sendRequest({
url: pm.variables.get("Auth_Url"),
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': pm.variables.get("Basic_Auth")
}
}, function (err, res) {
pm.environment.set("OAuth_Token", res.json().access_token);
pm.environment.set("OAuth_Timestamp", new Date());
// Set the ExpiresInTime variable to the time given in the response if it exists
if(res.json().expires_in){
expiresInTime = res.json().expires_in * 1000;
}
pm.environment.set("ExpiresInTime", expiresInTime);
});
}
Let's say my API call URL is www.example.com/quiz with POST method.
And I get the response body like this. And
var jsonData = pm.response.json();
pm.collectionVariables.set("cv_quiz_order", quiz_order)
if(!jsonData.is_end){
// TODO: request next question using `quiz_order`
}else{
// TODO: finish this API and go to the next request.
}
When I use Run Collection. I want it(the Apis) tests one by one in regular sequence. And only this Api repeats until its is_end is true.
How can I do this?
var jsonData = pm.response.json();
pm.collectionVariables.set("cv_quiz_order", quiz_order)
if(!jsonData.is_end){
postman.setNextRequest(pm.info.requestName)
}else{
// TODO: finish this API and go to the next request.
}
this will keep sending the same request until is_end is true
postman.setNextRequest allows you to set the next reqeust to be executed , pm.info.requestName gives thecurrent request Name , so you are saying run this request as next request
I have a GET request to OKTA to retrieve some information that uses some variables etc. It returns a body. I have a second request of type PUT where I manually paste the BODY and make a change to one variable. I am trying to determine if I can remove the manual process of pasting in the response body from the 1st GET request onto the second PUT request.
As an example, I have a URL:
GET https://{{myurl}}/api/v1/apps/{{instanceid}}
This returns some dyanmic JSON data in the payload like so
"blah":{ some more blah
},
"signOn": {
"defaultRelayState": null,
"ssoAcsUrlOverride": ""
"audienceOverride": null,
"recipientOverride": null
}
what I am hoping to do is:
PUT https://{{myurl}}/api/v1/apps/{{instanceid}}
{replay entire body from 1st request with the modification of
"ssoAcsUrlOverride": "{{some var that points to a new url}},
}
I have looked at some articles that show:
Using Tests to send a GET request with a static body and replaying that exact body. In this case, I am looking to modify a parameter not replay as=is
I tried this thread here (In postman, how do I take a response body and use it in a new request within Tests
postman-how-do-i-take-a-response-body-and-use-it-in-a-new-request-within-tes) but I get an error stating that responseBody is not defined
First of all, let's validate the JSON response first. Here is the valid JSON with some dummy data.
{
"blah": "some more blah",
"signOn": {
"defaultRelayState": "1",
"ssoAcsUrlOverride": "www.google.com",
"audienceOverride": "true",
"recipientOverride": "yes"
}
}
1) Save first request's response into a environment variable req_body as follows,
var jsonData = pm.response.json();
pm.environment.set("req_body", jsonData);
2) In the PUT request, take another environment variable replace_this_body in body.
3) Get the value of E'variable req_body we had set in the first request in Pre-request script. Then change the value of it and set current request's body variable.
var requestBody = pm.environment.get("req_body");
requestBody.signOn.ssoAcsUrlOverride = "https://www.getpostman.com";
pm.environment.set("replace_this_body", JSON.stringify(requestBody));
Finally, you will get updated request data into PUT request!
I have a get request with Tests script as below
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("var1", jsonData.var1);
postman.setEnvironmentVariable("var2", jsonData.var2);
However response for the request may or may not include all values eg.
response1
{
"var1": "value1",
"var2": "value2"
}
response2
{
"var2": "value2"
}
I use above data in next Put request. Body of the Put request is like below
{
"var1": "{{var1}}",
"var2": "{{var2}}"
}
The issue I am facing is if previous Get request did not have a value for a property (as in response2) then {{var1}} (i.e. variable name) is getting stored in the database (mysql). I tried removing double quotes around variable in the Put request but that gives me
invalid character '{' looking for beginning of object key string "
error
Can you please suggest best solution for the situation.
Thanks
I'm having trouble storing the user's email address in a variable in javascript. What I want to do is call the API, get the email address, and store it in the "email" variable, for use in other functions on the screen.
My code looks like this:
function emailCheck(){
var email;
FB.api('/me',email = function(response){
return response.email;
})
}
alert(email);
I did check to make sure that I have the proper permissions. I would put alert(response.email) in my response section, and it would alert with the proper email. The problem is that I cant get the email variable accessible outside of the function.
You need to use a continuation as all API methods are asynchronous
function emailCheck(continuation){
FB.api('/me', function(response){
continuation(response && response.email);
});
}
emailCheck(function(email) {
alert(email);
}
A different way is to use Promises, Futures or deferreds (same thing really) to abstract pieces of this.