Postman: set Environment Variable - rest

I have a POST call in Postman that returns this JSON object:
{
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiO3Jsb3Blei5hbnRvbmlvODVAZ21haWwuY29tIiwiZXhwIjoxNTkzNjc0MzUxLCJpYXQiOjE1MzMxOTQzNTF9.oTPVkcgF1QcoOsg6KDGOaaTyCQYrWS51QDdRn__MDigivcsuaqUgBhDaTYwQnxOtOCjxDRXO_cqK8i5xBq02bQ"
}
In my environment I set a variable named token
I want to set the value. I've tried with
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.message.token);
and
var data = pm.response.json();
pm.environment.set("token", data.message.token);
but both with errors: SyntaxError | Invalid or unexpected token

If that's the only thing you get back in the response body, why are you adding 'message'?
Use data.token or just use pm.response.json().token and remove the variable declaration.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("TOKEN",jsonData.token);

In order to set the environment variable key use below
var response=pm.response.json();
pm.environment.set("tokenkey", response.token);

The environment variables were not working for me after a Postman update. In my case the problem was that my environment was not set on the top right (it was using the default, "No Environment"). 🤦‍♂️

Related

Axios - Sending a GET with & sign

I have a GET call (/getTag) that has a variable 'name'.
One of my users created on with a & sign. And unfortunately the GET call is now failing because it looks like this.
/getTag?name=IS&me-1234
Unfortunately my server interprets it like this because of the & sign:
{ id: 'IS', 'me-1234': '' }
Anyone experienced this before and have a way to solve it?
You should use encodeURIComponent on a variable name before passing it to axios.
You can use params key in axios
axios.get('/getTag', {params: {name: 'Is&me123'}})
You should request like:
axios.get('https://your-site.com/getTag', { params: { name: 'IS&me-1234' } });
instead of:
axios.get('https://your-site.com/getTag?name=IS&me-1234');

Iterative Post request in Postman

I need help for doing Post request repeatedly in Postman with different bodies. Example given below, where company name must be changed. It would be better to read company names from a document or may be from an array in script. Please advice how can I do it?
{
"d": "{{company}}"
}
I found somethin like that, but I am getting error: (There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'get' of undefined)
Pre-request Script:
if(!companies){
companies = ["111",
"222",
"333"];
}
var currentCompany = companies.shift();
pm.enviroment.set("company",currentCompany);
pm.enviroment.set("companies", companies);
Tests:
var companies = pm.enviroment.get("companies");
if(companies && companies.length > 0){
postman.setNextRequest("my url");
} else {
postman.setNextRequest(null);
}
There are multiple but small mistakes:
the set environment function is misspelled: please use pm.environment.set(right) instead of pm.enviroment.set(false)
you have to load the companies var from the environments before. Add var companies = JSON.parse(pm.environment.get("companies")); to the first line of your pre rquest script.
Please make sure that you are saving string values to the environment vars. Use JSON.stringify(myObject) e.g. pm.environment.set("company", JSON.stringify(currentCompany)); and analogue JSON.parse(myStringVar) for loading variables in var companies = JSON.parse(pm.enviroment.get("companies"));
(Maye also a problem) Please make sure, there is a enviroment chosen in Postman, postman-runner and newman. If there is no environment set, you can get errors:

Retrieving SendGrid Transactional Templates List

I have been trying to retrieve list of SendGrid transactional templates using API. I'm using correct API key and getting an empty array while there are about 5 transactional templates existing in my SendGrid account. Here is the response:
{
"templates": []
}
Any guesses what could be wrong?
Any guesses what could be wrong?
Yep, their documentation could be!
I also stuck with the problem and finally managed to solve it once I opened the devtools and saw how they request their own API from the UI. Long story short - one has to pass additional generations=dynamic query parameter. Here is the C# code I use:
var client = new SendGridClient("key");
var response = await client.RequestAsync(
SendGridClient.Method.GET,
urlPath: "/templates",
queryParams: "{\"generations\": \"dynamic\"}");
Using Api 7.3.0 PHP
require("../../sendgrid-php.php");
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
#Comma-delimited list specifying which generations of templates to return. Options are legacy, dynamic or legacy,dynamic
$query_params = json_decode('{"generations": "legacy,dynamic"}');
try {
#$response = $sg->client->templates()->get();
$response = $sg->client->templates()->get(null, $query_params);
echo $response->body();
exit;
} catch (Exception $e) {
echo '{"error":"Caught exception: '. $e->getMessage().'"}';
}
I had the same problem using the python wrapper provided by Sendgrid.
My code was similar to this:
response = SendGridAPIClient(<your api key>).client.templates.get({'generations': 'legacy,dynamic'})
This returned an empty array.
To fix you have to name the param or to pass None before the dict:
response = SendGridAPIClient(<your api key>).client.templates.get(None, {'generations': 'legacy,dynamic'})
or
response = SendGridAPIClient(<your api key>).client.templates.get(query_params={'generations': 'legacy,dynamic'})

Posting multiple images to tumblr using tumblr.js api

I am trying to creating a app which can send posts to tumblr using tumblr.js api.
I could send single image using the createPhotoPost method, but I have to send multiple image in a single post via this method.
From the documentation it says that createPhotoPost method has a "data" parameter which can be an array with "URL-encoded binary contents"
When ever I try to send something in the data Array it returns "[Error: form-data: Arrays are not supported.]".
Can someone please help to solve this issue and please explain what should we pass in the array (Really I am not getting what is URL-encoded binary contents)?
Thanks in advance
There is an error in tumblr.js
https://tumblr.github.io/tumblr.js/tumblr.js.html#line504
The documentation at https://www.tumblr.com/docs/en/api/v2#posting is correct.
Basically the issue is that its not supposed to be
data = [ one , two ] its litterally params['data[0]'] = one ; params['data[1]'] = two; (?A PHP Convention)
var request = require('request')// already a tumblr.js dependency
var currentRequest = request({
url:'https://api.tumblr.com/v2/blog/someblog.tumblr.com/post',
oauth:keys,
},function(err,response,body){
currentRequest//
debugger
cb()
})
var params = {
'type' :'photo',
'caption':'Click To Verify You Are A Robot',
}
var params_images = [
fs.createReadStream('image'),
fs.createReadStream('image')
]
// Sign it with the non-data parameters
currentRequest.form(params)
currentRequest.oauth(keys);
// Clear the side effects from form(param)
delete currentRequest.headers['content-type'];
delete currentRequest.body;
// And then add the full body
var form = currentRequest.form();
//###add params_images to params keys 'data[0]' 'data[1]' 'data[2]' ....
params_images.forEach(function(image,index){
params['data['+index+']']
})
for (var key in params) {
form.append(key, params[key]);
}
// Add the form header back
var form_headers = form.getHeaders()
for(var key in form_headers){
currentRequest[key] = form_headers[key]
}

Request Post in GAE Method Request Post in GAE

I wonder if there is a way to make a request for a form which was sent by post in a way more dynamic without having to be variable by setting the variable. I mean if I have a form with 10 fields instead of doing:
var1 = self.request ('text1')
[...]
var10 self.request = ('text10')
If there is any way that he has returned me a list where the list argument is the field name and the value of the argument is the field value, eg:
list = { 'text1': value_text1, [ ... ] }
Tanks.
I think you are talking about the get_all() function. For more details see this reference