API Testing with Playwright
Playwright is primarily known for its browser automation capabilities, it can also be used for API testing. Here’s a simple example of how you can perform API testing using Playwright:
const { test, expect } = require('@playwright/test');
const fetch = require('node-fetch');
test.describe('API Testing with Playwright', () => {
let authToken;
test.beforeEach(async () => {
// Simulate authentication and obtain an authentication token
const response = await fetch('https://jsonplaceholder.typicode.com/authenticate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username: 'test_user', password: 'test_password' }),
});
const jsonData = await response.json();
authToken = jsonData.token;
});
test('GET Request with Authentication', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
Authorization: `Bearer ${authToken}`,
},
});
// Verify the status code
expect(response.status).toBe(200);
// Verify response headers
expect(response.headers.get('Content-Type')).toBe('application/json; charset=utf-8');
});
test('PUT Request', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ title: 'Updated Title', body: 'Updated Body' }),
});
// Verify the status code
expect(response.status).toBe(200);
// Verify response data
const jsonData = await response.json();
expect(jsonData.title).toBe('Updated Title');
expect(jsonData.body).toBe('Updated Body');
});
test('DELETE Request', async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE',
});
// Verify the status code
expect(response.status).toBe(200);
});
});Get Navya PS’s stories in your inbox
Join Medium for free to get updates from this writer.
In this example:
- We use
node-fetchto make HTTP requests to the JSONPlaceholder API, which provides a fake online REST API for testing and prototyping. - In the first test, we send a GET request to retrieve a specific post (
https://jsonplaceholder.typicode.com/posts/1). We then verify the status code and the response data. - In the second test, we send a POST request to create a new post (
https://jsonplaceholder.typicode.com/posts). We provide the request body in JSON format and set theContent-Typeheader accordingly. After receiving the response, we verify the status code and the response data.





