TESTEVERYTHING

Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Tuesday, 13 October 2026

Steps for API Testing in Playwright: A Complete Step-by-Step Guide

 Playwright guide

Steps for API Testing in Playwright

A complete, practical walkthrough for building fast, reliable API tests—from your first request to authenticated CRUD flows and CI-ready reporting.

Meta description
Learn how to perform API testing in Playwright with setup, HTTP methods, assertions, authentication, fixtures, and best practices for reliable automated tests.

Introduction

Modern applications are built on APIs, and ensuring those APIs work correctly is just as important as testing the UI. While Playwright is widely known as a powerful end-to-end browser automation tool, it also ships with a built-in APIRequestContext for API testing.

You can validate backend services, mock data for UI tests, or build a full API test suite—all without installing a separate HTTP client library. This guide walks through the complete process, from installation to robust, production-ready test suites.

What is API testing?

API testing verifies that an application programming interface meets expectations for functionality, reliability, performance, and security. Instead of interacting with a UI, API tests send requests directly to REST, GraphQL, or other endpoints and validate status codes, headers, response bodies, and timing.

Why use Playwright for API testing?

Playwright includes a dedicated request context that lets you:

  • Send GET, POST, PUT, PATCH, and DELETE requests without a browser.
  • Reuse authentication state between API calls and UI tests.
  • Combine API setup and teardown with UI tests in one file.
  • Run requests in parallel with Playwright's test runner.
  • Use built-in retries, timeouts, tracing, and reporting.

Step-by-step: API testing in Playwright

Prerequisites

  • Node.js v16 or later
  • Basic JavaScript or TypeScript knowledge
  • A code editor (VS Code recommended)
  • An API endpoint to test

Step 1: Install Playwright

Create a new project, or install the test runner in an existing project:

npm init playwright@latest
# or
npm install -D @playwright/test

Step 2: Understand the request fixture

The built-in fixture provides an APIRequestContext. No browser or page is needed.

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

test('get list of users', async ({ request }) => {
  const response = await request.get(
    'https://jsonplaceholder.typicode.com/users'
  );
  expect(response.status()).toBe(200);
});

Step 3: Write your first API test

Create tests/api.spec.ts and assert both the response and its data:

const BASE_URL = 'https://jsonplaceholder.typicode.com';

test('GET /users returns a list', async ({ request }) => {
  const response = await request.get(`${BASE_URL}/users`);
  expect(response.ok()).toBeTruthy();

  const users = await response.json();
  expect(Array.isArray(users)).toBeTruthy();
  expect(users.length).toBeGreaterThan(0);
});

Run the test with npx playwright test.

Step 4: Handle HTTP methods

The request object exposes all common HTTP verbs:

// GET
await request.get(`${BASE_URL}/posts/1`);

// POST
await request.post(`${BASE_URL}/posts`, {
  data: { title: 'Playwright API Testing', body: 'Learning APIs', userId: 1 }
});

// PUT
await request.put(`${BASE_URL}/posts/1`, {
  data: { id: 1, title: 'Updated Title', body: 'Updated body', userId: 1 }
});

// DELETE
await request.delete(`${BASE_URL}/posts/1`);

Step 5: Validate responses with assertions

Validate status codes, headers, and body content together for expressive, useful failures.

const response = await request.post(`${BASE_URL}/posts`, {
  data: { title: 'foo', body: 'bar', userId: 1 },
});

expect(response.status()).toBe(201);
expect(response.headers()['content-type']).toContain('application/json');

const body = await response.json();
expect(body.title).toBe('foo');
expect(body).toHaveProperty('id');

Step 6: Handle authentication

Set default headers on a context so every request includes the required token:

const apiContext = await request.newContext({
  baseURL: 'https://api.example.com',
  extraHTTPHeaders: {
    Authorization: `Bearer ${process.env.API_TOKEN}`,
  },
});

const response = await apiContext.get('/protected-resource');
expect(response.status()).toBe(200);
await apiContext.dispose();
Security note: Keep tokens and credentials in environment variables or your CI secret store—not in test files.

Step 7: Use fixtures and custom contexts

For larger suites, create an authenticated context once and dispose of it after use:

type MyFixtures = { apiContext: APIRequestContext };

export const test = base.extend({
  apiContext: async ({}, use) => {
    const context = await request.newContext({
      baseURL: 'https://api.example.com',
      extraHTTPHeaders: {
        Authorization: `Bearer ${process.env.API_TOKEN}`,
      },
    });
    await use(context);
    await context.dispose();
  },
});

Step 8: Chain requests

Model real workflows by creating, updating, verifying, and deleting a resource:

const createRes = await request.post(`${BASE_URL}/posts`, {
  data: { title: 'New Post', body: 'Content', userId: 1 },
});
const { id } = await createRes.json();

const updateRes = await request.put(`${BASE_URL}/posts/${id}`, {
  data: { title: 'Updated Post' },
});
expect(updateRes.status()).toBe(200);

const getRes = await request.get(`${BASE_URL}/posts/${id}`);
expect(getRes.status()).toBe(200);

const deleteRes = await request.delete(`${BASE_URL}/posts/${id}`);
expect(deleteRes.status()).toBe(200);

Step 9: Test errors and negative cases

Do not test only the happy path. Check invalid input, missing authentication, and unknown resources:

test('returns 404 for a missing resource', async ({ request }) => {
  const response = await request.get(`${BASE_URL}/posts/999999`);
  expect(response.status()).toBe(404);
});

test('returns 401 without authentication', async ({ request }) => {
  const response = await request.get('https://api.example.com/protected');
  expect(response.status()).toBe(401);
});

Step 10: Generate and review reports

Playwright's HTML reporter works for API tests too:

npx playwright test
npx playwright show-report

Configure multiple reporters in playwright.config.ts:

export default {
  reporter: [['html'], ['junit', { outputFile: 'results.xml' }]],
};

Best practices

  • Isolate API and UI tests with separate project configurations when useful.
  • Use environment variables for URLs, tokens, and credentials.
  • Create reusable fixtures for authentication and setup/teardown.
  • Validate schemas with libraries such as zod or ajv.
  • Clean up records created during tests.
  • Run independent API tests in parallel in CI.
  • Use API calls to set up data quickly before UI assertions.

Common pitfalls to avoid

  • Forgetting dispose() on manually created request contexts.
  • Hardcoding tokens or secrets in test files.
  • Parsing a body without first checking response.ok().
  • Relying only on status codes instead of validating content.
  • Running tests against production instead of a dedicated test environment.

Conclusion

Playwright's built-in API capabilities provide an all-in-one way to validate both the UI and backend. Start with one GET request, then expand into CRUD flows, authentication, schema checks, and negative scenarios. You will quickly have a maintainable regression suite that catches issues before production.

Ready to get started?
Set up a Playwright project, choose one endpoint, and write your first automated test today.

FAQs

Do I need a browser to run API tests?No. APIRequestContext sends HTTP requests directly, making tests fast and lightweight.
Can I combine API and UI testing?Yes. Use API calls for quick data setup or authentication, then switch to browser-based testing in the same test file.
Does Playwright support GraphQL?Yes. Test GraphQL endpoints with request.post() and place the query or mutation in the JSON payload.
How do I handle flaky API tests?Use retries, isolate test data, and avoid depending on unstable external services.
Can Playwright validate JSON schemas?Integrate ajv or zod alongside Playwright assertions for deeper schema validation.

Friday, 4 September 2026

How AI is Finally Fixing Our Worst API Testing Nightmares

Beyond Broken Endpoints: How AI is Finally Fixing Our Worst API Testing Nightmares

Beyond Broken Endpoints: How AI is Finally Fixing Our Worst API Testing Nightmares

If you’ve ever wanted to pull your hair out over a failing POST /users test at 4:45 PM on a Friday, you are in good company. API automation testing is supposed to be the "easy" part of the testing pyramid. No complex UI locators to break, no browser rendering issues to debug, just clean JSON payloads and predictable status codes. Except, it’s rarely that simple. In the real world, API automation is a constant battle against dynamic data, shifting schemas, and brittle test suites. But things are changing. AI is quietly stepping in to take over the tedious, repetitive parts of the job, turning API testing from a maintenance headache into something almost… effortless. Let’s look at the biggest pain points in API testing today, and how AI-powered tools (both free and paid) are solving them.


The Real-World Obstacles: Why API Testing Breaks

Before we look at the fixes, let’s be honest about what makes API automation so exhausting.

1. Schema Drift (The "Who Changed the JSON?" Problem)

You write a flawless suite of tests. Overnight, a developer updates a microservice and changes a response key from user_id to userId. Suddenly, fifty tests fail. The API still works, but your tests are dead in the water.

2. The Dynamic Data & Auth Token Chase

Managing dynamic states—like generating a fresh OAuth token, passing it to a helper function, grabbing an ID from a GET response, and feeding it into a DELETE request—requires a lot of boilerplate code. If one step timing-out or returning slightly different data occurs, the whole chain collapses.

3. Assertion Fatigue

Writing assertions is boring. To properly test an endpoint, you need to verify status codes, headers, response times, data types, and specific value ranges. Writing these manually for dozens of endpoints is a recipe for developer burnout, which often leads to cutting corners (e.g., only asserting status === 200 and calling it a day).


How AI Actually Helps (Without the Hype)

AI isn't going to replace the human understanding of business logic, but it is incredibly good at handling the heavy lifting of API testing.

  • Self-Healing Tests: When a field name changes slightly, AI can analyze the historical context of the payload, realize that userId is the same as the old user_id, update the test logic on the fly, and flag it for your review instead of failing the build.
  • Auto-Generating Payloads: Instead of manually writing mock JSON objects, you can feed an AI your API schema, and it will automatically generate edge-case payloads (like empty strings, SQL injection attempts, and massive integers) to stress-test your endpoints.
  • Automated Assertions: Instead of writing twenty lines of assertion code, you can ask an AI assistant to analyze a sample response and write the assertion block for you in seconds.

The Toolbox: Paid vs. Free AI Testing Tools

If you want to start leveraging AI for your API testing, you don't need a massive budget. Here is a breakdown of the best tools currently available.

The Paid Heavy Hitters

These platforms are built for teams and enterprise workflows, offering robust, out-of-the-box AI integrations.

1. Postman (with Postbot)

  • What it is: Postman is already the industry standard for API development, but its built-in AI assistant, Postbot, takes it to the next level.
  • How it helps: You can highlight a response payload and tell Postbot in plain English: "Write tests to verify all fields are present and response time is under 200ms." It writes the JavaScript code instantly. It can also generate mock data and fix broken test scripts on the fly.
  • Pricing: Postbot is available as an add-on to Postman plans (starting at around $9/user/month), though there is a limited free tier to try it out.

2. Katalon Platform

  • What it is: A comprehensive quality management platform that combines UI, mobile, and API testing.
  • How it helps: Katalon uses AI to auto-generate test code from your API documentation (like Swagger/OpenAPI specs) and offers self-healing capabilities that prevent test suites from breaking when minor changes occur in API responses.
  • Pricing: Free tier available for basic use; premium plans start at $167/month for professional teams.

The Free and Open-Source Game Changers

If you prefer open-source software or are working with zero budget, these tools are incredibly powerful.

1. Keploy

  • What it is: An open-source, developer-focused API testing tool that uses AI/ML to automate the entire test generation process.
  • How it helps: Keploy runs in the background while you run your application. It records actual API traffic (including database calls and external dependencies) and automatically generates test cases and mocks. It completely bypasses the need to write manual boilerplate API test code.
  • Pricing: 100% Free and Open Source.

2. Local AI + Playwright / REST Assured (The DIY Route)

  • What it is: Running a local, open-source Large Language Model (like Llama 3 via Ollama) directly on your machine.
  • How it helps: If your company has strict data privacy rules and won't let you send API payloads to external servers (like OpenAI), you can use a local LLM. You can feed your Swagger file or API controller code into the local model and ask it to: "Generate a complete suite of Playwright API tests covering positive, negative, and boundary cases."
  • Pricing: Completely free.

The Verdict: Don't Code Harder, Code Smarter

API testing doesn't have to be a repetitive cycle of fixing broken assertions and updating outdated mocks. The smartest approach today is a hybrid one. Let AI write the boilerplate code, generate your edge-case payloads, and draft your assertions. Save your brainpower for the high-level architecture: designing the integration flows, understanding the security implications, and ensuring the business logic actually makes sense.

Have you started using AI in your API testing pipeline yet? What’s your go-to tool? Let me know in the comments below!

Translate







Tweet