0

Description

So, I have a Pre-request script in Postman which runs and gets a API_token, which in turn sets the env variable "api_token". I have set this "api_token" using the script specified in the next section.

Requirement

I want the behaviour to be such.

  1. I click the send button.
  2. The Pre-Request script handles whole request and the default behaviour is prevented.
  3. The result of the request is outputted as if the default request was sent. ( optional. brownie points if you can get this :D )

I tried the following script :

// setting the header body
const options = {
  url:  'https://api/v1/login', 
  method: 'POST',
  header: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: {
    mode: 'raw',
    urlencoded : [
      { key: 'username', value: 'admin'},
      { key: 'password', value: 'Admin@123'},
    ]
  }
};  

// sending the request :D
pm.sendRequest(options, function (err, response) {

    pm.environment.set("api_token", response["id"]);
});
    // throw new Error("Error : access denied"); I Tried to prevent any further execution;
return;

Shortcomings

  1. Although, It does set the env variable, but it also sends the default request which in turn creates 2 api_tokens for me ( which I want to prevent)
  2. It does not display the response I generated with my pre-request script.
Lucifer
  • 79
  • 6
  • why need 2 login request, one in pre-request and one in request? – lucas-nguyen-17 Nov 14 '22 at 08:39
  • I actually set up the API with login request but then I realised I can set ENV variables with `pre request scripts`. But now that I think of it , I can remove the request body and the send button wont work which would solve 2 of 3 requirements. – Lucifer Nov 14 '22 at 12:15
  • IMO, request in `pre-req` helps you to prepare pre-conditions for the main request, for eg. in `pre-req` is getting token of login API, the main `request` is GET users. In this case, you can view both request info in Console tab. No one puts 2 requests Login (one in `pre-req` and one in `main request`) like you. – lucas-nguyen-17 Nov 14 '22 at 14:01
  • I just want the login to be stored as env variable and a success message ( can alert work ?) – Lucifer Nov 15 '22 at 08:01

0 Answers0