30/10/2024
In Postman, we often need to monitor the outcomes of our requests, particularly to catch failures and understand why they happened. Using JavaScript within Postman’s scripting capabilities, we can create a script to log failed requests in a structured format. Below, we will walk through the steps to set this up.
Postman has two scripting sections: Pre-request Script and Tests. The Tests section runs after the request completes and is the ideal place for logging the results of API calls.
Here’s a simple script that logs failed requests with relevant details such as the request URL, HTTP method, response code, and error message.
pm.test("Log failed requests", function() { if (pm.response.code >= 400) { // Check if the response code indicates a failure // Create an object to hold the log details const logDetails = { timestamp: new Date().toISOString(), url: pm.request.url.toString(), method: pm.request.method, status: pm.response.code, errorMessage: pm.response.status, responseBody: pm.response.text() // Capture the response body for additional context }; // Convert the log details to a string and log it to the console console.error(JSON.stringify(logDetails, null, 2)); // Optionally, save the log to an environment variable for persistence if (!pm.environment.get("failedRequests")) { pm.environment.set("failedRequests", JSON.stringify([])); } const currentLogs = JSON.parse(pm.environment.get("failedRequests")); currentLogs.push(logDetails); pm.environment.set("failedRequests", JSON.stringify(currentLogs)); } });
timestamp
: Using new Date().toISOString()
captures the exact time when the failure occurred.url
: The request URL is captured using pm.request.url.toString()
.method
: This captures the request method (GET, POST, etc.).status
: The HTTP response code is stored here.errorMessage
: Provides a short description of the error.responseBody
: Captures the response body, which may provide more context on the error condition.console.error()
, we output the log details to the console, making it easy to track failed requests.To test the script:
View -> Show Postman Console
).By implementing this script, you will improve your ability to monitor and troubleshoot issues in your API requests efficiently.
30/10/2024 | API Testing
30/10/2024 | API Testing
30/10/2024 | API Testing
30/10/2024 | API Testing
30/10/2024 | API Testing
30/10/2024 | API Testing
30/10/2024 | API Testing