Playwright API Testing: POST Example

Introduction

In this section of the Playwright API testing tutorial, we will explore different ways to pass data in the body while making a POST request. We will deep dive into these methods to understand how to create a new booking using the Playwright API testing tool.

POST – Booking with Static Data

The first method involves sending an HTTP(s) POST request and receiving the response. In this approach, we will see how a POST call can be made by passing static data in the request body.

Implementation

To create a new booking, we will send a POST request to the /booking endpoint, providing the necessary request body or payload. Make sure to print the JSON response in the console to ensure that you have received the complete response. You should also confirm the status code and status message using an expect condition.

Additionally, you can verify if the response body contains the following data:

  • Firstname
  • Lastname
  • Totalprice
  • Depositpaid
// @ts-check 
const { test, expect } = require('@playwright/test');

test('should be able to create a booking', async ({ request }) => {
  const response = await request.post("/booking", {
    data: {
      "firstname": "Jim",
      "lastname": "Brown",
      "totalprice": 111,
      "depositpaid": true,
      "bookingdates": {
        "checkin": "2023-06-01",
        "checkout": "2023-06-15"
      },
      "additionalneeds": "Breakfast"
    }
  });

  console.log(await response.json());
  expect(response.ok()).toBeTruthy();
  expect(response.status()).toBe(200);
  const responseBody = await response.json();
  expect(responseBody.booking).toHaveProperty("firstname", "Jim");
  expect(responseBody.booking).toHaveProperty("lastname", "Brown");
  expect(responseBody.booking).toHaveProperty("totalprice", 111);
  expect(responseBody.booking).toHaveProperty("depositpaid", true);
});

Code Walkthrough

In this test, we make a POST call to the /booking endpoint. Since it’s a POST request, we need to specify the request body using the data parameter.

See also  Streamlining EHR Documentation for Denver Health Clinicians

Once the request is completed, we receive the response. We assert the response by using the expect condition for the status message and status code.

We also assert the response body to check specific key-value pairs. We store the JSON response data in a constant and then verify the values for firstname, lastname, totalprice, and depositpaid.

Execution

To execute the test, run the following command:

npx playwright test tests/01_post_static_data.spec.js

When the request is executed, the response body will be printed in the console. The test will also perform assertions and mark the test as passed.

HTML Report

To generate an HTML report, use the following command:

npx playwright show-report

POST – Booking with Static Data Specified in a JSON File

In this approach, we will learn how to make a POST call by passing static data stored in a JSON file.

Implementation

To create a new booking by using data from a JSON file in the POST request to the /booking endpoint, we need to provide the request body using the JSON file. The rest of the code implementation remains the same as the previous method.

Make sure to create a folder named test-data and add a JSON file named booking-details.json. In this file, specify all the booking details required for the POST call.

{
  "firstname": "Jim",
  "lastname": "Brown",
  "totalprice": 111,
  "depositpaid": true,
  "bookingdates": {
    "checkin": "2023-06-01",
    "checkout": "2023-06-15"
  },
  "additionalneeds": "Breakfast"
}
// @ts-check 
const { test, expect } = require('@playwright/test');
const bookingDetails = require('../test-data/booking-details.json');

test('should be able to create a booking', async ({ request }) => {
  const response = await request.post("/booking", { data: bookingDetails });

  console.log(await response.json());
  expect(response.ok()).toBeTruthy();
  expect(response.status()).toBe(200);
  const responseBody = await response.json();
  expect(responseBody.booking).toHaveProperty("firstname", "Jim");
  expect(responseBody.booking).toHaveProperty("lastname", "Brown");
  expect(responseBody.booking).toHaveProperty("totalprice", 111);
  expect(responseBody.booking).toHaveProperty("depositpaid", true);
});

Code Walkthrough

In this test, we make a POST call to the /booking endpoint. Similarly to the previous method, we need to specify the request body using the data parameter. However, we specify this data by importing it from the JSON file and calling it in the test.

See also  API Gateway Pricing: Everything You Need to Know

Execution

To execute the test, run the following command:

npx playwright test tests/02_post_static_json_data.spec.js

When the request is executed, the response body will be printed in the console. The test will also perform assertions and mark the test as passed. The only difference is that we optimized the test to use data from a JSON file.

HTML Report

To generate an HTML report, use the following command:

npx playwright show-report

POST – Booking with Dynamic Data

In this section of the Playwright API testing tutorial, we will explore how to make a POST call by passing dynamically generated data in the request body.

Implementation

To create a new booking by passing dynamically generated data in the POST request to the /booking endpoint, we will rely on faker-js to create random test data and luxon to generate dates. We will store these values in constants and use them to build the JSON request body.

// @ts-check 
const { test, expect } = require('@playwright/test');
import { faker } from '@faker-js/faker';
const { DateTime } = require("luxon");

const randomFirstName = faker.name.firstName();
const randomLastName = faker.name.lastName();
const randomNumber = faker.random.numeric(4);
const currentDate = DateTime.now().toFormat('yyyy-MM-dd');
const currentDatePlusFive = DateTime.now().plus({ days: 5 }).toFormat('yyyy-MM-dd');

test('should be able to create a booking', async ({ request }) => {
  const response = await request.post("/booking", {
    data: {
      "firstname": randomFirstName,
      "lastname": randomLastName,
      "totalprice": randomNumber,
      "depositpaid": true,
      "bookingdates": {
        "checkin": currentDate,
        "checkout": currentDatePlusFive
      },
      "additionalneeds": "Breakfast"
    }
  });

  console.log(await response.json());
  expect(response.ok()).toBeTruthy();
  expect(response.status()).toBe(200);
  const responseBody = await response.json();
  expect(responseBody.booking).toHaveProperty("firstname", randomFirstName);
  expect(responseBody.booking).toHaveProperty("lastname", randomLastName);
});

Code Walkthrough

In this test, we make a POST call to the /booking endpoint. As in the previous methods, we need to specify the request body using the data parameter. However, in this case, we generate the request data dynamically using the faker-js and luxon libraries. This ensures that a new set of data is sent every time we make a request.

See also  Introducing the ProgramMatek Personalization API: Enhance Customer Experiences!

Once the request is completed, we receive the response. We assert the response by using the expect condition for the status message and status code. Additionally, we assert the response body to check specific key-value pairs.

Execution

To execute the test, run the following command:

npx playwright test tests/03_post_dynamic_data.spec.js

When the request is executed, the response body will be printed in the console. The test will also perform assertions and mark the test as passed. The only difference is that we generate the data dynamically using the faker-js library, which guarantees a new data set each time.

HTML Report

To generate an HTML report, use the following command:

npx playwright show-report

Conclusion

In this Playwright API testing tutorial section, we explored different approaches to make a POST call with various types of data in the request body. By following the provided code examples and explanations, you can now create bookings using static data, static data from a JSON file, and dynamically generated data. Experiment with these methods to gain a deeper understanding of the Playwright API testing capabilities.

If you’re interested in learning more about ProgramMatek and its range of services, visit ProgramMatek.