Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
TestingintermediateNew

Playwright API Testing

Share

Write API tests with Playwright's request context

Works with OpenClaude

You are a QA engineer writing API tests using Playwright's request context API. The user wants to write automated API tests that verify endpoints, handle authentication, validate responses, and manage test data lifecycle.

What to check first

  • Run npm list @playwright/test to confirm Playwright is installed (v1.40+)
  • Verify your API base URL and authentication requirements (API key, token, OAuth)
  • Check if your API requires specific headers (Content-Type, User-Agent, Authorization)

Steps

  1. Create a test file using Playwright's APIRequestContext by importing test and expect from @playwright/test
  2. Use the request fixture (automatically provided) to create API requests without a browser context
  3. Set the base URL in playwright.config.ts using webServer.url or pass it directly in requests
  4. Chain .post(), .get(), .put(), .delete() methods on the request object with endpoint paths
  5. Add authentication headers via the request.post(url, { headers: { Authorization: 'Bearer token' } }) option
  6. Parse JSON responses with .json() method and validate structure with expect() assertions
  7. Use test.beforeAll() to set up test data (create resources) and test.afterAll() to clean up (delete resources)
  8. Extract IDs from creation responses and pass them to subsequent tests using shared test context

Code

import { test, expect } from '@playwright/test';

const API_BASE_URL = 'https://api.example.com';
const API_KEY = process.env.API_KEY || 'test-key';

test.describe('User API Tests', () => {
  let userId: string;
  let authToken: string;

  test.beforeAll(async ({ playwright }) => {
    // Optional: Get auth token if needed
    authToken = `Bearer ${API_KEY}`;
  });

  test('POST /users - Create a new user', async ({ request }) => {
    const response = await request.post(`${API_BASE_URL}/users`, {
      headers: {
        'Authorization': authToken,
        'Content-Type': 'application/json',
      },
      data: {
        name: 'John Doe',
        email: 'john@example.com',
        role: 'admin',
      },
    });

    expect(response.status()).toBe(201);
    const body = await response.json();
    expect(body).toHaveProperty('id');
    expect(body.email).toBe('john@example.com');
    userId = body.id; // Store for use in other tests
  });

  test('GET /users/:id - Retrieve created user', async ({ request }) => {
    const response = await request.get(
      `${API_BASE_URL}/users/${userId}`,
      {
        headers: { 'Authorization': authToken },
      }
    );

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryTesting
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
playwrightapi-testinge2e

Install command:

curl -o ~/.claude/skills/playwright-api-testing.md https://clskills.in/skills/testing/playwright-api-testing.md

Related Testing Skills

Other Claude Code skills in the same category — free to download.

Want a Testing skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.