How to test APIs in Playwright
Playwright also provides a powerful API for testing web services and APIs directly. You can use the request
object to send HTTP requests and verify the responses. Here's how to test an API in Playwright:
Example
Let's say you want to test a simple REST API endpoint that returns a list of users.
Sample REST API
Here is a sample endpoint you might be testing: https://jsonplaceholder.typicode.com/users
.
Playwright Script to Test API
Here's how you can write a Playwright script to test the API:
const { request } = require('playwright');
(async () => {
// Create a new API request context
const apiRequest = await request.newContext();
// Send a GET request to the API endpoint
const response = await apiRequest.get('https://jsonplaceholder.typicode.com/users');
// Check if the request was successful
if (response.ok()) {
console.log('Request succeeded!');
} else {
console.log('Request failed.');
}
// Print the status code
console.log('Status Code:', response.status());
// Parse and print the response body
const responseBody = await response.json();
console.log('Response Body:', responseBody);
// Close the request context
await apiRequest.dispose();
})();
Explanation
-
Create a New API Request Context:
const apiRequest = await request.newContext();
- This creates a new API request context, which you can use to send HTTP requests.
-
Send a GET Request:
const response = await apiRequest.get('https://jsonplaceholder.typicode.com/users');
- This sends a GET request to the specified API endpoint.
-
Check the Request Status:
response.ok()
checks if the response status is in the range of 200-299.response.status()
returns the status code of the response.
-
Parse and Print the Response Body:
const responseBody = await response.json();
parses the response body as JSON.console.log('Response Body:', responseBody);
prints the parsed response body.
-
Close the Request Context:
await apiRequest.dispose();
- This disposes of the API request context.
Running the Script
To run the script, save it to a file (e.g., api_test.js
) and execute it using Node.js:
node api_test.js
Additional Features
- Sending POST, PUT, DELETE Requests: Playwright allows you to send other types of requests (POST, PUT, DELETE, etc.) using
apiRequest.post()
,apiRequest.put()
,apiRequest.delete()
, etc. - Setting Headers: You can set custom headers for your requests using the
headers
option. - Sending JSON Data: You can send JSON data in the request body by using the
data
option and setting the appropriateContent-Type
header.
Here is an example of sending a POST request with JSON data:
const { request } = require('playwright');
(async () => {
const apiRequest = await request.newContext();
const response = await apiRequest.post('https://jsonplaceholder.typicode.com/posts', {
data: {
title: 'foo',
body: 'bar',
userId: 1
},
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok()) {
console.log('POST request succeeded!');
} else {
console.log('POST request failed.');
}
console.log('Status Code:', response.status());
const responseBody = await response.json();
console.log('Response Body:', responseBody);
await apiRequest.dispose();
})();
This script demonstrates how to send a POST request with JSON data to an API endpoint.