본문 바로가기

Develop/Etc

[Postman] Example of Pre-request Script

When I was doing a project to make REST API Client, I had to make access token before request REST API.

If the access token were expired, refreshing access token process was very bothersome process..

When I using Postman to testing my REST API, I could make this authentication process to automatically with pre-request script.

And easily access the authorization token with environment variables..


Here is example code of that process...

At first, Make pre-request script for request api.

This script using API_ID and API_SECRET from environment variables of Postman.

Make authorization header string that encoded with API_ID and API_SECRET..

This rule is my authorization server's personal rule.. It may different from another servers..

Set the request options, like url and method, and request headers like with authorization header string and request parameters...etc...

That's all !!


You can get the data for authentication from callback function with response data..

And get the token infomation from response with use json function of response object..

Then set the environment variable to using the data from auth server to access main request...

const api_id = pm.environment.get('API_ID');
const api_secret = pm.environment.get("API_SECRET");
const authorizationHeader = Buffer.from([api_id, api_secret].join(':')).toString('base64');

pm.sendRequest({
url: "https://auth_server/oauth/token",
method: "POST",
header: {
'content-type': 'application/x-www-form-urlencoded',
Authorization: "Basic " + authorizationHeader
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "client_credentials" },
]
}
}, function (err, res) {
const authResponse = res.json();
pm.environment.set("AUTHORIZATION_KEY", authResponse.access_token);
});

Set the Authorization field in header with environment variables like "{{AUTHORIZATION_KEY}}" in your main request.

Works great !!

'Develop > Etc' 카테고리의 다른 글

[Postgres] Setup via docker  (0) 2019.03.05
[Docker] Remove <none>:<none> images  (0) 2019.01.22
[HTML] Way to remove the arrow button at input tag that number type  (0) 2018.10.23
PostgreSQL install  (0) 2018.02.22
[CSS] Flexbox  (0) 2018.02.14