1
{
    "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)

Update: enter image description here

guradio
  • 15,524
  • 4
  • 36
  • 57

1 Answers1

1

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.

enter image description here

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)

Install Dependency

pip install flask
pip install pyjwt

Run server

python server.py

enter image description here

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

enter image description here

After send POST API encryptedPassword need to assign by manually.

username and number will assign.

enter image description here

And debug the variable log from Postman console.

enter image description here

Conclusion

API's output will create token by Flask JWT logic. The number variable picked up from input body by last 4 digit of username.

Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • do i need to set the username like the on in image? i tried but i am getting undefined – guradio Jul 27 '23 at 13:04
  • 1
    the demo declare variable in environment variable, see upper image(last screen image) from my answer. – Bench Vue Jul 27 '23 at 13:18
  • one question the value is from the environment variable not from `"username": "tell1535",` from the body ? is there a way to get the value from the body not from the environment? – guradio Jul 31 '23 at 23:06
  • @guradio, I revised my answer the `username` data comes from another API call. let me know if you figure out. – Bench Vue Aug 01 '23 at 03:50
  • if I understand this correctly you get the number from the `response/Output Body` because you can change the response on my current problem I cant change the response all I can use is the data from `Input Body` is this possible to get that data ? – guradio Aug 01 '23 at 05:02
  • Usually GET API use a query parameter instead of an input body. I changed API1 with get API. Can you follow my steps? then you can get the whole flow then you can apply it to your API. – Bench Vue Aug 01 '23 at 10:42
  • My problem is, I cant change the response body also the request is a post request .. Is it not possible to do it in `post` and get the value from the `Input Body`? – guradio Aug 02 '23 at 00:53
  • Can you draw detail of your input body and output body with picture, I need to understand your situation and want to item. – Bench Vue Aug 02 '23 at 01:13
  • I update my OP with an image of my request . – guradio Aug 02 '23 at 02:45
  • 1
    I updated my answer, can you review it and confirm it? – Bench Vue Aug 02 '23 at 09:19