Postman giving 400 for pm.sendRequest - postman

When I am running below send request from Postman - Tests, getting 400 bad request.
Could anyone tell me where I am wrong in sending the request?
let loginRequest = {
url: new_url,
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization":autho
},
body: {
mode: 'raw',
raw:JSON.stringify({
"name":child_group,
"description":"Create Via RestAPI"
})}
};
// send request
pm.sendRequest(loginRequest, function (err, res) {
console.log(err ? err : res.text());
});
Error:
{ "message" : "Missing Authorization header."}

#Manish Katepallewar , this worked for me:
let loginRequest=
{
url:new_url,
method:'post',
header:
{
'Content-Type':'application/json',
'Authorization':autho
},
body:
{
mode:'raw',
raw:JSON.stringify(
{
'name':child_group,
'description':'Create Via RestAPI'
})
}
};
pm.sendRequest(loginRequest,function(err,res)
{
console.log(err?err:res.text());
});

Related

Postman pre-request script oder - does not run the requests in the order I expect

Total postman noob. I have a script (well I don't I am trying to) to do the drudge tasks of authentication and authorization which takes 2 requests:
console.log("START");
var authenticationToken;
// Identity token
var authenticationTokenRequest = {
url: 'xxxx',
method: 'POST',
timeout: 0,
header: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxx="
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "password"},
{key:"username", value: "xxxxx"},
{key:"password", value: "xxxx"},
]}
};
pm.sendRequest(authenticationTokenRequest, function (err, res) {
**console.log("01 send first request body");**
var responseJson = res.json();
console.log(responseJson);
pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
authenticationToken = responseJson['access_token'];
});
**console.log("Authentication token local var: " + authenticationToken);
console.log("Authorization token env var: " + pm.environment.get('ACCESS_TOKEN'));**
var authorizationTokenRequest = {
url: "xxxx",
method: "POST",
header: {
"Content-Type": "application/json",
"Authorization": "Bearer " + authenticationToken,
"Accept": "application/xxx+json"
},
body:{
tenantId: "xxx",
deviceId: "xxx"
}
}
pm.sendRequest(authorizationTokenRequest, function (err, res) {
**console.log("02 second request call");**
var responseJson = res.json();
pm.environment.set('ACCESS_TOKEN', responseJson['access_token']);
});
//
When I run this and look at the console, the console messages of the local vars show undefined. The console message for the second request shows in console before the first request. The second request depends on a value from the first.
What am I doing wrong? Thanks

AWS post request works on postman but not react-native

This is my JS code for the API
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user:user
}),
})
.then((res) => {
return res.json();
})
.catch((err) => {
console.log("Error in getUser: " + err);
});
return json;
};
Here is an attempt to make the request, which unfortunately return the authentication error.
fetchUser.request("kirolosM")
.then((result)=>{
console.log(result);
}).catch((err)=>{console.log("Error ",err);})
The error
{
"message": "Missing Authentication Token"
}
I have tested the API using postman and it is working as expexted.
Probably useful to compare the request sent from your json code to the one you're sending from postman. It looks like you need to include you auth token in your headers in your request.
Something like
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authentication": `Bearer ${token}`
},
...

sendRequest does not seem to use Headers values I specify in the Test

I'm using sendRequest function to send a 2nd request as part of the Test for my 1st request. But it seems that sendRequest does not use the Headers I specify in the function. Any ideas why and how to fix it?
Here is part of my Test, that sends 2nd request:
var runHost = pm.environment.get("MyHost");
var runToken = pm.environment.get("Token");
pm.sendRequest({
url: runHost,
method: 'PUT',
headers: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});
Here is what I see as an actual Request Headers sent (what I see in Console):
PUT https://some_url
Request Headers:
Content-Type:"text/plain"
User-Agent:"PostmanRuntime/7.15.2"
Accept:"*/*"
Cache-Control:"no-cache"
Postman-Token:"5e3543c-1ww0-dfc4-bert-92ba9a455667"
Host:"my_host"
Accept-Encoding:"gzip, deflate"
Content-Length:1876
Connection:"keep-alive"
I expect Request Headers to have the following attributes and values:
Authorization:"Auth current_token_value"
Accept:"application/json"
Content-Type:"application/json"
...
The key for the object that contains the Request Headers should be header, like in the example below:
pm.sendRequest({
url: runHost,
method: 'PUT',
*header*: {
"Authorization": "Auth "+runToken,
"Accept": "application/json",
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify(jsonData)
}
}, (err, res) => {
console.log(res);
});

Express Gateway: Not getting response body

I am not being able to get the response body that I need to store in the logs along with the request body. The only time I'm able to get the response body is when the request fails.
I've followed the blog post that solved my issue on getting the request body while using body-parser plugin - https://www.express-gateway.io/exploit-request-stream/.
const { PassThrough } = require("stream");
const jsonParser = require("express").json();
const urlEncodedParser = require("express").urlencoded({ extended: true });
module.exports = {
name: 'body-parser',
policy: actionParams => {
return (req, res, next) => {
req.egContext.requestStream = new PassThrough()
req.pipe(req.egContext.requestStream)
return jsonParser(req, res, () => urlEncodedParser(req, res, next))
}
}
};
When the request does work:
{ res: { statusCode: 400 },
req:
{ body: { a: 'b' },
headers:
{ ... } },
responseTime: 310 }
When it does not work:
{ res: { body: 'Bad gateway.', statusCode: 502 },
req:
{ body: { a: 'b' },
headers:
{ ... } },
responseTime: 1019 }
this code alone is not enough to get the response body. This will simply hook in the request body processing and make it available to EG in a parsed way. In case you want to hook in the response too, you will need to write an hook in the response object, once it's done.
You can find an example code here
I hope that helps!
V.

loopback rest connection headers authorization

I'm trying to access the Shopify Orders API in a Loopback application. I have the following data source:
"ShopifyRestDataSource": {
"name": "ShopifyRestDataSource",
"connector": "rest",
"operations": [{
"template": {
"method": "GET",
"url": "https://mystore.myshopify.com/admin",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
}
},
"headers": {
"Authorization": "Basic MzdiOD..."
},
"functions": {
"find": []
}
}]
}
And then I attempt a simple call:
var ds = app.dataSources.ShopifyRestDataSource;
ds.find(function(err, response, context) {
if (err) throw err;
if (response.error) {
next('> response error: ' + response.error.stack);
}
console.log(response);
next();
});
I'm getting the following exception message:
Error: {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
at callback (/order-api/node_modules/loopback-connector-rest/lib/rest-builder.js:529:21)
The Shopify API authenticates by basic HTTP authentication and I'm sure my request works since the same data works with curl. What am I doing wrong?
I couldn't find the "Loopback way" to do this and I couldn't wait, so I just wrote a simple https Node call. I'll paste this in here but I won't accept it as the answer. I'm still hoping someone will provide the right answer.
let response;
const options = {
hostname: 'mystore.myshopify.com',
port: 443,
path: '/admin/orders.json',
method: 'GET',
auth: `${instance.api_key}:${instance.password}`
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
let jsonResponse = JSON.parse(body);
// application logic goes here
response = 'ok';
});
});
req.on('error', (e) => {
response = e.message;
});
req.end();