Raw json body how to add variable?

Hello,

How can I add variable to raw - json body?

 {
    "referenceId": "022078925508",
    "productCode": "001002461285",
    "quantity": "1",
    "version": "V1",
    "signature": {{Signature}},
    "applicationCode": "52e7cf966b724749a7c4efadc3727ed7"
}

Here is my pre-request script

var ApplicationCode = request.data["ApplicationCode"];
var Version=request.data["version"];
var ReferenceId=request.data["referenceId"];
var ProductCode=request.data["productCode"];
var Quantity=request.data["quantity"];
var SecretKey="e56067172e61";
var hashText = ApplicationCode+ProductCode+Quantity+ReferenceId+Version+SecretKey;
var encryption = CryptoJS.MD5(hashText).toString();

postman.setEnvironmentVariable("Signature", encryption);
3 Likes

Hi @kizildagcenk, you’re using the correct method to set the variable in the pre-request script.
One thing I’d like to point out on the last line is that you can use pm.environment.set("Signature", encryption);
This is the new API and I recommend using it.

Also, in the raw body, you’ve to surround the Signature variable with quotes.
So your raw body actually becomes the following:

{
    "referenceId": "022078925508",
    "productCode": "001002461285",
    "quantity": "1",
    "version": "V1",
    "signature": "{{Signature}}", // notice the quotes here around the variable
    "applicationCode": "52e7cf966b724749a7c4efadc3727ed7"
}

Now run your script and it should work as expected.

8 Likes

Thank you for your reply @sivcan, I m getting error from the service. I think they want content-type = application/x-www-form-urlencoded. Is there a way to convert this to application/x-www-form-urlencoded?

Best Regards.

@kizildagcenk
You can try this:
Disable the first header.
And then you can add the other header like so:

Or if this fits your case then you can use the body type x-www-form-urlencoded instead of raw
This will automatically add the header too.

I know this is an older post/has been closed for a while. But is there a limit to the variable size? I am trying to get a description from a JIRA issue and use it as a variable to create another one.

The syntax you mention, “{{Variable}}”, works for me in Body Raw JSON when using variables such as Date or Title from the JIRA issue, but when using the description I am getting the following error:

{
“errorMessages”: [
“Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value\n at [Source: org.apache.catalina.connector.CoyoteInputStream@7fc7314c; line: 13, column: 39]”
]
}

I am able to get the request to work when I copy in the description value into the JSON Body (even its entire length )

Any suggestions?

Edit:

So I was able to answer my own question.
Using stringify() to set my variable seems to fix my problem:

pm.environment.set(“description”, JSON.stringify(description));

2 Likes

Thank you, @davidbeinhart. It works for me.