Sending a Post request in postman pre-script
Last Updated :
12 Dec, 2023
Postman stands out as a go-to tool for crafting and testing APIs, offering a robust set of features including API monitoring and script-based testing. Pre-request scripts which are effectively snippets of JavaScript code, play an important role in API testing. This article focuses on discussing sending a post request in Postman pre-script.
What is a Pre-script?
Pre-scripts are executed before any request is sent via Postman.
- They’re commonly utilized for initial setup tasks like configuring environment variables, data generation, request sending, checks, cookie value setting, and more.
- These scripts are a key player in effectively testing REST APIs.
Sending POST Request with Pre-request Script
To send the POST request, a sample REST API from jsonplaceholder will be used. To send a request we will use the pm.sendRequest() function provided by Postman. Follow the steps below to send the request:
Step 1: Launch the Postman application and create a new script.
Step 2: Set the HTTP method to GET and set the URL field to https://jsonplaceholder.typicode.com/posts/1 .
Step 3: Open the pre-request scripts tab. Paste the following code given below.
Javascript
const preRequest = {
method: 'POST' ,
header: 'Content-Type: application/json' ,
body: {
mode: 'raw' ,
raw: JSON.stringify({
title: 'Pre-Request Post Title' ,
body: 'Pre-Request Post Body' ,
userId: 1
})
}
};
pm.sendRequest(preRequest, (err, response) => {
if (err) {
console.error( 'Error:' , err);
} else {
console.log( 'Pre-request script response:' , response.json());
}
});
|
Step 4: Hit the send button. You will see the response of the your actual GET request in the output.
Response body of the actual GET request
Step 5: Open the Console (At the bottom of the screen), to see the response of the POST request sent by pre-request script.
Response of the POST request sent by pre-request script.
Conclusion
In this article, we learned how to send a POST request in the pre request script. There are many more possible actions that can be performed with the help of pre request scripts such as settings environment variables, constructing request body, fetching some data from external API, generating data for the request, setting cookie values, and all sorts of initial setup that is required before sending the request. You can read more about pre-request scripts . Alternatively, you can get more information about pre-request scripts and scripting in general on the official documentation website of Postman.
Share your thoughts in the comments
Please Login to comment...