How to add authorization header in POSTMAN environment? - postman

I'm testing bunch of API calls using POSTMAN. Instead of adding authorization header to each request, can I make it as a part of POSTMAN environment? So, I don't have to pass it with every request.

Yes, you can do this through Postman by assigning your header as an environment variable, let's say authorization, as follow:
then set you environment variable with its value as follow:

In contemporary releases of Postman, you can just set your auth on the collection (or folder), and have every request inherit it (which I believe new requests do by default).

postman usually remembers your key-value pairs you send in header. So there is no need to add headers each request. Anyway you can configure a "Preset" with your auth token.

Not sure if this is what you're looking for, but we use a link-based API that requires auth headers on each request. If you go to Postman > Preferences > General and enable Retain headers when clicking on links, Postman will pass through your auth headers to the child links.
Hope that helps!

If you can't wait here is a work around I just made:
Export your collection (data format v2.1)
Open firefox , dev tools, scratch pad
Paste the code below
Replace the header information with your header
Replace the var a with your contents of the exported .json file
Run the script
The copy(b) command will put the new data with in your clipboard
In postman, click import > Paste Raw Text > Import > as a copy.
Verify your requests have your header, and run it :)
var myHeader = {
"key": "X-Client-DN",
"value": "{{Postman-DN}}",
"description": "The User's DN Interacting with the system."
};
function addHeader(obj, header) {
if (obj.hasOwnProperty('request')) {
obj.request.header.push(myHeader)
}
if (obj.hasOwnProperty('item')) {
obj.item.forEach(function(element) {
element = addHeader(element, header);
});
}
return obj;
}
var a = {
"item": [{}, {
"request": {
"header": []
}
}, {
"item": [{
"request": {
"header": []
}
}]
}]
}
var b = addHeader(a, myHeader);
console.log(JSON.stringify(b, null, 2))
// Might have to run copy manually on console
//copy(b);

Related

Postman: Set a request header from the output of a program

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);
});
}

API endpoint to save multipart-file by POST method through Postman

I am trying to mock the request to upload a zip file through 'POST' method using Wiremock. But I could not find the required property for that. Following is my mocked request which needs to be sent.
How can I save this file to the _file directory through POST request?
"request":
{
"url": "/order/uploadFile",
"method": "POST",
"headers": {
"token": {
"equalTo": "0000000"
},
"Content-Type":{
"equalTo": "multipart/form-data"
}
},
"bodyPatterns": [{
"equalToJson": "{\"sampleFile\":\"Sample_file.zip\"}"}]
} ....```
Here is the postman request. [![request-postman][1]][1]
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/CQaSj.png
In short: you can't save anything to the __files directory using the out-of-the-box standalone WireMock from withing a mapping rule. This functionality requires a custom extension that needs to do the saving for you.
That said, it is possible, according to this Stack Overflow answer to store a file in __files using a PUT on /__admin/files/[your desired filename]. This will then create a new file under the __files. It appears to be undocumented and as such may not feature in future versions. Sub-folders seem to go unsupported when I tried it.

Getting "Bad Request" for Postman API

I simply took an example from Postman API Documentation for Create Collection and removed the extra request outside the folder.
My intention is to create just a folder with 1 request in it.
Here is the request:
{
"collection":{
"variables":[
],
"info":{
"name":"Sample Collection",
"description":"This is just a sample collection.",
"schema":"https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
},
"item":[
{
"name":"This is a folder",
"description":"",
"item":[
{
"name":"Sample POST Request",
"request":{
"url":"echo.getpostman.com/post",
"method":"POST",
"header":[
{
"key":"Content-Type",
"value":"application/json",
"description":""
}
],
"body":{
"mode":"raw",
"raw": "{
\"data\": \"123\"
}"
},
"description":"This is a sample POST Request"
},
"response":[
]
}
]
}
]
}
}
But for this, I am getting "Bad Request" error, what exactly is wrong with my request?
EDIT - Here's what it looks like in Postman
To me, it looks like you’re trying to send the whole collection json file back to that route.
The JSON in the request body on the image is what you would import into Postman to get the Sample Collection folder. This contains a request called Sample POST Request
Copy the request body JSON and save it as a .json file - Then import this using the Import feature in the top left on the application.
This will then create the folder for you in the application with the sample POST request.
If you send it to the echo URL, you will receive a response telling you that the URL has now changed to https://postman-echo.com/post - Add this new URL into the address bar and hit Send.

Create unique body request in postman for API-test

I want to create test request on postman with unique email property in the request body.
{
...
"email": "{{email_string}}.com",
...
}
I've set email_string with static string in enviroment, but is there any way that I can set email_string dynamically before request occured?
You can use Postman's built in support for the Faker library direct in the request body:
{
...
"email": "{{$randomEmail}}",
...
}
or, in a pre-request script:
pm.environment.set('user-email', pm.variables.replaceIn('{{$randomEmail}}'));
As an alternative to the previous answer, you could use the sendRequest function to get the value from a 3rd party API that is designed to return randomised data.
This can be added to the Pre-Request Script tab:
pm.sendRequest("https://randomuser.me/api/", (err, res) => {
// Get the random value from the response and store it as a variable
var email = res.json().results[0].email
// Save the value as an environment variable to use in the body of the request
pm.environment.set("email_address", JSON.stringify(email))
})
You could potentially create lots of randomised data using this API but it is a 3rd party API so you won't have any control over this changing. If you only need this in the short term, i'm sure it will be fine.
Something also worth remembering is that Postman comes with Lodash built-in so that gives you the ability to use any of that modules functions, to reduce down some of the native JS code.
There is tab in postman application named "pre-request script" near to "Test" tab. You can use this tab to set your environment variables.
Here is the trick:
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
postman.setEnvironmentVariable('email_string', text + '#' + text);
I think this script could help you to set a random value in your environment.

Cannot change includeInGlobalAddressList using Directory API

I am trying to migrate a script from the Profiles API to the Directory API. Its purpose is to manage the visibility of certain Google Apps Domain users' contact information using the includeInGlobalAddressList attribute.
I can fetch the user objects, and am able to submit a patch request, but the change does not get made. The object returned from the patch method has the original value for includeInGlobalAddressList. There are some vague references to etags in the api documentation, but it's not clear to me if the etag is supposed to be included in the patch body or as an If-Match header. (if the answer to that is an If-Match header, then how am I supposed to pass that in using the python library?)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("admin", "directory_v1", http=http)
usersvc=service.users()
d=usersvc.get(userKey=userkey, projection="basic",fields="etag,id,includeInGlobalAddressList").execute()
visible = d['includeInGlobalAddressList']
# logic to decide what change elided. this is "transition from visible to invisible contact"
pch=json.dumps({'includeInGlobalAddressList': False, 'etag': d['etag']})
print pch
res=usersvc.patch(userKey=userkey, body=pch, fields="etag,id,includeInGlobalAddressList").execute()
print json.dumps(res, indent=4)
The result I get is:
{"includeInGlobalAddressList": false, "etag": "\"WIg4sZOp0a-9Z5MJXVMQx1SQW5A/avXX6NaPX78Y6qFG7S4TqKFMIEU\""}
{
"includeInGlobalAddressList": true,
"etag": "\"WIg4sZOp0a-9Z5MJXVMQx1SQW5A/J0MuBtIvJoTcifknCMScMlyCQnc\"",
"id": "109793672165131484748"
}
This happens even if I do not use fields or pass the etag.
There's no need to do a GET before the PATCH request. The idea of PATCH is that only changed data is sent across the wire. Try:
service = build("admin", "directory_v1", http=http)
usersvc = service.users()
res = usersvc.patch(userKey=userkey, body={"includeInGlobalAddressList": False}, fields="id,includeInGlobalAddressList").execute()
print res