Reputation: 87
I want to run a query before the actual request runs and get a value from the pre-request response and set it in a collection variable. I have a problem running the following as I used to do it while testing REST APIs.
This is what I tried to do
const getUserBeforeUpdate = {
url: pm.environment.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});
but I get a console error stating
There was an error in evaluating the Pre-request Script: Error: Unexpected token u in JSON at position 0
What's the right way to chain requests in graphql?
Upvotes: 1
Views: 2884
Reputation: 31
Collection variable are accessible via collectionVariables. This should work for you:
const getUserBeforeUpdate = {
url: pm.collectionVariables.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.collectionVariables.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});
Upvotes: 3
Reputation: 25921
I don't have the ability to run you request but would this work?
const getUserBeforeUpdate = {
url: `${pm.environment.get("base-url")}`,
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({
query: 'query { user { profile { id } } }'
})
};
pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});
Upvotes: 0
Reputation: 87
I was able to fix this by changing the url value to the actual url directly as a string. I'm not sure why getting the variable from environment didn't work yet.
Upvotes: -1