• Automation
  • Home
  • /
  • Learning Hub
  • /
  • Playwright API Testing: Definitive Guide With Example
  • -
  • May 05 2023

Playwright API Testing: Definitive Guide With Example

This tutorial delves extensively into Playwright API testing with working examples for POST, GET, PUT, PATCH, and DELETE requests.

Chapters

Total Chapters (22)

Chapter 16 : Playwright API Testing Tutorial: A Complete Guide with Examples

Triangle
Testμ Conference

OVERVIEW

In modern web development, APIs play a significant role. The API economy refers to the use of Application Programming Interfaces (APIs) to facilitate the creation of new products, services, and business models. APIs allow different software applications and systems to interact with each other, enabling data sharing, integration, and communication between different services and devices.

APIs have become fundamental building blocks of modern software development, allowing businesses to develop new products and services more quickly and efficiently by leveraging the capabilities of existing software and platforms.

It also provides new opportunities for businesses to generate revenue and reach new markets. For example, many companies offer APIs that allow third-party developers to build applications that integrate with their services, creating new business opportunities for both the API provider and the developers.

APIs are integral to microservices architecture, as they enable communication and interaction between the individual services that make up the application. Each microservice exposes a set of well-defined APIs that other services can use to access its functionality.

When doing automation testing, you must automate use cases on UI, API, or both. Let's take an example where you need to log in using the token, or you want to quickly create a dataset using API and then run the UI test. You need an automation testing framework to run UI tests and trigger API endpoints. Further, it helps in end to end testing, creating prerequisite data, configuring microservices, and setting up the environment.

Playwright is one such framework that provides the ability to not only automate your UI flow, but it can also help you automate the APIs. Playwright added support for API testing from v1.16, making the perfect solution for E2E testing.

Before we get into further details in this Playwright API testing tutorial, let's first understand CRUD operations in APIs.

...

CRUD in API

CRUD stands for Create, Read, Update, and Delete, which are the four basic operations that can be performed on data in a database or system. When building an API, it is common to implement CRUD functionality to allow customers to perform these operations on the resources the API exposes.

Here's a brief overview of how CRUD can be implemented in an API:

Create (POST)

This operation is used to create a new resource. The client sends a POST request to the API endpoint with the data for the new resource in the request body. The API then creates the resource and returns a response with the details of the newly created resource, including its unique identifier.

Read (GET)

This operation retrieves an existing resource or a list of resources. The client sends a GET request to the API endpoint, optionally with query parameters to filter, sort, or paginate the results. The API then returns the requested resource or resources in the response body.

Update (PUT or PATCH)

This operation is used to modify an existing resource. The client sends a PUT or PATCH request to the API endpoint with the updated data for the resource in the request body. PUT replaces the entire resource with the new data, while PATCH only updates the specified fields. The API then updates the resource and returns a response with the updated resource details.

Delete (DELETE)

This operation is used to remove an existing resource. The client sends a DELETE request to the API endpoint with the unique identifier of the resource to be deleted. The API then removes the resource and returns a response with a status code indicating success or failure.

Implementing CRUD in an API provides a simple and consistent interface for clients to interact with the underlying data. It is a common pattern used by many web APIs and is essential to building scalable and maintainable systems.

Note

Note : Run Playwright Test Scripts across 50+ browsers & devices. Try LambdaTest Now!

Why use Playwright for API Testing?

Playwright is useful for testing the user interface of applications that rely on APIs, such as single-page applications (SPAs) or progressive web apps (PWAs) that use APIs to fetch data or perform other operations in the background.

In Playwright API testing, we will use APIRequestContext class, which sends all kinds of HTTP(S) requests over the network. APIRequest class is used for creating APIRequestContext instances. API Request’s instance can be created by Playwright’s request.

By the end of this Playwright API testing tutorial, you will understand how API testing can be done.

Let’s quickly look into how Playwright can be set up for API testing in the next section of this Playwright API testing tutorial.

You can also subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorial around Selenium testing, Cypress testing, and more.

Setup Playwright for API Testing

Before we look into the actual implementation of Playwright API testing with examples, let's quickly set up the Playwright. Further, you can use it to create a working example code.

Step 1

To start with, you need to have Node.js installed on your machine. You can download it directly from the Node.js website and install it on your machine if you are not already using it. Once installed, check the version:


node -v

Playwright API Testing node -v

Step 2

Download and Install Visual Studio Code.

Step 3

Open your integrated terminal and run the following command.


mkdir playwright-api-testing

Step 4

Open the directory.


cd playwright-api-testing

Step 5

You can install Playwright using npm or yarn, and another way is by VS Code Extension.


Playwright API Testing install Playwright using npm or yarn

Source

In this Playwright API testing tutorial, we will install the Playwright using the npm command.

On your terminal, type:


npm init playwright@latest
Playwright API Testing npm init playwright@latestPlaywright API Testing npm init playwright@latest

Step 6

Let's install a few other packages we will use, like faker-js to generate test data, luxon to generate date, and rimraf to clean up the folder before each test run.


npm install --save-dev @faker-js/faker luxon rimraf
Playwright API Testing npm install --save-dev @faker-js/faker luxon rimraf

Once the installation of packages is complete, a folder node_module will be created with all the dependencies.

Step 7

By default .gitignore file will be created so that unwanted files are not committed to the code repository.


node_modules/
/test-results/
/playwright-report/
/playwright/.cache/
gitignore

Clone the Playwright API testing GitHub repository to follow the steps mentioned in this Playwright API testing tutorial.


LambdaTest

Let’s take a deep dive into the Playwright API testing example in the below section

...

Playwright API Testing Example

Let’s take a deep dive into Playwright API testing capabilities by creating a sample project to test the Restful-booker API. This site contains a list of API endpoints developed to test the different API operations like POST, GET, PUT, PATCH, and DELETE with status codes and responses, and it acts as a playground..

You can learn more about it through this blog on getting Response Status Code.

API Testing Approach

For easy understanding, we will create a simple Playwright API testing approach:

POST - We will look into three different ways to do a POST call.

  • Create a booking by providing static data.
  • Create a booking by providing data from the JSON file.
  • Create a booking by creating data at run time that looks realistic and unique. To achieve this, we will use the faker-js npm package, which will give you test data.

Response Validation - Assert the response by either comparing it with JSON data or matching it with data stored in the variable.

GET - Get the booking details by using some of the techniques of query param, without query param and path param. And assert the response for each type.

PUT - Update booking attributes for an existing resource and assert the response.

PATCH - Partially update an existing resource (not all attributes required) and assert the response.

DELETE - Finally, we will delete the booking and assert the response code.

Configuration

With little changes in the playwright.config.js file, you can start creating API tests.

Step 1:

Update baseURL in the playwright.config.js file so you can use it in each endpoint testing without specifying them.

baseURL: 'https://restful-booker.herokuapp.com'

Step 2

Keeping one browser enabled, you can disable all other browsers in the configuration file.


Playwright API Testing configuration file

POST Example

Below are three different ways to pass the data in the body while making a POST request. Let’s dive deep into it in this Playwright API testing tutorial section.

POST - Booking with static data

Sends HTTP(s) POST request and returns its response. In this Playwright API testing tutorial section, you will see how a POST call can be made by passing the static data in the body.

Implementation

To create a new booking, we will send a POST request to the /booking endpoint, and you need to provide the request body or payload in the request. Print the JSON response in the console to ensure you have received the entire response. As the endpoint will return a status code of 200 and ok as a status message, you should confirm this using an expect condition.

Also, you can verify if the response body has certain 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 have made a POST call to an endpoint /booking. Since it's a POST request, we must specify the body mentioned in the data.


/booking

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


Playwright API Testing expect condition

Also, we assert the response body to check the key and value. First, we store the JSON response data in a constant, then verify the firstname, lastname,totalprice, and depositpaid.


Playwright API Testing response body

Execution

Run the following command:


npx playwright test tests/01_post_static_data.spec.js
Playwright API Testing npx playwright test tests/01_post_static_data.spec.js

When we execute the request, it prints the response body as we have used console.log, then it asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report
Playwright API Testing npx playwright show-report

POST - Booking with static data specified in JSON file

In this section of the Playwright API testing tutorial, we will see how a POST call can be made by passing the static data in the body, which is mentioned in the JSON file.

Create a folder with the name test-data and then add a JSON file with the name booking-details.json. In the booking-details file, mention all the booking details you must pass while making a POST call.


{
    "firstname": "Jim",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2023-06-01",
        "checkout": "2023-061-15"
    },
    "additionalneeds": "Breakfast"
}

Implementation

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


// @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 made a POST call to an endpoint /booking. Since it's a POST request, we must specify the body mentioned in the data. However, we specify this data in the JSON file and then call this JSON data in the test. To achieve this, we first import the JSON data, store it in constant, and then call this in the test under data.


Playwright API Testing POST call to an endpoint /booking

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


Playwright API Testing status code 200

Also, we assert the response body to check the key and value.


response-body

Execution

Run the following command:


npx playwright test tests/02_post_static_json_data.spec.js
Playwright API Testing npx playwright test tests/02_post_static_json_data.spec.js

When we execute the request, it prints the response body as we have used console.log, then it does the assertions and marks the test as passed. It is the same as the previous one, but we have only optimized the test to use data from a JSON file.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report
Playwright API Testing npx playwright show-report

POST - Booking with dynamic data

In this Playwright API testing tutorial section, we will see how a POST call can be made by passing the dynamically generated data in the body.

You must import faker-js to create random test data and luxon to generate dates. Store the value in const and use it to build the JSON body.

Implementation

To create a new booking by passing the dynamically generated data in the body by faker-js and luxon library in the POST request to the /booking endpoint. The rest of the implementation of the code would be the same as mentioned in the previous approach.


// @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 made a POST call to an endpoint /booking. Since it's a POST request, we must specify the body mentioned in the data. However, we dynamically generate this data at the run time by using faker-js and luxon npm packages so that it will send a new set of data every time we request.


Playwright API Testing faker-js and luxon npm packages

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


Playwright API Testing status code 200

Also, we assert the response body to check the key and value.


Playwright API Testing response body to check the key and value

Execution

Run the following command:


npx playwright test tests/03_post_dynamic_data.spec.js
Playwright API Testing npx playwright test tests/03_post_dynamic_data.spec.js

When we execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed. It is the same as the previous one, but here, we have only optimized the test to use data from a faker-js library and will always generate a new data set.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report
Playwright API Testing npx playwright show-report

GET Example

Below are four different ways to make a GET request. Let’s look into this in detail in this section of this Playwright API testing tutorial.

GET all bookings IDs

Here, we will see how a GET call can be made to return the ids of all the bookings within the API.

Implementation

To get all bookings, we will use a GET request to the /booking endpoint and need not provide the request body or payload in this request.

You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you must verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


test('should be get all the booking details', async ({ request }) => {
    const response = await request.get("/booking");
    console.log(await response.json());
    expect(response.ok()).toBeTruthy();
    expect(response.status()).toBe(200);
});

Code Walkthrough

In this test, we made a GET call to an endpoint /booking. Since it's a GET request, we don’t need to specify the body and skip using data, and here we will get all the booking details.


playwright-api-testing-get-request

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


Playwright API Testing status code 200

Execution

Run the following command:


npx playwright test tests/04_get_all_booking_details.spec.js
Playwright API Testing npx playwright test tests/04_get_all_booking_details.spec.js

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.

HTML Report


marks-the-test-as-passed

GET specific booking IDs

In this Playwright API testing tutorial section, we will see how a GET call can be made to return a specific booking based on the booking ID provided.

Implementation

To get a specific booking, we will use a GET request to the /booking/:id endpoint, and we don’t need to provide the request body or payload in this request. You can print the complete JSON response in the console just to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you must verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


test('should be get specific booking details', async ({ request }) => {
const response = await request.get('/ booking / 1');
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});

Code Walkthrough

In this test, we made a GET call to an endpoint /booking/1. Since it's a GET request, we don’t need to specify the body and skip using data, and here we will get only one booking detail.


here-we-will-get-only-one-booking-detail

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


expect-condition-for-the-ok-message-and-status-code

Execution

Run the following command:


npx playwright test tests/05_get_specific_booking_details.spec.js
05_get_specific_booking_details

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

get-the-html-report-command

GET bookings by applying Filter example 1

In this section of this Playwright API testing tutorial, we will see how a GET call can be made to optionally add query strings to search and return a subset of booking IDs based on the filter string provided.

Implementation

To get the subset of booking, we will use a GET request to the /booking endpoint, and we don’t need to provide the request body or payload in this request.

You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


test('should be able to get subset of booking details using query parameters', async ({ request }) => {
const response = await request.get('/booking', {
params: {
firstname: "Susan",
lastname: "Jackson"
},
});
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});

Code Walkthrough

In this test, we made a GET call to an endpoint /booking. Since it's a GET request, we need not specify the body and skip using data. Here, we apply a filter on the data by using parameters in params, and it returns all the matching booking details.


filter-on-the-data-by-using-parameters

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


we-assert-by-using-expect-condition-for-the-ok-message

Execution

Run the following command:


npx playwright test tests/06_get_booking_details_query_param.spec.js

06_get_booking_details_query_param

When you execute the request, it prints the response body as we have used console.log, and then it asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

npx playwright show-report

GET bookings by applying Filter example 2

In this Playwright API testing tutorial section, we will see how a GET call can be made. This is another example where we can optionally add query strings to search and return a subset of booking IDs based on the filter string provided

Implementation

To get the subset of bookings, we will use a GET request to the /booking endpoint, and we don’t need to provide the request body or payload in this request.

You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and an ok as a status message, you need to verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


test('should be able to get subset of booking details using query parameters - checkin date example', async ({ request }) => {
const response = await request.get('/booking', {
params: {
checkin: "2021-01-15",
checkout: "2023-03-25"
},
});
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
});

Code Walkthrough

This is another test where we make a GET call to an endpoint /booking. Since it's a GET request, we don’t need to specify the body and skip using data. Here, we apply a filter of check-in and check-out dates by using parameters in params, and it returns all the matching booking details.


make-a-get-call-to-an-endpoint

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


we-will-receive-the-response

Execution

Run the following command:


npx playwright test tests/07_get_booking_details_query_param.spec.js

07_get_booking_details_query_param

When you execute the request, it prints the response body as we have used console.log and asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

npx-playwright-report

PUT - Updating a resource

It is used to update the current booking details. In this section of the Playwright API testing tutorial, we need to specify a fully updated body.

Implementation

To update the current booking details, we will use a PUT request to the /booking/1 endpoint, and we need to provide the request body or payload in the request, which needs to be updated.

You can print the complete JSON response in the console to check what we receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


var token


test('should be able to update the booking details', async ({ request }) => {


// Create a Token which will be used in PUT request


const response = await request.post('/auth', {
data: {
"username": "admin",
"password": "password123"
}
});
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const responseBody = await response.json();
token = responseBody.token;
console.log("New Token is: " + token);


// PUT
const updateRequest = await request.put('/booking/1', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': 'token=$'{token}',
},
data: {
"firstname": "Jim",
"lastname": "Brown",
"totalprice": 111,
"depositpaid": true,
"bookingdates": {
"checkin": "2023-06-01",
"checkout": "2023-06-15"
},
"additionalneeds": "Breakfast"
}
});
console.log(await updateRequest.json());
expect(updateRequest.ok()).toBeTruthy();
expect(updateRequest.status()).toBe(200);
const updatedResponseBody = await updateRequest.json()
expect(updatedResponseBody).toHaveProperty("firstname", "Jim");
expect(updatedResponseBody).toHaveProperty("lastname", "Brown");
expect(updatedResponseBody).toHaveProperty("totalprice", 111);
expect(updatedResponseBody).toHaveProperty("depositpaid", true);
});

Code Walkthrough

In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the PUT request. The username and password need to be specified in the body mentioned in the data.


post-call-to-an-endpoint

Once the request is completed, we receive the response. Here, we store the token in a variable.


store-the-token-in-a-variable

Now we make a PUT call to an endpoint /booking/1 and pass the token in the header and body in the data.


put-call-to-an-endpoint

We will receive the response and need to make an assert by using expect condition for the ok message and status code 200.


response-and-need-to-make-an-assert

Also, we will assert the response body to check the key and value.


we-will-assert-the-response-body-to-check

Execution

Run the following command:


npx playwright test tests/08_update_booking_details.spec.js

08_update_booking_details

When you execute the request, it prints the response body as we have used console.log, a newly generated token, and then it prints another response in the console, which is for the PUT request, and then it asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

you-can-run

PATCH - Updating a resource partially

In this Playwright API testing tutorial section, we will see how to use PATCH to update the current booking with a partial payload.

Implementation

To update the booking with the partial payload, we will use a PATCH request to the /booking/1 endpoint, and we need to provide the partial request body or payload, which needs to be updated. You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, we need to verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


var token


test('should be able to partial update the booking details', async ({ request }) => {


// Create a Token which will be used in PATCH request


const response = await request.post('/auth', {
data: {
"username": "admin",
"password": "password123"
}
});
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const responseBody = await response.json();
token = responseBody.token;
console.log("New Token is: " + token);


// PATCH


const partialUpdateRequest = await request.patch('/booking/1', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': 'token=${token}'
},
data: {
"firstname": "Sim",
"lastname": "Son",
"totalprice": 333,
"depositpaid": false
}
});
console.log(await partialUpdateRequest.json());
expect(partialUpdateRequest.ok()).toBeTruthy();
expect(partialUpdateRequest.status()).toBe(200);
const partialUpdatedResponseBody = await partialUpdateRequest.json()
expect(partialUpdatedResponseBody).toHaveProperty("firstname", "Sim");
expect(partialUpdatedResponseBody).toHaveProperty("lastname", "Son");
expect(partialUpdatedResponseBody).toHaveProperty("totalprice", 333);
expect(partialUpdatedResponseBody).toHaveProperty("depositpaid", false);
});

Code Walkthrough

In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the PATCH request. The username and password need to be specified in the body, which is mentioned in the data.


passed-with-the-patch-request

Once the request is completed, we will receive the response. Here, we will store the token in a variable.


here-we-will-store-the-token

Now we will make a PATCH call to an endpoint /booking/1 and pass the token in the header and body in the data.


token-in-header

We will receive the response and assert by making use of expect condition for the ok message and status code 200.


we-will-receive-the-response-and-assert-by-making-use-of-expect

Also, we will assert the response body to check the key and value.


check-key-value

Execution

Run the following command:


npx playwright test tests/09_partial_update_booking_details.spec.js

09_partial_update_booking_details

When you execute the request, it prints the response body as we have used console.log, a newly generated token, and then it prints another response in the console, which is for the PATCH request, and then it asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

Playwright API Testing npx playwright show-report09

DELETE

It is used to delete the resource. In this section of the Playwright API testing tutorial, we will delete the booking details.

Implementation

To delete a booking, we will use the DELETE request to the /booking/1 endpoint, and we don’t need to provide the request body or payload in this request.

You can print the complete JSON response in the console to check what you receive as a complete response. Since this endpoint will give you 200 status codes and ok as a status message, you need to verify it with the expect condition.


// @ts-check
const { test, expect } = require('@playwright/test');


var token


test('should be able to delete the booking details', async ({ request }) => {


// Create a Token which will be used in DELETE request


const response = await request.post('/ auth', {
data: {
"username": "admin",
"password": "password123"
}
});
console.log(await response.json());
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const responseBody = await response.json();
token = responseBody.token;
console.log("New Token is: " + token);


// DELETE


const deleteRequest = await request.delete('/booking/1', {
headers: {
'Content-Type': 'application/json',
'Cookie': 'token=${token}'
}
});
expect(deleteRequest.status()).toEqual(201);
expect(deleteRequest.statusText()).toBe('Created');
});

Code Walkthrough

In this test, we make a POST call to an endpoint /auth to generate the token, which needs to be passed with the DELETE request. The username and password need to be specified in the body, which is mentioned in the data.


need-specified

Once the request is completed, we will receive the response. Here, we will store the token in a variable.


store

Now we will make a DELETE call to an endpoint /booking/1 and pass the token in the header, and the body is not required.


will-make-a-delete-call

We will receive the response and assert by using expect condition for Created message and status code 201.


created-message-and-status-code

Execution

Run the following command:


npx playwright test tests/10_delete_booking_details.spec.js

10_delete_booking_details

When you execute the request, it prints the response body as we have used console.log and then asserts and marks the test as passed.

HTML Report

To get the HTML report, you can run the command:


npx playwright show-report

npx-playwright-show-repo

However, you can leverage the true potential of Playwright automation on cloud-based digital experience testing like LambdaTest. Cloud grid like LambdaTest offers an online browser farm with 3000+ real browsers and OS to accelerate your automation testing with Playwright. This can help improve your overall test coverage by running tests on different combinations of browsers and operating systems using the same test scripts.

...

Conclusion

Playwright is a powerful tool for automating web application testing and can also be used for API testing. Playwright provides a simple and easy-to-use API that allows you to make HTTP requests, perform assertions, and parse responses. By now, you have a fair understanding of Playwright requests, and how Playwright API testing can be done with working examples for POST, GET, PUT, PATCH, and DELETE requests.

Frequently asked questions

  • General ...
  • LambdaTest related FAQs
Can Playwright be used for API testing?
Playwright is primarily designed for UI testing of web applications, but it can also be used for API testing to some extent. The Playwright does provide some basic capabilities for API testing, such as making HTTP requests and handling responses.
How to write test scripts for API?
When writing test scripts for API testing, you typically follow a few basic steps: 1. Define the API endpoints and parameters to be tested. 2. Set up the test environment. 3. Write the test cases. 4. Implement the test scripts. 5. Run the tests. 6. Monitor and maintain the tests. By following these steps, you can create effective test scripts for API testing that help ensure the reliability and accuracy of your APIs.

Did you find this page helpful?

Helpful

NotHelpful

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud