Home > Mobile >  Using the postman I try to test, various scenarios for my APIs. But I have a question, if I have an
Using the postman I try to test, various scenarios for my APIs. But I have a question, if I have an

Time:03-14

But I have a question, if I have an authentication API (I don't use any authorization method), it generates a different token for me every time in response (after a POST request), to be used in other APIs, how can I add that token in the environment to be taken automatically and only called in the other APIs?

For example, to be a little more specific: POST Request

{
"username": "test",
"password": "password"
}

Response:

{
"status": 0,
"message": "success"
"token":"zxvnm5yrhd6dfdfd6fd8g56f6teui5AXgGk851"
}

That token needs to be added to other APIs in order to be tested, but I want it to be added automatically, or just to call it, so I don't always have to copy-paste.

And another curiosity, can you give me some recommendations for tutorials, on how to automate the tests in postman, and the alerts/tests to get your results by email?

CodePudding user response:

After successful register, you can set your token variable as an environment variable. For instance, set your variable as {{autToken}} set your value with pm.environment.set("autToken", userData.accessToken); After that, at every other API using that token in your postman tests, set authorization parameters as Bearer token (if your token is bearer token) and give that env variable as a parameter.

CodePudding user response:

You can create a variable for your collection, which will hold the token, lets call it access.token. How to do it.

You can add a test after request for getting access token, which actually won't test anything, but will set the variable value.

pm.test("Set access token", function() {
    console.log("Attempting to set access token variable");
    pm.response.to.have.status(200);
    let token = pm.response.json()["token"];
    if (token === undefined || token === "") {
        console.log("Missing access token");
        return;
    }
    pm.collectionVariables.set("access.token", token);
});

This example actually tests for response status code to be 200, but you can remove/change it depending on needs. The first step is not really needed, setting the variable in the test will create if it is missing.

Then you can use the variable in your other requests like this:

{{access.token}}

Check the postman guide as well.

  • Related