{
"data": {
"username": "tell1535",
"password": "{{encryptedPassword}}",
"type": "session"
}
}
this is the body of my postman request
is there a way to use the value of username
in pre request tab and set a value like
pm.environment.set("number", usernamelast4digits)
This is overview
How to use Postman's global variable for username
and number
by JSON.parse(pm.request.body.toString())
By JavaScript commands (slice) in Pre-request Script
tab from input body.
Demo by Flask and Postman To save as server.py
It has one post API
.
The post API
forward from the input POST body to the output body.
from flask import Flask, jsonify, request
import jwt
app = Flask(__name__)
@app.route("/sessions", methods=["POST"])
def post_test():
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
json = request.get_json()
encoded_jwt = jwt.encode({'username': json['data']['username']}, 'secret', algorithm='HS256')
newJson = {
'data' : {
'type': 'session',
'token': encoded_jwt
}
}
return jsonify(newJson), 201
else:
return 'Content-Type not supported!'
if __name__ == "__main__":
app.run(debug=True)
pip install flask
pip install pyjwt
python server.py
Example POST call
http://127.0.0.1:5000/sessions
Input Body
{
"data": {
"username": "tell1535",
"password": "{{encryptedPassword}}",
"type": "session"
}
}
Pre-request Script
var jsonData = JSON.parse(pm.request.body.toString());
console.log(jsonData);
pm.globals.set("username", jsonData.data.username);
pm.globals.set("number", jsonData.data.username.slice(-4));
console.log(pm.globals.get("username"));
console.log(pm.globals.get("number"));
Output Body
{
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlbGwxNTM1In0.V8tbNNjiEtv3MBYmwX82W-t0y0bnfLER48a9pQiK8m0",
"type": "session"
}
}
Send POST API
After send POST API
encryptedPassword
need to assign by manually.
username
and number
will assign.
And debug the variable log from Postman console.
API's output will create token by Flask JWT logic.
The number variable picked up from input body by last 4 digit of username
.