API Test
HTTP and GraphQL endpoint testingEdit
Validate REST APIs and GraphQL endpoints with HTTP requests and response assertions. API tests use Playwright's request context for reliable HTTP testing.
Example
import { expect, test } from '@playwright/test';
const API_URL = 'https://jsonplaceholder.typicode.com';
test.describe('API health check', () => {
test('health endpoint responds with expected payload', async ({ request }) => {
// Send GET request
const response = await request.get(API_URL + '/posts/1');
// Basic status checks
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
expect(response.headers()['content-type']).toContain('application/json');
// Validate JSON structure
const body = await response.json();
expect(body).toMatchObject({ id: 1 });
expect(typeof body.title).toBe('string');
});
});Create Test
- Go to Create → API Test
- Write your test script
- Click Run to validate
- Save when passing
HTTP Methods
const API_URL = 'https://jsonplaceholder.typicode.com';
// GET - Retrieve resource
const getResponse = await request.get(API_URL + '/posts/1');
// POST - Create resource
const postResponse = await request.post(API_URL + '/posts', {
data: { title: 'New Post', body: 'Content', userId: 1 }
});
// PUT - Update resource
const putResponse = await request.put(API_URL + '/posts/1', {
data: { title: 'Updated', body: 'New content', userId: 1 }
});
// DELETE - Remove resource
const deleteResponse = await request.delete(API_URL + '/posts/1');Assertions
// Status code
expect(response.status()).toBe(200);
expect(response.ok()).toBeTruthy();
// JSON body
const data = await response.json();
expect(data.id).toBeDefined();
expect(data).toMatchObject({ id: 1 });
expect(typeof data.title).toBe('string');
// Headers
expect(response.headers()['content-type']).toContain('application/json');Using Variables
const baseUrl = getVariable('API_BASE_URL');
const apiKey = getSecret('API_KEY');
const response = await request.get(`${baseUrl}/users`, {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
expect(response.ok()).toBeTruthy();Tips
- Use
getSecret()for API keys (execution output is redacted) - Set appropriate timeouts for slow endpoints
- Validate response structure, not just status codes
- Use Playwright's
requestcontext instead offetchfor better integration
Learn More
- Playwright API Testing — Complete API testing guide
- Playwright Request Context — API reference