code-8
code-8

Reputation: 58662

Pass dynamic value to url in Postman

I have 2 requests

1st Request

After did my first request, I get the response where I can parse for a taskId

In my test tab, I will then parse and store it like this

let taskId = pm.response.json().body.result[0].data.task
console.log(taskId)

I can see taskId printing in my console as 938

2nd Request

I require making a GET with this dynamic URL with the taskId that I got from the first one

http://localhost:3000/fortinet/monitor/{{taskId}}

So I set the above URL , set the HTTP verb to GET

in my Pre-request Script tab, I did this

let taskId = pm.globals.get("taskId") 

Result

ReferenceError: taskId is not defined

Image Result

enter image description here

How can I debug this further?

Upvotes: 9

Views: 24750

Answers (4)

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6272

For passing dynamic value, first you have to set it in environment or global variable in Tests tab because tests runs after request and you will get response value after request sent, but because you get response in json you have to first parse it, so what you can write in Tests tab is as follows:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("taskId", jsonData.token); // OR
postman.setGlobalVariable("taskId", jsonData.token);

Then you can use taskId as {{taskId}} wherever you want in url parameters or in request body or form data wherever.

If you want to know in detail how to extract data from response and chain it to request then you can go to this postman's official blog post which is written by Abhinav Asthana CEO and Co Founder of Postman Company.

Upvotes: 0

robmax
robmax

Reputation: 352

You have to set variable, but you are doing it wrong.
try this:
pm.globals.set("taskID", pm.response.json().body.result[0].data.task)

more you can read here: https://learning.postman.com/docs/postman/variables-and-environments/variables/

Upvotes: 7

Tarasovych
Tarasovych

Reputation: 2398

Please note, that URL which ends with resource identified like https://example.com/:pathVariable.xml or https://example.com/:pathVariable.json will not work.

You can go with https://example.com/:pathVariable with Accept: application/json header.

Upvotes: 0

Naveen K Reddy
Naveen K Reddy

Reputation: 499

The most suggested way is to use :key as in

http://localhost:3000/fortinet/monitor/:taskId

See the colon before taskId. The reason being, URI values sometimes many not be environment dependent. So, based on the usecase, you can use like I said or {{taskId}}

Upvotes: 17

Related Questions