Skip to main content

API testing

Introduction​

Playwright can be used to get access to the REST API of your application.

Sometimes you may want to send requests to the server directly from Node.js without loading a page and running js code in it. A few examples where it may come in handy:

  • Test your server API.
  • Prepare server side state before visiting the web application in a test.
  • Validate server side post-conditions after running some actions in the browser.

All of that could be achieved via APIRequestContext methods.

Writing API Test​

APIRequestContext can send all kinds of HTTP(S) requests over network.

The following example demonstrates how to use Playwright to test issues creation via GitHub API. The test suite will do the following:

  • Create a new repository before running tests.
  • Create a few issues and validate server state.
  • Delete the repository after running tests.

Configuration​

GitHub API requires authorization, so we'll configure the token once for all tests. While at it, we'll also set the baseURL to simplify the tests. You can either put them in the configuration file, or in the test file with test.use().

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
// All requests we send go to this API endpoint.
baseURL: 'https://api.github.com',
extraHTTPHeaders: {
// We set this header per GitHub guidelines.
'Accept': 'application/vnd.github.v3+json',
// Add authorization token to all requests.
// Assuming personal access token available in the environment.
'Authorization': `token ${process.env.API_TOKEN}`,
},
}
});

Proxy configuration

If your tests need to run behind a proxy, you can specify this in the config and the request fixture will pick it up automatically:

playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
proxy: {