DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Do API Testing?
  • A Developer's Guide to Chrome Extension Manifest V3 Declarative Net Request API
  • From Microservices to Agent Services: The Next Architectural Shift
  • The Bill You Didn't See Coming

Trending

  • Why Real-Time Data Pipelines Are Becoming the Foundation of Industrial AI
  • Why Security Scanning Isn't Enough for MCP Servers
  • A Practical Guide to Using Java Virtual Threads With JMS Listeners
  • Isolation Boundaries in Multi-Tenant AI Systems: Architecture Is the Only Real Guardrail
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. How to Test POST API Requests With Playwright TypeScript

How to Test POST API Requests With Playwright TypeScript

Learn how to test POST API requests in Playwright with TypeScript using static JSON objects and arrays, JSON.stringify(), JSON files, and the Faker library.

By 
Faisal Khatri user avatar
Faisal Khatri
DZone Core CORE ·
Sep. 29, 26 · Analysis
Likes (0)
Comment
Save
Tweet
Share
87 Views

Join the DZone community and get the full member experience.

Join For Free

Testing POST API requests is an important skill for modern QA and automation engineers working with backend services and microservices. In this article, we’ll explore how to test POST API requests with Playwright and TypeScript, focusing on sending a request body using different approaches.

By the end, you will learn how to send POST API requests using the following approaches for adding a request body:

  1. JSON Object/Array(data)
  2. Stringified JSON
  3. JSON File
  4. Faker library

Application Under Test

We will use the POST /addOrder API of the RESTful e-commerce demo application for this demo. The API schema is provided below:

JSON
 
{
    "user_id": "string",
    "product_id": "string",
    "product_name": "string",
    "product_amount": 0,
    "qty": 0,
    "tax_amt": 0,
    "total_amt": 0
  }
]


Testing POST API Requests With Playwright TypeScript

Playwright provides a powerful request API that allows us to create and manage HTTP request contexts. Let’s walk through how to send POST API requests step-by-step using different approaches for passing the request body:

Request Body as JSON Object/Array

Let’s send a POST API request with a static JSON Array and verify that the response status code is 201.

TypeScript
 
test("POST order details API with static JSON Array", async ({ request }) => {
  const response = await request.post("http://localhost:3004/addOrder/", {
    data:[{
    user_id: "1",
    product_id: "82",
    product_name: "Cadbury Bar",
    product_amount: 12,
    qty: 2,
    tax_amt: 1,
    total_amt: 25
  },
  {
    user_id: "2",
    product_id: "80",
    product_name: "MilkyBar",
    product_amount: 10,
    qty: 1,
    tax_amt: 1,
    total_amt: 11
  }
],
});
  expect(response.status()).toBe(201);
});


Code Walkthrough

A Playwright test case for testing the POST API request is created using the request API, which is a built-in Playwright APIRequestContext fixture used to send HTTP requests.

  • Sending the POST Request: The request.post() sends a POST request to the “http://localhost:3004/addOrder/” endpoint. The response received after sending a POST request is stored in the response variable.
  • Passing the Request Body (Static JSON Array): The data property is used to send the request body, which accepts data in JSON Array and JSON object formats. Since the POST /addOrder API accepts an array of order details, allowing multiple orders to be submitted within a single JSON array, the test provides the data in JSON array format.
  • Validating the Response: The response.status() retrieves the HTTP status code. The assertion ensures that the status code 201 is returned, indicating that the orders were successfully created.
Available on GitHub


Request Body Using JSON.Stringify()

JSON.stringify() can be used while sending raw payloads, testing malformed JSON, or sending custom-formatted JSON. However, the Content-Type header should be set to application/json so the server correctly interprets the request body as JSON data.

Let’s write the same POST /addOrder test using JSON.stringify() and verify that a status code 201 is returned in the response.

TypeScript
 
test("POST order details API using JSON.Stringify", async ({ request }) => {

    const orderData = [{
        user_id: "5",
        product_id: "64",
        product_name: "Cadbury Mini",
        product_amount: 5,
        qty: 3,
        tax_amt: 1,
        total_amt: 16

    }];
  const response = await request.post("http://localhost:3004/addOrder/", {
    data: JSON.stringify(orderData),
    headers: {
      "Content-Type": "application/json",
    },
});
  expect(response.status()).toBe(201);
});


The orderData array is defined to contain one order object. Each field represents the order details such as user_id, product_id, product_name, and so on. This is a normal JavaScript object at this stage, not JSON yet.

The JSON.stringify(orderData )converts the JavaScript object into a JSON string. As we manually stringify the request payload, we should explicitly set the Content-Type header to application/json. It tells the server to treat the request body as JSON data.

Playwright sends the POST API request using the post() method and then validates that the response returns a 201 status code.

Request Body as a JSON File

Using a JSON file as a request body is a handy approach when testing POST API requests with Playwright TypeScript. It supports large payloads and allows the same file to be easily reused across multiple tests.

The following orders.json file will be used as a request payload in the POST /addOrder API:

JSON
 
[
  {
    "user_id": "1",
    "product_id": "79",
    "product_name": "5 star 10gm Chocobar",
    "product_amount": 5,
    "qty": 1,
    "tax_amt": 0.5,
    "total_amt": 5.5
  },
  {
    "user_id": "2",
    "product_id": "71",
    "product_name": "Lindt Milk Chocolate",
    "product_amount": 15,
    "qty": 3,
    "tax_amt": 2.5,
    "total_amt": 47.5
  }
]


The following configurations should be in place before we proceed to write the test using a JSON file as the request payload.

tsconfig.json

JSON
 
{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "resolveJsonModule": true
  }
}


We need to ensure that the JSON file is imported first and then attached to the data parameter while sending the POST request.

TypeScript
 
import orders from '../test_data/orders.json' with {type: 'json'};

test("POST order details API using JSON file", async ({ request }) => {

  const response = await request.post("http://localhost:3004/addOrder/", {
    data: orders,
});
  expect(response.status()).toBe(201);
});


This test imports test data from an external orders.json file and uses it as the request body for a POST API call in Playwright. The request.post() method sends the imported JSON directly as the payload, and the test verifies that the API returns a 201 status code.

Using a JSON file makes it easier to manage, reuse, and update request payloads without modifying the test logic, improving the maintainability and readability of API tests.

Request Body With Faker Library

Using the Faker library to create a request body for a POST API helps generate realistic and dynamic test data, reduces hardcoded values, and improves test coverage. It is especially useful for simulating real-world scenarios and avoiding duplicate data issues.

However, it also has limitations. Since Faker generates random data, it may lead to inconsistent test results if not properly handled, and debugging failures could become more difficult without fixed or reproducible inputs.

To use the Faker library, we need to install it first using the following command:

Plain Text
 
npm install --save-dev @faker-js/faker


Next, let’s create two helper functions: one to create order objects with the required order details, and another to generate an array of orders based on the count provided by the user.

TypeScript
 
import { faker } from '@faker-js/faker';

export function createOrderDetails() {
    const productAmount:number = faker.number.int({ min: 1, max: 100 });
    const qty:number = faker.number.int({ min: 1, max: 5 });
    const taxAmt:number = faker.number.int({ min: 2, max: 10 });
    const totalAmt:number = (productAmount*qty)+taxAmt;

    return {
    user_id: faker.number.int({ min: 1, max: 50 }),
    product_id: faker.number.int({ min: 1, max: 100 }),
    product_name: faker.commerce.productName(),
    product_amount: productAmount,
    qty:qty,
    tax_amt: taxAmt,
    total_amt: totalAmt
  };
}


The createOrderDetails() function returns the order details with the required fields. It also calculates the total amount by summing the total product value and tax amount. The values in all fields are updated randomly using the appropriate methods provided by the Faker library.

TypeScript
 
import { faker } from '@faker-js/faker';

export function createRandomOrders(count:number) {
    return faker.helpers.multiple(createOrderDetails, {count});
}


The createRandomOrders(count) method accepts a count parameter and returns randomly generated orders that can be directly used in the test.

TypeScript
 
return faker.helpers.multiple(createOrderDetails, {count});


This is where the work happens.

multiple() is a helper function provided by Faker. Its job is to execute another function multiple times and collect all the results into an array. It takes two arguments:

  1. A function to execute repeatedly.
  2. An options object specifying how many times to execute it.

It asks Faker to call createOrderDetails() exactly count times, collect all the generated orders into an array, and return that array to the caller.

TypeScript
 
test('POST order details API using Faker library', async({request}) => {
  
    const orderData = createRandomOrders(5);
    const response = await request.post("http://localhost:3004/addOrder/", {
    data: orderData,
    headers: {
      "Content-Type": "application/json",
    },
});
    expect(response.status()).toBe(201);
  
});


This test sends a POST request to the /addOrder endpoint API using dynamically generated test data from the Faker library. The createRandomOrders(5) function generates an array of 5 random order objects, which are passed as the request body using the data property.

The test then verifies that the API responds with a 201 status code, confirming that the orders were successfully created.

Summary

In this tutorial, we explored multiple approaches to testing POST API requests using Playwright with TypeScript, including sending static JSON payloads, using JSON.stringify, importing data from external JSON files, and generating dynamic test data with the Faker library. We also covered how to handle headers correctly and validate API responses using status code assertions.

In my experience, using external JSON files is a practical approach for testing POST API requests because it lets us send bulk data from a single file. Similarly, the Faker library can also be used to generate dynamic test data; however, in some cases, using a third-party library may not be permitted. Ultimately, the software team chooses the approach that best fits their testing strategy.

Happy testing!

API Requests Testing

Published at DZone with permission of Faisal Khatri. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Do API Testing?
  • A Developer's Guide to Chrome Extension Manifest V3 Declarative Net Request API
  • From Microservices to Agent Services: The Next Architectural Shift
  • The Bill You Didn't See Coming

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook