As noted in the previous post, the app icon for the packaged app was updated in line with the new Postman logo. Apart from bug fixes, the other big change though is something that a lot of users had requested – pre-request scripting.
Pre-request scripts are similar to test scripts except as the name implies, they are executed just before your request is going to be sent to the server by Postman. Some sample use cases for pre-request scripts are:
- Generating values and injecting them in requests through environment variables. For example, you can generate timestamps or hashes of values.
- Handle custom authentication protocols.
- Read and modify data from JSON or CSV files and inject them into scripts.
The primary flow while working with pre-requests would be setting an environment or a global variable and then using the variable in your HTTP request. Let’s look at an example:
Open Postman and click on the “Pre-request scripts” button.
Set the request URL to http://echo.getpostman.com/post and set the method to POST. Keep the body type as form-data.
Inside the pre-request editor, write the script below:
var date = new Date();
var time = date.getTime();
What we are doing here is generating a timestamp and setting an environment variable. This environment variable will then be used in the Postman request builder interface.
Set the environment variable in the form-data key value editor.
Create a new environment called “echo.getpostman.com” in the environment manager modal.
Select the environment from the selector on the top right.
Hit “Send” and analyze the response.
As evident above, the server receives the value of the variable which was dynamically generated.
Pre-request scripts can be used in creative ways and can save you a lot of time. If you come up with an interesting use case, make sure to let us know on Twitter or email! Check out the official docs page here. We will be updating it with more examples continuously.