Scripts
Postdata lets you add dynamic behavior to REST API requests. This allows you to write test suites and build requests that can contain dynamic parameters. You can add ECMAScript code that executes based on events in the flow:- Pre-request scripts are executed before a request is sent to the server.
- You can add multiple pre-request scripts to a request.
- You can add pre-request scripts to both requests saved and not saved in a collection.
Postdata will then execute the scripts along with the requests in the specified order.
Pre-request script
Pre-request script is a piece of code that will run before the execution of the request. You can use the pre-request script for a pre-processing task such as:- Setting parameters, headers.
- Adding body data.
- Adding variable values.
- Including timestamps in request headers.
Writing pre-request scripts
Postdata provides a specialpw
object containing various methods to create scripts and tests. The pw
object is global and can be referenced by name to access methods.
For example, to set an environment variable, you can use the pw.env.set()
method.
Examples
Let us look at some examples of how you can use Postdata to write pre-request scripts.Setting environment variables
pw.env.set()
can be used directly for quick and convenient environment variable definition. It can be used to better organize request codes.
<<variable_name>>
. So the URL will be <<baseURL>>/<<method>>
.
Generating random Values to test API
Let us take a case where we need to test random test-user data available at an endpoint. Let us use the following GET API endpointhttps://reqres.in/api/users/
.
Add <<randomValue>>
to the endpoint URL.
randomValue
and the API will return a random user associated with the random value.
You will get a similar response as shown below: