In your previous blog post, you learned how to use a Postman script to automatically handle Django's CSRF token for single requests. This post will show you how to take that a step further by using a script to loop through a list of product categories and create them all at once. This is a common and powerful technique for populating a development or staging database with test data.
Looping Requests with a Script
When dealing with a list of items, manually creating a request for each one is not only time-consuming but also prone to error. Postman's pm.sendRequest
function, combined with a JavaScript loop, allows you to automate this process. The script you provided is a great example of this. It iterates through a JSON array of product categories and sends a separate POST request for each item.
The Code Explained
Let's break down the key parts of the script:
- JSON Data: The script starts with a `categories` array containing a list of objects. Each object represents a product category, with a single property: `category_name`. This is the data we want to send to our Django API.
pm.sendRequest
: This is a core Postman function that allows you to send a new request from within a script. It's an asynchronous function, so we'll use a modern JavaScript pattern to handle the loop and ensure requests are sent sequentially with a delay.- Adding a Delay: To prevent a flood of concurrent requests that could overload your server, we introduce a delay between each request. Our updated script uses a cleaner `async/await` pattern with a `Promise` and `setTimeout` to manage this.
urlencoded
Body: The script uses theurlencoded
mode for the request body, which is what a standard HTML form submission uses. It maps the `category_name` value from your JSON data to the corresponding form field.
Refined Script with Improved JSON Data
The updated script is more modular and uses Postman's built-in pm.sendRequest
with `async/await` to create a cleaner and more maintainable code block. This approach makes the script easier to read and modify for future use.
// JSON data for product categories
const categories = [
{ "id": "prodcat_001", "category_name": "Dry Goods" },
{ "id": "prodcat_002", "category_name": "Meat & Poultry" },
{ "id": "prodcat_003", "category_name": "Seafood" },
{ "id": "prodcat_004", "category_name": "Produce (Vegetables)" },
{ "id": "prodcat_005", "category_name": "Produce (Fruits)" },
{ "id": "prodcat_006", "category_name": "Dairy & Eggs" },
{ "id": "prodcat_007", "category_name": "Prepared Goods" },
{ "id": "prodcat_008", "category_name": "Wine & Spirits" },
{ "id": "prodcat_009", "category_name": "Beer" },
{ "id": "prodcat_010", "category_name": "Non-alcoholic Beverages" }
];
// Configuration
const requestUrl = 'http://127.0.0.1:8000/product/category/add/';
const delayInMs = 1000; // 1-second delay
// Asynchronous function to handle the loop and delay
async function sendRequestsSequentially() {
for (const item of categories) {
// Construct the request object
const requestDetails = {
url: requestUrl,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': pm.environment.get('csrftoken'),
'HX-Request': 'true',
'Cookie': `csrftoken=${pm.environment.get('csrftoken')}`
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: 'name', value: item.category_name }
]
}
};
// Send the request and wait for the response
try {
const response = await pm.sendRequest(requestDetails);
console.log(`Request for '${item.category_name}' succeeded. Status: ${response.status}`);
} catch (error) {
console.error(`Request for '${item.category_name}' failed. Error:`, error);
}
// Wait for the specified delay before the next iteration
await new Promise(resolve => setTimeout(resolve, delayInMs));
}
}
// Start the process
sendRequestsSequentially();
This powerful approach is not limited to creating data. You can adapt this script to perform mass updates, deletions, or other operations, making it an essential tool for automating API workflows and managing your test environments.