Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/lucky-jokes-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"openapi-typescript-helpers": minor
"openapi-typescript": minor
"openapi-fetch": minor
---

Add support for the HTTP `QUERY` method ([RFC 10008](https://www.rfc-editor.org/rfc/rfc10008)).

`query` is recognised as a path item verb in [OpenAPI 3.2](https://spec.openapis.org/oas/v3.2.0.html#path-item-object). openapi-typescript previously dropped it as an unknown property, so no types were emitted for it.

- `openapi-typescript` now emits a `query` operation for the path items that declare one. Path items without a `query` operation are unchanged, so existing generated output is not affected.
- `openapi-typescript-helpers` adds `"query"` to `HttpMethod`.
- `openapi-fetch` adds `client.QUERY()` (and `QUERY` on the path-based client), which sends a request body like `POST` while preserving QUERY's safe/idempotent semantics.
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
- run: pnpm test
test-e2e:
runs-on: ubuntu-latest
# Browser installation has hung indefinitely before (microsoft/playwright#40724).
# Without a timeout, a hung job burns the full 6h runner limit before being killed.
timeout-minutes: 20
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
Expand Down
40 changes: 40 additions & 0 deletions docs/openapi-fetch/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,46 @@ client.GET("/my-url", options);
| `middleware` | `Middleware[]` | [See docs](/openapi-fetch/middleware-auth) |
| (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal`, …) ([docs](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)) |

## Request methods

A client exposes one method per HTTP verb: `.GET()`, `.PUT()`, `.POST()`, `.DELETE()`, `.OPTIONS()`, `.HEAD()`, `.PATCH()`, `.TRACE()`, and `.QUERY()`. Each one is typed against the operations your schema declares for that verb, so only the paths that actually support a verb are accepted.

### QUERY

[QUERY](https://www.rfc-editor.org/rfc/rfc10008) is a safe, idempotent method that carries a request body — it fills the gap between `GET` (no body) and `POST` (neither safe nor idempotent), and is useful for searches whose parameters are too large or too structured for a URL.

`query` is recognised as a path item verb in [OpenAPI 3.2](https://spec.openapis.org/oas/v3.2.0.html#path-item-object):

```yaml
paths:
/resources:
query:
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
ids:
type: array
items:
type: integer
responses:
200:
description: OK
```

```ts
const { data, error } = await client.QUERY("/resources", {
body: { ids: [1, 2, 3] },
});
```

Because QUERY is safe and idempotent, sending the same request twice must be equivalent to sending it once. openapi-fetch keeps that guarantee: it adds no per-request state of its own, and it does not read or mutate the `body` and `params` you pass in, so the same options object can be reused across retries.

Note that support is only as good as the runtime and the server. `QUERY` requests are constructed with the standard `Request` API, so any environment that rejects the verb (or any intermediary that doesn't forward it) will fail the request.

## wrapAsPathBasedClient

**wrapAsPathBasedClient** wraps the result of `createClient()` to return a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)-based client that allows path-indexed calls:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@biomejs/biome": "2.4.14",
"@changesets/changelog-github": "0.7.0",
"@changesets/cli": "2.31.0",
"@playwright/test": "1.59.1",
"@playwright/test": "1.62.1",
"@size-limit/preset-small-lib": "12.1.0",
"@types/node": "25.6.0",
"prettier": "3.8.3",
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-fetch/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,14 @@ export interface Client<Paths extends {}, Media extends MediaType = MediaType> {
request: ClientRequestMethod<Paths, Media>;
/** Call a GET endpoint */
GET: ClientMethod<Paths, "get", Media>;
/**
* Call a QUERY endpoint
*
* QUERY is safe and idempotent (RFC 10008): unlike POST it may be retried or
* cached, and unlike GET it carries a request body.
* @see https://www.rfc-editor.org/rfc/rfc10008
*/
QUERY: ClientMethod<Paths, "query", Media>;
/** Call a PUT endpoint */
PUT: ClientMethod<Paths, "put", Media>;
/** Call a POST endpoint */
Expand Down
10 changes: 10 additions & 0 deletions packages/openapi-fetch/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,13 @@ export default function createClient(clientOptions) {
GET(url, init) {
return coreFetch(url, { ...init, method: "GET" });
},
/**
* Call a QUERY endpoint
* @see https://www.rfc-editor.org/rfc/rfc10008 (safe & idempotent; carries a request body)
*/
QUERY(url, init) {
return coreFetch(url, { ...init, method: "QUERY" });
},
/** Call a PUT endpoint */
PUT(url, init) {
return coreFetch(url, { ...init, method: "PUT" });
Expand Down Expand Up @@ -348,6 +355,9 @@ class PathCallForwarder {
GET = (init) => {
return this.client.GET(this.url, init);
};
QUERY = (init) => {
return this.client.QUERY(this.url, init);
};
PUT = (init) => {
return this.client.PUT(this.url, init);
};
Expand Down
171 changes: 171 additions & 0 deletions packages/openapi-fetch/test/http-methods/query.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { describe, expect, test } from "vitest";
import { wrapAsPathBasedClient } from "../../src/index.js";
import { createObservedClient, headersToObj } from "../helpers.js";
import type { paths } from "./schemas/query.js";

describe("QUERY", () => {
test("sends the correct method", async () => {
let method = "";
const client = createObservedClient<paths>({}, async (req) => {
method = req.method;
return Response.json({});
});
await client.QUERY("/resources/{id}", {
params: { path: { id: 123 } },
body: { ids: [1, 2, 3] },
});
expect(method).toBe("QUERY");
});

describe("request body", () => {
test("requires necessary requestBodies", async () => {
const client = createObservedClient<paths>({});

// expect error on missing `body`
await client.QUERY("/resources/{id}", {
params: { path: { id: 1 } },
// @ts-expect-error
body: undefined,
});

// expect error on missing required fields
await client.QUERY("/resources/{id}", {
params: { path: { id: 1 } },
// @ts-expect-error
body: {},
});

// expect present body to be good enough
await client.QUERY("/resources/{id}", {
params: { path: { id: 1 } },
body: { ids: [1, 2, 3] },
});
});

test("requestBody with required: false", async () => {
const client = createObservedClient<paths>({});

// assert missing `body` doesn't raise a TS error
await client.QUERY("/resources-optional", {
params: { path: { id: 1 } },
});

// assert error on type mismatch
await client.QUERY("/resources-optional", {
params: { path: { id: 1 } },
body: {
// @ts-expect-error
ids: "not-an-array",
},
});
});
});

test("sends correct options, returns success", async () => {
const mockData = { status: "ok" };
let actualPathname = "";
const client = createObservedClient<paths>({}, async (req) => {
actualPathname = new URL(req.url).pathname;
return Response.json(mockData, { status: 200 });
});

const { data, error, response } = await client.QUERY("/resources/{id}", {
params: { path: { id: 456 } },
body: { ids: [7, 8, 9] },
});

// assert correct URL was called
expect(actualPathname).toBe("/resources/456");

// assert correct data was returned
expect(data).toEqual(mockData);
expect(response.status).toBe(200);

// assert error is empty
expect(error).toBeUndefined();
});

test("sends the request body with a Content-Type", async () => {
// RFC 10008 §2: a QUERY request has content, so it must identify its media type
let actualBody = "";
let actualContentType: string | null = "";
const client = createObservedClient<paths>({}, async (req) => {
actualBody = await req.text();
actualContentType = req.headers.get("Content-Type");
return Response.json({});
});

await client.QUERY("/resources/{id}", {
params: { path: { id: 123 } },
body: { ids: [1, 2, 3] },
});

expect(actualBody).toBe(JSON.stringify({ ids: [1, 2, 3] }));
expect(actualContentType).toBe("application/json");
});

// QUERY is defined as safe & idempotent (RFC 10008 §2), so identical calls must stay
// identical on the wire: the client may not add per-request state of its own, and it
// may not consume or mutate the caller’s `init`.
describe("idempotency", () => {
test("repeated identical calls produce identical requests", async () => {
const observed: { method: string; url: string; headers: Record<string, string>; body: string }[] = [];
const client = createObservedClient<paths>({}, async (req) => {
observed.push({
method: req.method,
url: req.url,
headers: headersToObj(req.headers),
body: await req.text(),
});
return Response.json({});
});

const init = {
params: { path: { id: 123 } },
body: { ids: [1, 2, 3] },
};

// reuse the exact same init object, to assert it is not consumed or mutated
await client.QUERY("/resources/{id}", init);
await client.QUERY("/resources/{id}", init);

expect(observed).toHaveLength(2);
expect(observed[1]).toEqual(observed[0]);
expect(init).toEqual({ params: { path: { id: 123 } }, body: { ids: [1, 2, 3] } });
});

test("is safe: no request body is read or replayed across calls", async () => {
// a request body may only be consumed once, so each call must build its own Request
const bodies: string[] = [];
const client = createObservedClient<paths>({}, async (req) => {
bodies.push(await req.text());
return Response.json({});
});

await client.QUERY("/resources/{id}", { params: { path: { id: 1 } }, body: { ids: [1] } });
await client.QUERY("/resources/{id}", { params: { path: { id: 1 } }, body: { ids: [1] } });

expect(bodies).toEqual([JSON.stringify({ ids: [1] }), JSON.stringify({ ids: [1] })]);
});
});

test("works with the path based client", async () => {
let method = "";
let actualPathname = "";
const client = wrapAsPathBasedClient<paths>(
createObservedClient<paths>({}, async (req) => {
method = req.method;
actualPathname = new URL(req.url).pathname;
return Response.json({});
}),
);

await client["/resources/{id}"].QUERY({
params: { path: { id: 123 } },
body: { ids: [1, 2, 3] },
});

expect(method).toBe("QUERY");
expect(actualPathname).toBe("/resources/123");
});
});
Loading
Loading