---
name: integrate-playwright-client
description: >
  Use the generated playwright-mode client for E2E API testing in CI/CD.
  Covers peer dependencies (zod, @playwright/test), instantiation from
  Playwright APIRequestContext fixture, calling async operation methods,
  ApiResponse<T> assertions, and Zod-validated response bodies. Load when
  importing or using a generated playwright-mode client file in tests.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/playwright/index.ts"
  - "bazo/openapi-client-generator:src/modes/playwright/query.ts"
  - "bazo/openapi-client-generator:src/modes/playwright/mutation.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate Playwright Client

## Setup

Install peer dependencies:

```bash
npm install -D zod @playwright/test
```

The generated validators are Zod 4, so `zod` must be >= 4.

Use the generated client in a Playwright test:

```typescript
import { test, expect } from "@playwright/test";
import { TestApi } from "./generated/TestApi";

test("list tasks returns 200", async ({ request }) => {
  const api = new TestApi(request);
  const result = await api.listTasks({ page: 1, limit: 10 });
  expect(result.status).toBe(200);
  expect(result.data.items.length).toBeGreaterThan(0);
});
```

The constructor takes a single argument: Playwright's `APIRequestContext`, available from the `{ request }` test fixture.

## Core Patterns

### Query operation with parameters

```typescript
test("get task by id", async ({ request }) => {
  const api = new TestApi(request);
  const result = await api.getTask({ taskId: "123" });
  expect(result.status).toBe(200);
  expect(result.data.id).toBe("123");
});
```

All operations are async methods on the client class. Path, query, and header parameters are passed as a single params object.
Path parameters are percent-encoded for you (pass raw values). An array query parameter declared
`explode: false` is sent once, comma-joined (`include=a,b`); an empty one is left out.

### Mutation operation with request body

```typescript
test("create a task", async ({ request }) => {
  const api = new TestApi(request);
  const result = await api.createTask({
    body: { title: "Test task", status: "todo" },
  });
  expect(result.status).toBe(201);
  expect(result.data.title).toBe("Test task");
});
```

Mutations accept a `body` property in the params object. The body is Zod-validated before sending.

### Assert on ApiResponse structure

```typescript
test("check response shape", async ({ request }) => {
  const api = new TestApi(request);
  const result = await api.healthCheck();
  expect(result).toEqual(
    expect.objectContaining({
      status: 200,
      data: expect.any(Object),
      headers: expect.any(Object),
      url: expect.any(String),
    }),
  );
});
```

Every operation returns `ApiResponse<T>` with `data`, `status`, `headers`, and `url`. **Every documented body is validated strictly; a mismatch throws `ResponseValidationError` carrying the status.** That holds for successes and errors alike — an exact status (200, 401, 404, 500…), a `4XX`-style range or `default`. A body that does not match its schema (the wrong shape, a key a strict schema does not declare, a proxy's HTML page on a documented status) is a contract violation: the call rejects with a `ResponseValidationError` that has `status`, `headers`, `url`, the raw `body`, and the ZodError (or, for a non-JSON body, the JSON SyntaxError) as `cause`; its message reads `Response to GET /tasks/{taskId} (500) does not match the contract`. A status is matched exact → range → `default` (Go mode's precedence); a status none of them documents resolves `data: null` — there is nothing to validate it against. So a 500 page from a proxy on a documented 500 fails the test with a `ResponseValidationError` that names the status and URL — not a bare ZodError.

## File uploads (multipart)

An operation whose request body is `multipart/form-data` takes `BinaryInput` (`Blob | File`) for each `format: binary` field — the client builds the request's `FormData` for you. Note this is **narrower than full mode's**, which also accepts React Native's `{ uri, name, type }` file part: a Playwright client only ever runs in Node, where that shape means nothing and where this mode's raw-binary path needs `body.arrayBuffer()`.

```typescript
import { readFile } from "node:fs/promises";

test("upload a task attachment", async ({ request }) => {
  const api = new TestApi(request);
  const bytes = await readFile("./fixtures/invoice.pdf");
  const result = await api.uploadTaskAttachment({
    taskId: "42",
    body: {
      file: new File([bytes], "invoice.pdf", { type: "application/pdf" }),
      description: "Q3 invoice",
    },
  });
  expect(result.status).toBe(201);
});
```

Field encoding rules match full mode: scalars become one part; arrays of scalars become repeated parts under the same field name; objects and arrays of objects become a single part carrying their JSON as a plain **text field** (no filename, no `Content-Type: application/json` — `FormData` cannot set one without turning the part into a file); `undefined`/`null` fields are omitted. A field whose spec name is not a valid JS identifier (`file-name`) keeps that exact wire name. A composed (`allOf`) body contributes every branch's properties. A `oneOf`/`anyOf` body is typed as the union of its branches and sends the fields of whichever branch you actually pass — the client reads the value **you** passed at request time (not the Zod-parsed copy: `z.union` returns the first option that validates, which would truncate a body built from a wider branch, and strip an all-optional branch's sibling to nothing), so the parts are identical to the ones the swift, kotlin and php clients send for the same branch, wire names, repeated array parts and single JSON parts included. Validation still runs; it just no longer decides the wire form. Only wire names the spec declares on some branch are sent, so an object typed wider than the branch does not leak its extra properties into the request. A union body's branches must each have a field set of their own: if any branch has none — a primitive, an array, or an object with no declared properties — the whole body falls back to sending no parts at all, in every mode alike. The same fallback applies to a union the Kotlin generator cannot express as a sealed class (most reachably when a schema named `<UnionName>Serializer` already exists, but also when the union carries a sibling `enum` or is an `anyOf` of one type plus `null`), because Kotlin then has no sum type to dispatch on and the five modes only stay in step by all sending nothing. A `oneOf`/`anyOf` **urlencoded** body dispatches on the branch in exactly the same way, sending that branch's own fields as `k=v` pairs — an array field as repeated keys, an object-valued field as one JSON-encoded value — and it takes the same fallback, with the same explanatory comment, only when the branches cannot be described. A SINGLE-variant `anyOf` (`anyOf: [$ref Only]`) is not a union at all: it is simply its branch, typed and sent as that object in every mode. A schema carrying BOTH top-level `properties` and an `allOf` means "an object with those properties that ALSO satisfies every member of the allOf": the generator folds the properties in as one more `allOf` member, so they appear in the generated type and on the wire alongside the composed base's fields (they used to be dropped from the type while the form walk still emitted a part for them). The folded properties go LAST, so they WIN any name they share with the base: a sibling `count: { type: string }` over a base's `count: { type: integer }` types the field `string`, the reading the swift, kotlin and php clients have always taken. The base's own copy is SUBTRACTED from the emitted validator for that name (`z.intersection(OverrideBase.omit({ count: true }), z.object({ count: z.string() }))`), because intersecting the two demanded the value be a number AND a string — a validator no payload could satisfy, and one the same spec avoided entirely if the base was written inline instead of behind a `$ref`. A schema carrying BOTH top-level `properties` and a `oneOf` means "an object with those properties that additionally satisfies one of the branches": the generator distributes the properties over every branch, so the body types as `({ album: string } & Song) | ({ album: string } & Podcast)` and each alternative carries the shared fields. All five modes distribute identically, so the parts on the wire are the same from each. Because distribution reaches response schemas too, the shared properties are now required in every branch, so a response omitting one fails validation where it previously passed — spec-faithful, but stricter than before. A discriminated union whose branches are `allOf` compositions, or whose discriminator property is an unconstrained `string`, cannot be a `z.discriminatedUnion`: Zod only accepts plain object options whose discriminator narrows to literals, and handing it anything else fails `tsc` and throws on the first `parse`. Those unions are emitted as a `z.union` whose options are **tag-constrained** — each branch is paired with the literal its `discriminator.mapping` demands (`z.intersection(SystemEvent, z.object({ kind: z.literal("system") }))`) and the bare branches follow as a trailing fallback. So a recognised tag selects its branch no matter what order the branches are declared in, and an unrecognised or absent tag falls through to trial decoding — the same answer the kotlin client gives for the same bytes. A `mapping` is OPTIONAL: absent one, OpenAPI says the tag is matched against the branches' own SCHEMA names, and the tag constraint is built from those instead (`z.literal("SystemEvent")`) — the rule the swift and kotlin clients already applied, so all four typed modes now pick the same branch for a mapping-less discriminator. Previously the TS modes refused without a mapping and fell back to declaration order, which answered with the narrow branch (and stripped the fields only the wide one declares) where swift and kotlin answered with the wide one. An ANONYMOUS branch — one the spec spells inline, with no schema name — has no name to answer to, so it is never selected by tag and stays reachable only through trial decoding. A `discriminator` declared on an **`anyOf`** is read exactly the same way — OpenAPI allows one on all three composition keywords, and the swift and kotlin clients have always honoured it there, so a bare `z.union` answered with the narrow branch (dropping the fields only the wide one declares) where they answered with the wide one. The bare options stay behind the tag-constrained ones for the same reason as on a `oneOf`, and it matters more here: `anyOf` permits a value to satisfy several branches, and a tag no branch claims still has to reach trial decoding. Because the tag constraint is an `z.intersection(Branch, z.object({ kind: z.literal(...) }))`, the tag is present in the PARSED data even when the branch schema itself never declares that property: `{"petType":"Cat","lives":9}` comes back as `{ lives: 9, petType: "Cat" }` here, while the swift and kotlin clients drop it (their branch types have no such field), so the returned object differs across modes for that shape. If you control the spec, prefer OpenAPI 3.1's `kind: { type: string, const: "system" }`: a STRING `const` is treated as a one-value enum, which restores a real `z.discriminatedUnion` and with it TypeScript narrowing (`if (e.kind === "system") e.severity`). Only a string narrows to an `enum`, because a `String`-raw Swift enum cannot decode a bare `true` or `null`. A boolean, integer or `null` `const` is still PINNED, just as a literal rather than an enum: `z.literal(true)`, `z.literal(42)`, `z.null()`. That matters beyond precision — a bare `{ const: null }` names no type, so it used to fall through to `z.unknown()`, which accepts the key being ABSENT and quietly loosened a REQUIRED field that the swift and kotlin clients both reject. Omitting the whole `body` on an operation with an optional multipart body still sends a well-formed (empty) form, not a bodyless request.

Form-urlencoded bodies (`application/x-www-form-urlencoded`) take a plain object and follow the same field rules, with a `format: binary` field treated as a plain string (a urlencoded body cannot carry a file). Raw binary bodies (`application/octet-stream`, `image/*`, …) take a single `BinaryInput`, converted to a `Buffer` internally because Playwright's `data` option does not accept a `Blob`:

```typescript
await api.requestToken({ body: { grantType: "password", clientId: "abc" } });
await api.uploadRawBlob({ body: new Blob([bytes]) });
// A `text/*` body with a `string` schema is sent verbatim, with its Content-Type set explicitly:
await api.renderMarkdownRaw({ body: "# Title" });
```

Note: an **inline** (non-`$ref`) request body or parameter schema is spelled out as a structural type (the same derivation as full mode), so it is fully typed without a named schema — e.g. `body: { file: BinaryInput; title: string }`. A `$ref`'d body still types as `body: z.infer<typeof ReportUpload>`.

## Common Mistakes

### CRITICAL Missing peer dependencies

Wrong:

```bash
npm install -D @playwright/test
# Generated file fails: Cannot find module 'zod'
```

Correct:

```bash
npm install -D zod @playwright/test
```

The generated playwright-mode file imports both `zod` and `@playwright/test`. Both must be installed.

Source: src/modes/playwright/index.ts generateImports

### CRITICAL Passing a URL string instead of APIRequestContext

Wrong:

```typescript
const api = new TestApi("https://api.example.com");
```

Correct:

```typescript
test("api test", async ({ request }) => {
  const api = new TestApi(request);
});
```

The playwright client constructor takes an `APIRequestContext`, not a base URL. The request context comes from Playwright's `{ request }` test fixture, which handles base URL configuration via `playwright.config.ts`.

Source: src/modes/playwright/index.ts generateClient

### HIGH Editing the generated file directly

Wrong:

```typescript
// Adding a helper method directly in TestApi.ts
export class TestApi {
  // ...generated methods...
  async customHelper() { /* hand-written */ }
}
```

Correct:

```typescript
// Create a wrapper in a separate file
import { TestApi } from "./generated/TestApi";

class ExtendedTestApi extends TestApi {
  async customHelper() { /* hand-written */ }
}
```

The generated output is meant to be regenerated from the spec. Manual edits are overwritten on the next generation run.

Source: maintainer interview

See also: generate-client/SKILL.md — CLI usage for regenerating the client
