包详细信息

openapi-fetch

openapi-ts3.2mMIT0.13.5

Fast, type-safe fetch client for your OpenAPI schema. Only 6 kb (min). Works with React, Vue, Svelte, or vanilla JS.

openapi, swagger, rest, api

自述文件

openapi-fetch

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

Library Size (min) “GET” request*
openapi-fetch 6 kB 300k ops/s (fastest)
openapi-typescript-fetch 3 kB 300k ops/s (fastest)
feature-fetch 15 kB 300k ops/s (fastest)
axios 32 kB 225k ops/s (1.3× slower)
superagent 55 kB 50k ops/s (6× slower)
openapi-typescript-codegen 367 kB 100k ops/s (3× slower)

* Benchmarks are approximate to just show rough baseline and will differ among machines and browsers. The relative performance between libraries is more reliable.

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

import createClient from "openapi-fetch";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

const client = createClient<paths>({ baseUrl: "https://myapi.dev/v1/" });

const {
  data, // only present if 2XX response
  error, // only present if 4XX or 5XX response
} = await client.GET("/blogposts/{post_id}", {
  params: {
    path: { post_id: "123" },
  },
});

await client.PUT("/blogposts", {
  body: {
    title: "My New Post",
  },
});

data and error are typechecked and expose their shapes to Intellisense in VS Code (and any other IDE with TypeScript support). Likewise, the request body will also typecheck its fields, erring if any required params are missing, or if there’s a type mismatch.

GET(), PUT(), POST(), etc. are thin wrappers around the native fetch API (which you can swap for any call).

Notice there are no generics, and no manual typing. Your endpoint’s request and response were inferred automatically. This is a huge improvement in the type safety of your endpoints because every manual assertion could lead to a bug! This eliminates all of the following:

  • ✅ No typos in URLs or params
  • ✅ All parameters, request bodies, and responses are type-checked and 100% match your schema
  • ✅ 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 6 kb client package 🎉

Setup

Install this library along with openapi-typescript:

npm i openapi-fetch
npm i -D openapi-typescript typescript

Highly recommended

Enable noUncheckedIndexedAccess in your tsconfig.json (docs)

Next, generate TypeScript types from your OpenAPI schema using openapi-typescript:

npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts

Lastly, be sure to run typechecking in your project. This can be done by adding tsc --noEmit to your npm scripts like so:

{
  "scripts": {
    "test:ts": "tsc --noEmit"
  }
}

And run npm run test:ts in your CI to catch type errors.

TIP:

Use tsc --noEmit to check for type errors rather than relying on your linter or your build command. Nothing will typecheck as accurately as the TypeScript compiler itself.

Basic usage

The best part about using openapi-fetch over oldschool codegen is no documentation needed. openapi-fetch encourages using your existing OpenAPI documentation rather than trying to find what function to import, or what parameters that function wants:

OpenAPI schema example

import createClient from "openapi-fetch";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

const client = createClient<paths>({ baseUrl: "https://myapi.dev/v1/" });

const { data, error } = await client.GET("/blogposts/{post_id}", {
  params: {
    path: { post_id: "my-post" },
    query: { version: 2 },
  },
});

const { data, error } = await client.PUT("/blogposts", {
  body: {
    title: "New Post",
    body: "<p>New post body</p>",
    publish_date: new Date("2023-03-01T12:00:00Z").getTime(),
  },
});
  1. The HTTP method is pulled directly from createClient()
  2. You pass in your desired path to GET(), PUT(), etc.
  3. TypeScript takes over the rest and returns helpful errors for anything missing or invalid

📓 Docs

View Docs

更新日志

openapi-fetch

0.13.5

Patch Changes

0.13.4

Patch Changes

0.13.3

Patch Changes

Refresh of 0.13.2; corrupted package

0.13.2

Patch Changes

  • #2020 7081842 Thanks @mellster2012! - Add client option to pass custom RequestInit object into fetch requests for supported implementations

0.13.1

Patch Changes

0.13.0

Minor Changes

  • #1968 267977e Thanks @DjordyKoert! - 204 responses or response with a Content-Length of 0 will now return undefined instead of an empty object

0.12.5

Patch Changes

  • #1937 06163a2 Thanks @DjordyKoert! - client data & error now return a union of possible types

  • Updated dependencies [06163a2]:

    • openapi-typescript-helpers@0.0.15

0.12.4

Patch Changes

  • Updated dependencies [abfad56]:
    • openapi-typescript-helpers@0.0.14

0.12.3

Patch Changes

0.12.2

Patch Changes

  • #1918 e39d11e Thanks @yicrotkd! - Improve Middleware type definition to require either onRequest or onResponse

0.12.1

Patch Changes

0.12.0

Minor Changes

  • ⚠️ Breaking Change #1826 b893c44 Thanks @goce-cz! - Do not set content-type on body-less requests

0.11.3

Patch Changes

0.11.2

Patch Changes

0.11.1

Patch Changes

  • #1831 091e71a Thanks @SebastienGllmt! - Add MethodResponse utility type to easily get the return type of an endpoint on a client

  • #1833 cec023d Thanks @ngraef! - Fix identification of required properties when strictNullChecks is disabled

  • Updated dependencies [cec023d]:

    • openapi-typescript-helpers@0.0.12

0.11.0

Minor Changes

-- ⚠️ Breaking Change #1791 a956d5d Thanks @gzm0! - Add support for client["/endpoint"].GET() style calls

0.10.6

Patch Changes

0.10.5

Patch Changes

0.10.4

Patch Changes

  • Updated dependencies [bcc9222]:
    • openapi-typescript-helpers@0.0.11

0.10.3

Patch Changes

0.10.2

Patch Changes

0.10.1

Patch Changes

0.10.0

Minor Changes

  • ⚠️ Breaking Change: openapi-typescript@7 is needed to work. You’ll get type errors with openapi-typescript@6 and below.
  • ⚠️ Breaking Change: The Middleware API has changed to be an object rather than (request, options) or (response, options). See Middleware docs for updated API.
  • ⚠️ Breaking Change: The Content-Type header is no longer sent by default if a body payload is attached.
  • ⚠️ Breaking Change: The customFetch type now calls fetch(input: string, init: RequestInit) and the types have been updated, rather than fetch(input: Request) introduced in 0.9.0.

  • Added id to middleware handlers that create a unique ID per-fetch

0.9.8

Patch Changes

0.9.7

Patch Changes

  • #1672 64cb619 Thanks @jaredLunde! - Fixes issue where native properties were not excluded from custom properties in the CustomRequest class

0.9.6

Patch Changes

0.9.5

Patch Changes

0.9.4

Patch Changes

0.9.3

Patch Changes

0.9.2

Patch Changes

  • #1550 a5a9cc7 Thanks @shirish87! - Fix 'Content-Type' header being removed from requests with multipart/form-data body

0.9.1

Patch Changes

0.9.0

Minor Changes

  • #1521 b174dd6 Thanks @drwpow! - Add middleware support

  • #1521 fc3a468 Thanks @drwpow! - ⚠️ Breaking change (internal): fetch() is now called with new Request() to support middleware (which may affect test mocking)

  • #1521 2551e4b Thanks @drwpow! - ⚠️ Breaking change: Responses are no longer automatically .clone()’d in certain instances. Be sure to .clone() yourself if you need to access the raw body!

  • #1534 2bbeb92 Thanks @drwpow! - ⚠️ Breaking change: no longer supports deeply-nested objects/arrays for query & path serialization.

Patch Changes

0.8.2

Patch Changes

  • #1424 8f5adb3 Thanks @drwpow! - Separate TS types to be managed manually

  • Updated dependencies [5be2082]:

    • openapi-typescript-helpers@0.0.5

0.8.1

Patch Changes

  • #1404 93204e4 Thanks @drwpow! - Fix behavior for empty arrays and objects in default querySerializer

0.8.0

Minor Changes

0.7.10

Patch Changes

0.7.9

Patch Changes

  • #1366 04dbd6d Thanks @drwpow! - Fix empty object being required param

  • Updated dependencies [04dbd6d]:

    • openapi-typescript-helpers@0.0.4

0.7.8

Patch Changes

0.7.7

Patch Changes

  • Updated dependencies [996e51e]:
    • openapi-typescript-helpers@0.0.3

0.7.6

Patch Changes

0.7.5

Patch Changes

  • Updated dependencies [e63a345]:
    • openapi-typescript-helpers@0.0.2

0.7.4

Patch Changes

0.7.3

Patch Changes

0.7.2

Patch Changes

0.7.1

Patch Changes

0.7.0

Minor Changes

  • #1243 541abf4 Thanks @drwpow! - ⚠️ Breaking: rename all methods to UPPERCASE (GET(), POST(), etc.)

0.6.2

Patch Changes

0.6.1

Patch Changes

0.6.0

Minor Changes

  • 0380e9a Thanks @drwpow! - Add multipart/form-data request body support

  • 0380e9a Thanks @drwpow! - Breaking: openapi-fetch now just takes the first media type it finds rather than preferring JSON. This is because in the case of multipart/form-data vs application/json, it’s not inherently clear which you’d want. Or if there were multiple JSON-like media types.

0.5.0

Minor Changes

Patch Changes

0.4.0

Minor Changes

0.3.0

Minor Changes

Patch Changes

0.2.1

Patch Changes

0.2.0

Minor Changes

  • 97c8757: Add custom fetch option (#51). Thanks, @hd-o!

0.1.4

Patch Changes

  • 63ebe48: Fix request body type when optional (#48)

0.1.3

Patch Changes

  • 8c01480: Fix querySerializer signature

0.1.2

Patch Changes

  • e730cd8: Fix post() and options() types

0.1.1

Patch Changes

  • 5d1fb7d: Fix bad HTTP method lookup causing polymorphsim

0.1.0

Minor Changes

  • f878cd3: Add querySerializer

Patch Changes

  • 22197a1: Add missing type defs for minified build
  • ff3174a: Fix type inference bugs
  • 4ce3828: Skip parsing JSON for empty responses (#23)
  • ff3ae1b: Skip parsing JSON for 204 responses (#28)

0.0.8

Patch Changes

  • 8e7cb46: Fix TypeScript lib error, simplify generated types

0.0.7

Patch Changes

  • fce1546: Support "application/json;charset=utf-8" content types (#15). Thanks, @shinzui!
  • 0899e0e: Add minified build (#18)

0.0.6

Patch Changes

  • 27c149c: Fix data, error sometimes returning undefined

0.0.5

Patch Changes

  • c818e65: Export BaseParams shared type (#8)

0.0.4

Patch Changes

  • ce99563: Fix optional requestBody in path

0.0.3

Patch Changes

0.0.2

Patch Changes

  • 5a47464: Fix module entry

0.0.1

Patch Changes

  • 55d7013: Encode path params