Skip to content

Improve query + path serialization #1534

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 15, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/lovely-needles-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-fetch": patch
---

Add support for automatic label & matrix path serialization.
5 changes: 5 additions & 0 deletions .changeset/shiny-trees-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-fetch": patch
---

Remove leading question marks from querySerializer
5 changes: 5 additions & 0 deletions .changeset/spicy-kings-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"openapi-fetch": minor
---

⚠️ Breaking change: no longer supports deeply-nested objects/arrays for query & path serialization.
2 changes: 1 addition & 1 deletion docs/data/contributors.json

Large diffs are not rendered by default.

125 changes: 96 additions & 29 deletions docs/openapi-fetch/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ description: openapi-fetch API

# API

## Create Client
## createClient

**createClient** accepts the following options, which set the default settings for all subsequent fetch calls.

```ts
createClient<paths>(options);
```

| Name | Type | Description |
| :---------------- | :-------------: | :-------------------------------------------------------------------------------------------------------------------------------------- |
| `baseUrl` | `string` | Prefix all fetch URLs with this option (e.g. `"https://myapi.dev/v1/"`) |
| `fetch` | `fetch` | Fetch instance used for requests (default: `globalThis.fetch`) |
| Name | Type | Description |
| :---------------- | :-------------- | :-------------------------------------------------------------------------------------------------------------------------------------- |
| `baseUrl` | `string` | Prefix all fetch URLs with this option (e.g. `"https://myapi.dev/v1/"`) |
| `fetch` | `fetch` | Fetch instance used for requests (default: `globalThis.fetch`) |
| `querySerializer` | QuerySerializer | (optional) Provide a [querySerializer](#queryserializer) |
| `bodySerializer` | BodySerializer | (optional) Provide a [bodySerializer](#bodyserializer) |
| (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal` …) ([docs](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) |
Expand All @@ -29,44 +29,98 @@ The following options apply to all request methods (`.GET()`, `.POST()`, etc.)
client.get("/my-url", options);
```

| Name | Type | Description |
| :---------------- | :---------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `params` | ParamsObject | [path](https://swagger.io/specification/#parameter-locations) and [query](https://swagger.io/specification/#parameter-locations) params for the endpoint |
| `body` | `{ [name]:value }` | [requestBody](https://spec.openapis.org/oas/latest.html#request-body-object) data for the endpoint |
| `querySerializer` | QuerySerializer | (optional) Provide a [querySerializer](#queryserializer) |
| `bodySerializer` | BodySerializer | (optional) Provide a [bodySerializer](#bodyserializer) |
| Name | Type | Description |
| :---------------- | :---------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `params` | ParamsObject | [path](https://swagger.io/specification/#parameter-locations) and [query](https://swagger.io/specification/#parameter-locations) params for the endpoint |
| `body` | `{ [name]:value }` | [requestBody](https://spec.openapis.org/oas/latest.html#request-body-object) data for the endpoint |
| `querySerializer` | QuerySerializer | (optional) Provide a [querySerializer](#queryserializer) |
| `bodySerializer` | BodySerializer | (optional) Provide a [bodySerializer](#bodyserializer) |
| `parseAs` | `"json"` \| `"text"` \| `"arrayBuffer"` \| `"blob"` \| `"stream"` | (optional) Parse the response using [a built-in instance method](https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods) (default: `"json"`). `"stream"` skips parsing altogether and returns the raw stream. |
| `fetch` | `fetch` | Fetch instance used for requests (default: fetch from `createClient`) |
| `fetch` | `fetch` | Fetch instance used for requests (default: fetch from `createClient`) |
| (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal`, …) ([docs](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)) |

### querySerializer
## querySerializer

By default, this library serializes query parameters using `style: form` and `explode: true` [according to the OpenAPI specification](https://swagger.io/docs/specification/serialization/#query). To change the default behavior, you can supply your own `querySerializer()` function either on the root `createClient()` as well as optionally on an individual request. This is useful if your backend expects modifications like the addition of `[]` for array params:
OpenAPI supports [different ways of serializing objects and arrays](https://swagger.io/docs/specification/serialization/#query) for parameters (strings, numbers, and booleans—primitives—always behave the same way). By default, this library serializes arrays using `style: "form", explode: true`, and objects using `style: "deepObject", explode: true`, but you can customize that behavior with the `querySerializer` option (either on `createClient()` to control every request, or on individual requests for just one).

### Object syntax

openapi-fetch ships the common serialization methods out-of-the-box:

| Option | Type | Description |
| :-------------- | :---------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `array` | SerializerOptions | Set `style` and `explode` for arrays ([docs](https://swagger.io/docs/specification/serialization/#query)). Default: `{ style: "form", explode: true }`. |
| `object` | SerializerOptions | Set `style` and `explode` for objects ([docs](https://swagger.io/docs/specification/serialization/#query)). Default: `{ style: "deepObject", explode: true }`. |
| `allowReserved` | `boolean` | Set to `true` to skip URL encoding (⚠️ may break the request) ([docs](https://swagger.io/docs/specification/serialization/#query)). Default: `false`. |

```ts
const { data, error } = await GET("/search", {
params: {
query: { tags: ["food", "california", "healthy"] },
const client = createClient({
querySerializer: {
array: {
style: "pipeDelimited", // "form" (default) | "spaceDelimited" | "pipeDelimited"
explode: true,
},
object: {
style: "form", // "form" | "deepObject" (default)
explode: true,
},
},
querySerializer(q) {
let s = [];
for (const [k, v] of Object.entries(q)) {
if (Array.isArray(v)) {
for (const i of v) {
s.push(`${k}[]=${i}`);
});
```

#### Array styles

| Style | Array `id = [3, 4, 5]` |
| :--------------------------- | :---------------------- |
| form | `/users?id=3,4,5` |
| **form (exploded, default)** | `/users?id=3&id=4&id=5` |
| spaceDelimited | `/users?id=3%204%205` |
| spaceDelimited (exploded) | `/users?id=3&id=4&id=5` |
| pipeDelimited | `/users?id=3\|4\|5` |
| pipeDelimited (exploded) | `/users?id=3&id=4&id=5` |

#### Object styles

| Style | Object `id = {"role": "admin", "firstName": "Alex"}` |
| :----------------------- | :--------------------------------------------------- |
| form | `/users?id=role,admin,firstName,Alex` |
| form (exploded) | `/users?role=admin&firstName=Alex` |
| **deepObject (default)** | `/users?id[role]=admin&id[firstName]=Alex` |

> [!NOTE]
>
> **deepObject** is always exploded, so it doesn’t matter if you set `explode: true` or `explode: false`—it’ll generate the same output.

### Alternate function syntax

Sometimes your backend doesn’t use one of the standard serialization methods, in which case you can pass a function to `querySerializer` to serialize the entire string yourself. You’ll also need to use this if you’re handling deeply-nested objects and arrays in your params:

```ts
const client = createClient({
querySerializer(queryParams) {
const search = [];
for (const name in queryParams) {
const value = queryParams[name];
if (Array.isArray(value)) {
for (const item of value) {
s.push(`${name}[]=${encodeURIComponent(item)}`);
}
} else {
s.push(`${k}=${v}`);
s.push(`${name}=${encodeURLComponent(value)}`);
}
}
return s.join("&"); // ?tags[]=food&tags[]=california&tags[]=healthy
return search.join(","); // ?tags[]=food,tags[]=california,tags[]=healthy
},
});
```

### bodySerializer
> [!WARNING]
>
> When serializing yourself, the string will be kept exactly as-authored, so you’ll have to call [encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) or [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) to escape special characters.

Similar to [querySerializer](#querySerializer), bodySerializer allows you to customize how the requestBody is serialized if you don’t want the default [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) behavior. You probably only need this when using `multipart/form-data`:
## bodySerializer

Similar to [querySerializer](#queryserializer), bodySerializer allows you to customize how the requestBody is serialized if you don’t want the default [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) behavior. You probably only need this when using `multipart/form-data`:

```ts
const { data, error } = await PUT("/submit", {
Expand All @@ -76,10 +130,23 @@ const { data, error } = await PUT("/submit", {
},
bodySerializer(body) {
const fd = new FormData();
for (const [k, v] of Object.entries(body)) {
fd.append(k, v);
for (const name in body) {
fd.append(name, body[name]);
}
return fd;
},
});
```

## Path serialization

openapi-fetch supports path serialization as [outlined in the 3.1 spec](https://swagger.io/docs/specification/serialization/#path). This happens automatically, based on the specific format in your OpenAPI schema:

| Template | Style | Primitive `id = 5` | Array `id = [3, 4, 5]` | Object `id = {"role": "admin", "firstName": "Alex"}` |
| :---------------- | :------------------- | :----------------- | :----------------------- | :--------------------------------------------------- |
| **`/users/{id}`** | **simple (default)** | **`/users/5`** | **`/users/3,4,5`** | **`/users/role,admin,firstName,Alex`** |
| `/users/{id*}` | simple (exploded) | `/users/5` | `/users/3,4,5` | `/users/role=admin,firstName=Alex` |
| `/users/{.id}` | label | `/users/.5` | `/users/.3,4,5` | `/users/.role,admin,firstName,Alex` |
| `/users/{.id*}` | label (exploded) | `/users/.5` | `/users/.3.4.5` | `/users/.role=admin.firstName=Alex` |
| `/users/{;id}` | matrix | `/users/;id=5` | `/users/;id=3,4,5` | `/users/;id=role,admin,firstName,Alex` |
| `/users/{;id*}` | matrix (exploded) | `/users/;id=5` | `/users/;id=3;id=4;id=5` | `/users/;role=admin;firstName=Alex` |
6 changes: 5 additions & 1 deletion docs/openapi-fetch/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,8 @@ _Note: if you’re using Svelte without SvelteKit, the root example in `src/rout

### Vue

TODO
There isn’t an example app in Vue yet. Are you using it in Vue? Please [open a PR to add it!](https://github.com/drwpow/openapi-typescript/pulls)

---

Additional examples are always welcome! Please [open a PR](https://github.com/drwpow/openapi-typescript/pulls) with your examples.
18 changes: 10 additions & 8 deletions docs/openapi-fetch/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ title: openapi-fetch

<img src="/assets/openapi-fetch.svg" alt="openapi-fetch" width="216" height="40" />

openapi-fetch is a typesafe fetch client that pulls in your OpenAPI schema. Weighs **2 kb** and has virtually zero runtime. Works with React, Vue, Svelte, or vanilla JS.
openapi-fetch is a typesafe fetch client that pulls in your OpenAPI schema. Weighs **4 kb** and has virtually zero runtime. Works with React, Vue, Svelte, or vanilla JS.

| Library | Size (min) | “GET” request |
| :------------------------- | ---------: | :------------------------- |
| openapi-fetch | `2 kB` | `200k` ops/s (fastest) |
| openapi-typescript-fetch | `4 kB` | `100k` ops/s (2× slower) |
| axios | `32 kB` | `165k` ops/s (1.2× slower) |
| superagent | `55 kB` | `50k` ops/s (6.6× slower) |
| openapi-typescript-codegen | `367 kB` | `75k` ops/s (2.6× slower) |
| openapi-fetch | `4 kB` | `278k` ops/s (fastest) |
| openapi-typescript-fetch | `4 kB` | `130k` ops/s (2.1× slower) |
| axios | `32 kB` | `217k` ops/s (1.3× slower) |
| superagent | `55 kB` | `63k` ops/s (4.4× slower) |
| openapi-typescript-codegen | `367 kB` | `106k` ops/s (2.6× slower) |

The syntax is inspired by popular libraries like react-query or Apollo client, but without all the bells and whistles and in a 2 kb package.
The syntax is inspired by popular libraries like react-query or Apollo client, but without all the bells and whistles and in a 4 kb package.

```ts
import createClient from "openapi-fetch";
Expand Down Expand Up @@ -49,7 +49,7 @@ Notice there are no generics, and no manual typing. Your endpoint’s request an
- ✅ No manual typing of your API
- ✅ Eliminates `any` types that hide bugs
- ✅ Also eliminates `as` type overrides that can also hide bugs
- ✅ All of this in a **2 kB** client package 🎉
- ✅ All of this in a **4 kb** client package 🎉

## Setup

Expand Down Expand Up @@ -139,6 +139,8 @@ openapi-fetch infers types from the URL. Prefer static string values over dynami

:::

This library also supports the **label** and **matrix** serialization styles as well ([docs](https://swagger.io/docs/specification/serialization/#path)) automatically.

### Request

The `GET()` request shown needed the `params` object that groups [parameters by type](https://spec.openapis.org/oas/latest.html#parameter-object) (`path` or `query`). If a required param is missing, or the wrong type, a type error will be thrown.
Expand Down
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@
"update-contributors": "node scripts/update-contributors.js"
},
"devDependencies": {
"vitepress": "1.0.0-rc.40"
"vitepress": "1.0.0-rc.42"
}
}
Loading