0
votes

I am considering using Postman for automating my testing of REST API and have been using it for only a few days. So far, I've created an adequate amount of requests for my initial collection. I have made use of global, environment, and collection variables in my pre-request scripts, tests, and bodies of my requests as well. I'm looking to control which properties are included in the request without making several copies of the same request to exclude some properties.

For example, I have a JSON request body as such:

{
    "Username": "{{Username}}",
    "Password": "{{Password}}",
    "AnotherProperty": ""
}

In the event that 'AnotherProperty' is null or empty, I would like to remove the property entirely from the request. I only want 'AnotherProperty' to be included in the request if it has a value. Thus, if null or empty the request should appear as:

{
    "Username": "{{Username}}",
    "Password": "{{Password}}"
}

The only way I found to complete this is to save separate requests both with and without the property in the collection, but this does not seem efficient to do for every property in the request when there are many properties. Is it possible to control the properties included in the request if their values are null or empty?

1

1 Answers

0
votes

If you have the JSON request body from a previous request, you save it as an environment variable. Then you can update the body that you plan to send in the pre-request script for the primary request, or update the body in the test script of the preceding request.

Then in the primary request, you can send the Body as raw with this syntax {{variableName}}.

Example of pre-request script:

// retrieve the environment variable
let potentialBody = JSON.parse(pm.environment.get("bodyToSend"));

// remove the property if empty
if (potentialBody.AnotherProperty === "") {
    delete potentialBody.AnotherProperty;
} 

// re-save the environment variable so it can be used in the primary request
pm.environment.set("bodyToSend", JSON.stringify(potentialBody));

Example of Body (select raw):

{{bodyToSend}}