Skip to content

How To Use Postman Scratchpad

API Testing Blog

Postman Scratchpad: Your Sandbox for API Exploration and Testing

Postman’s Scratchpad is a powerful tool that lets you experiment with code directly within the Postman environment. It’s a dynamic, interactive workspace where you can write and execute JavaScript, making it ideal for:

  • Testing API Responses: Analyze and manipulate data received from your API calls.
  • Data Transformation: Prepare data for requests or process responses before you send them to other tools.
  • Reusable Code Snippets: Create reusable functions for common tasks.

Getting Started with Postman Scratchpad

  1. Open a New Request: Start by creating a new request in Postman.
  2. Locate the Scratchpad Tab: Navigate to the “Tests” tab and click on the “Scratchpad” icon.

Understanding the Postman Scratchpad Interface

  • Code Editor: A text editor where you write JavaScript code.
  • Run Button: Executes your code.
  • Output Area: Displays the results of your code execution.

Basic Scratchpad Functionality

1. Accessing Request Data

The pm object in Postman provides access to various request and response information:

  • pm.response.json(): Parses the response body as JSON.
  • pm.response.text(): Returns the response body as a string.
  • pm.request.url.toString(): Retrieves the complete request URL.

Sample Code:

// Extract the status code from the response
const statusCode = pm.response.code;
console.log(`Status Code: ${statusCode}`);
// Access the response body as JSON
const jsonData = pm.response.json();
console.log(`First item in the response: ${jsonData[0].name}`);

2. Modifying Request Data

Before sending a request, you can modify the request data using the pm.request object:

Sample Code:

// Set a custom header
pm.request.headers.add({key: "Authorization", value: "Bearer <your_token>"});
// Update the request body
pm.request.body.raw = JSON.stringify({
"name": "Updated Name",
"email": "updated@example.com"
});

3. Working with Environments & Variables

Read and update variables defined within your Postman environment directly within the Scratchpad.

Sample Code:

// Access an environment variable
const apiUrl = pm.environment.get("base_url");
console.log(`API URL: ${apiUrl}`);
// Update an environment variable
pm.environment.set("customVar", "Test Value");

Advanced Scratchpad Techniques

4. Writing Reusable Functions

Create JavaScript functions to perform common testing tasks or data manipulation:

Sample Code:

function validateStatusCode(expectedCode) {
const actualCode = pm.response.code;
if (actualCode !== expectedCode) {
console.error(`Expected status code ${expectedCode}, but got ${actualCode}`);
} else {
console.log(`Status Code Verification: Passed`);
}
}
validateStatusCode(200);

5. Error Handling

Use try-catch blocks to handle potential errors during code execution.

Sample Code:

try {
const jsonData = pm.response.json();
console.log(`Data: ${jsonData.data}`);
} catch (error) {
console.error("Error parsing JSON:", error);
}

6. Testing with Assertions

Postman’s built-in assertion library allows for more rigorous tests.

Sample Code:

pm.test("Status code is 200", () => {
pm.expect(pm.response.code).to.be.equal(200);
});
pm.test("Response body contains a specific key", () => {
pm.expect(pm.response.json()).to.have.property('id');
});

Best Practices for Postman Scratchpad

  • Organize Your Code: Structure your code with comments and functions for readability.
  • Use Descriptive Variable Names: Make your code easier to understand.
  • Test Thoroughly: Validate your code through various test scenarios.
  • Leverage Postman Documentation: Consult the documentation for comprehensive details about the pm object and available methods.

With its versatility and integration with the Postman platform, the Scratchpad enables you to streamline your API testing workflow and gain valuable insights from your API interactions.

API Testing Blog