Update request.body in pre-request script

Hi, I am using postman to perform a POST api where I need to encrypt the request data before sending the post.
The way I am trying to solve the problem is to set in the body in plain json and in the pre-request script apply the encryption.

Now that the encrypted data is ready to be sent, how can I set the new request to the request.body?

I tried to directly assign it request.body = _request; without success.

Thanks in advance!

@mtanzi

You can encrypt the plain JSON in the pre-request script and then save it to an environment variable that can then be referenced in the request.

Example:
Pre-request
var data = {
“someJSON”: “green”,
“moreJSON”: “supergreen”,
};

var encrypt_data = (Your Encryption Method);
postman.setEnvironmentVariable(“Encrypted_Data”, encrypt_data);

Body
{
“Data”: “{{Encrypted_Data}}”,
}

Mick

1 Like

Thank you @mick.mcbride for the quick answer !

Hi @mick.mcbride,

I tried this solution but, when I call the API, I keep getting an error, and the call doesn’t even hit the server

{
    "errors": {
        "detail": "Internal server error"
    }
}

here is how my request looks like:

{
  "encoded_data": {{encoded_data}}
}

and in the pre-request script I set the encoded_data as environment var:

postman.setEnvironmentVariable("encoded_data", my_encoded_data);

Without knowing your setup or collection I couldn’t guess to what is happening. When you previously attempted to call the API did you get a similar message or something different?

Mick

Before I wasn’t getting that error because my response body was a json containing the not-encrypted data,

then, in the pre-request script I was calling the request.data and encoding the body.

The problem there was that I couldn’t re assign the new encoded data to the body and the api was sending the not-encrypted data to the server.

The error there was coming from the server. Now the API looks not to be able to reach the server even if the request looks well formed.

I’ll do some more investigation…

Thanks!
M.

Found it,

The problem was the json that was malformed, I wasn’t adding the quotes between the environment variables

{
  "encoded_data": "{{encoded_data}}"
}

thanks again!

Great, always seems to be the little things that trip me up the most.

Mick

but shouldn’t that result in a syntax error with a 400 status code when you send the request?