3
votes

How to call a POST API request (Login API having request body with Username & Password field) from pre-request script tab of an another GET API which uses token from above API's body in its request url.

Login API : POST method; request body : username and password; response body: token. Get Customer Records API : GET method; request URI : /token/

Want to cover this end to end scenario in one test only in Postman. Can please anyone help me with the pre-request script for this? How should I invoke Login API?

2

2 Answers

5
votes

I just had the same issue and found the solution here.

In a gist, you can pass in a request object instead of the URL to the request.

const loginRequest = {
    url: 'http://example.com/login',
    method: 'POST',
    header: 'Content-Type: application/json',
    body: {
        mode: 'application/json',
        raw: JSON.stringify({        
            "username": pm.environment.get("username"),
            "password": pm.environment.get("password")
        })
    }
};


pm.sendRequest(loginRequest, function (err, response) {
    pm.environment.set("accessToken", response.json().token);
});

That's all there is to it.

UPDATE I just found the detailed info in the Postman docs.

0
votes

It's possible for sure.

  1. On "Pre-request Script" tab in Postman, make a POST request using the jQuery ajax method to your login API.
  2. Save the response body(your token) into the environment variable(postman.setEnvironmentVariable()).
  3. Set your /token/ part of your Postman request url as /{{your_variable_name}}/.

Have a look at this.