Use postman to get a token from a request and send it to another
Asked Answered
R

6

9

I am using postman to do some testing on a REST API.

To login I use a post request who respond with a token I need to keep to use it with another request.

I did it that way : enter image description here

and then I want to use it in another request who need that token in the header :

enter image description here

I seems that it's not sending the token. What am I doing wrong ?

Ripp answered 3/2, 2016 at 14:31 Comment(1)
I see the example you have posted in question actually worked for me.Bibelot
R
4

The problem was that I was using postman.setEnvironmentVariable() instead of postman.setGlobalVariable().

I found the answer here

Ripp answered 6/4, 2016 at 15:29 Comment(0)
B
8

Let's say the login response is:

{
   "message": {
        "token":"Some token value here"
    }
}

There is a slight change in the latest postman and here is the syntax to set variable:

var data = pm.response.json();
pm.environment.set("token", data.message.token);

Read here more information: https://learning.getpostman.com/docs/postman/environments_and_globals/variables/

Bryophyte answered 3/1, 2019 at 10:56 Comment(0)
R
4

The problem was that I was using postman.setEnvironmentVariable() instead of postman.setGlobalVariable().

I found the answer here

Ripp answered 6/4, 2016 at 15:29 Comment(0)
A
3

I have used the below script in the Tests tab of the postman and it worked for me.

pm.environment.set("access_token", JSON.parse(responseBody).access_token);

After setting the access token in my first API, I am passing that access token in my second API.

Antoninus answered 4/3, 2020 at 9:24 Comment(0)
C
0

You can save token to an environment variable and access in any requests under that collection. May be this link will be helpful:

Extracting data from responses and chaining requests

Coordinate answered 5/11, 2019 at 8:5 Comment(0)
O
0
  1. Go to Login API

  2. Go to "Tests" tab.

  3. Add folowing script. This script will set variable "AuthToken" with response token.

    var jsonData = JSON.parse(responseBody); postman.setEnvironmentVariable("AuthToken", jsonData.data.accessToken);

enter image description here

Omit answered 1/3, 2021 at 13:8 Comment(0)
G
0

In addition to Gaurav's answer above, probably checking the status of the response first would be more nicer:

if(pm.response.code === 200) {
    pm.environment.set('authToken', pm.response.json().token)
}
Georgetta answered 14/4, 2023 at 9:37 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.