Skip to content

Instantly share code, notes, and snippets.

@d8vjork
Last active March 1, 2019 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d8vjork/727b23a16d1f987a6c54b790609bb4e7 to your computer and use it in GitHub Desktop.
Save d8vjork/727b23a16d1f987a6c54b790609bb4e7 to your computer and use it in GitHub Desktop.
Postman API auth

Reuse this as much as you want, this is supposed to be helpful testing APIs with Postman or using Postman in general without worry about the authentication tokens.

Modifications are welcome :)

if (pm.environment.has("auth_path") && pm.environment.has("auth_token") && !pm.environment.get("auth_token")) {
pm.sendRequest({
url: pm.variables.get("base_url") + pm.variables.get("auth_path"),
method: 'POST',
header: {
'Content-Type': 'application/json',
},
body: {
mode: 'raw',
raw: JSON.stringify({
'username': pm.variables.get("username"),
'password': pm.variables.get("password"),
})
}
}, function (err, response) {
pm.environment.set("auth_token", response.json().access_token);
});
}
if (pm.response.code == 401 || pm.response.code == 403 || pm.response.code == 500) {
pm.environment.set("auth_token", "");
}
pm.test("Successful request", function () {
pm.expect(pm.response.code).to.be.oneOf([200,201,202]);
});
pm.test("No errors on body", function () {
pm.response.to.not.have.jsonSchema({
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"additionalProperties": true,
"properties": {
"name": {
"type": "string",
},
"message": {
"type": "string",
},
"code": {
"type": "number",
},
"status": {
"type": "number",
}
},
"required": [
"name",
"message",
"code",
"status"
]
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment