diff --git a/docs/openapi-fetch/index.md b/docs/openapi-fetch/index.md index 1a0819733..619c7d9c1 100644 --- a/docs/openapi-fetch/index.md +++ b/docs/openapi-fetch/index.md @@ -44,7 +44,7 @@ await client.PUT("/blogposts", { ::: -`data` and `error` are typechecked and expose their shapes to Intellisence 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. +`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](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) (which you can [swap for any call](/openapi-fetch/api#create-client)). diff --git a/packages/openapi-fetch/README.md b/packages/openapi-fetch/README.md index d8ba284f8..c6891f0c5 100644 --- a/packages/openapi-fetch/README.md +++ b/packages/openapi-fetch/README.md @@ -1,6 +1,6 @@ openapi-fetch -openapi-fetch is a type-safe fetch client that pulls in your OpenAPI schema. Weighs **4 kB** and has virtually zero runtime. Works with React, Vue, Svelte, or vanilla JS. +openapi-fetch is a type-safe fetch client that pulls in your OpenAPI schema. Weighs **5 kb** and has virtually zero runtime. Works with React, Vue, Svelte, or vanilla JS. | Library | Size (min) | “GET” request\* | | :------------------------- | ---------: | :------------------------- | @@ -12,7 +12,7 @@ openapi-fetch is a type-safe fetch client that pulls in your OpenAPI schema. Wei _\* [Benchmarks are approximate](https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-fetch/test/index.bench.js) 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 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 5 kb package. ```ts import createClient from "openapi-fetch"; @@ -38,7 +38,7 @@ await client.PUT("/blogposts", { `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 only thin wrappers around the native [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) (which you can [swap for any call](https://openapi-ts.dev/openapi-fetch/api/#create-client)). +`GET()`, `PUT()`, `POST()`, etc. are thin wrappers around the native [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) (which you can [swap for any call](https://openapi-ts.dev/openapi-fetch/api/#create-client)). 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: @@ -49,7 +49,7 @@ Notice there are no generics, and no manual typing. Your endpoint’s request an - ✅ Also eliminates `as` type overrides that can also hide bugs - ✅ All of this in a **5 kb** client package 🎉 -## 🔧 Setup +## Setup Install this library along with [openapi-typescript](../openapi-typescript): @@ -58,7 +58,9 @@ npm i openapi-fetch npm i -D openapi-typescript typescript ``` -> **Highly recommended**: enable [noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess) in your `tsconfig.json` ([docs](/advanced#enable-nouncheckedindexaccess-in-your-tsconfigjson)) +> **Highly recommended** +> +> Enable [noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess) in your `tsconfig.json` ([docs](/advanced#enable-nouncheckedindexaccess-in-your-tsconfigjson)) Next, generate TypeScript types from your OpenAPI schema using openapi-typescript: @@ -66,9 +68,7 @@ Next, generate TypeScript types from your OpenAPI schema using openapi-typescrip npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts ``` -> ⚠️ Be sure to validate your schemas! openapi-typescript will err on invalid schemas. - -Lastly, be sure to **run typechecking** in your project. This can be done by adding `tsc --noEmit` to your npm scripts like so: +Lastly, be sure to **run typechecking** in your project. This can be done by adding `tsc --noEmit` to your [npm scripts](https://docs.npmjs.com/cli/v9/using-npm/scripts) like so: ```json { @@ -80,9 +80,11 @@ Lastly, be sure to **run typechecking** in your project. This can be done by add 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. +> **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. -## Usage +## 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: @@ -116,4 +118,4 @@ const { data, error } = await client.PUT("/blogposts", { ## 📓 Docs -[View Docs](https://openapi-ts.dev/openapi-fetch/) +[View Docs](https://openapi-ts.dev/openapi-fetch/) \ No newline at end of file diff --git a/packages/openapi-typescript/README.md b/packages/openapi-typescript/README.md index 6e1a15e6f..e6b65bd11 100644 --- a/packages/openapi-typescript/README.md +++ b/packages/openapi-typescript/README.md @@ -1,15 +1,20 @@ openapi-typescript -openapi-typescript generates TypeScript types from static OpenAPI schemas quickly using only Node.js. It is fast, lightweight, (almost) dependency-free, and no Java/node-gyp/running OpenAPI servers necessary. +openapi-typescript turns [OpenAPI 3.0 & 3.1](https://spec.openapis.org/oas/latest.html) schemas into TypeScript quickly using Node.js. No Java/node-gyp/running OpenAPI servers necessary. The code is [MIT-licensed](./LICENSE) and free for use. +> **Tip:** +> New to OpenAPI? Speakeasy’s [Intro to OpenAPI](https://www.speakeasyapi.dev/openapi) is an accessible guide to newcomers that explains the “why” and “how” of OpenAPI. + ## Features -- ✅ Supports OpenAPI 3.0 and 3.1 (including advanced features like discriminators) -- ✅ Generate **runtime-free types** that outperform old-school codegen +- ✅ Supports OpenAPI 3.0 and 3.1 (including advanced features like [discriminators](https://spec.openapis.org/oas/v3.1.0#discriminator-object)) +- ✅ Generate **runtime-free types** that outperform old school codegen - ✅ Load schemas from YAML or JSON, locally or remotely -- ✅ Native Node.js code is fast and generates types within milliseconds +- ✅ Generate types for even huge schemas within milliseconds + +_Note: OpenAPI 2.x is supported with versions `5.x` and previous_ ## Examples @@ -17,35 +22,49 @@ The code is [MIT-licensed](./LICENSE) and free for use. ## Setup -This library requires the latest version of Node.js installed (20.x or higher recommended). With that present, run the following in your project: +This library requires the latest version of [Node.js](https://nodejs.org) installed (20.x or higher recommended). With that present, run the following in your project: ```bash npm i -D openapi-typescript typescript ``` -> ✨ **Tip** -> -> Enabling [noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess) in `tsconfig.json` can go along way to improve type safety ([read more](../../docs/src/content/docs/advanced.md#enable-nouncheckedindexedaccess-in-your-tsconfigjson)) +And in your `tsconfig.json`, to load the types properly: + +```diff +{ + "compilerOptions": { ++ "module": "ESNext", // or "NodeNext" ++ "moduleResolution": "Bundler" // or "NodeNext" + } +} +``` + +> **Highly recommended** +> +> Also adding the following can boost type safety: +> ```diff +> { +> "compilerOptions": { +> + "noUncheckedIndexedAccess": true +> } +> } +> ``` ## Basic usage -First, generate a local type file by running `npx openapi-typescript`: +First, generate a local type file by running `npx openapi-typescript`, first specifying your input schema (JSON or YAML), and where you’d like the `--output` (`-o`) to be saved: ```bash # Local schema npx openapi-typescript ./path/to/my/schema.yaml -o ./path/to/my/schema.d.ts # 🚀 ./path/to/my/schema.yaml -> ./path/to/my/schema.d.ts [7ms] -``` -```bash # Remote schema npx openapi-typescript https://myapi.dev/api/v1/openapi.yaml -o ./path/to/my/schema.d.ts # 🚀 https://myapi.dev/api/v1/openapi.yaml -> ./path/to/my/schema.d.ts [250ms] ``` -> ⚠️ Be sure to validate your schemas! openapi-typescript will err on invalid schemas. - -Then, import schemas from the generated file like so: +Then in your TypeScript project, import types where needed: ```ts import type { paths, components } from "./my-openapi-3-schema"; // generated by openapi-typescript @@ -63,27 +82,13 @@ type ErrorResponse = paths["/my/endpoint"]["get"]["responses"][500]["content"]["application/json"]["schema"]; ``` -#### 🦠 Globbing local schemas - -```bash -npx openapi-typescript "specs/**/*.yaml" --output schemas/ - -# 🚀 specs/one.yaml -> schemas/specs/one.ts [7ms] -# 🚀 specs/two.yaml -> schemas/specs/two.ts [7ms] -# 🚀 specs/three.yaml -> schemas/specs/three.ts [7ms] -``` - -_Thanks, [@sharmarajdaksh](https://github.com/sharmarajdaksh)!_ - -#### ☁️ Remote schemas - -```bash -npx openapi-typescript https://petstore3.swagger.io/api/v3/openapi.yaml --output petstore.d.ts - -# 🚀 https://petstore3.swagger.io/api/v3/openapi.yaml -> petstore.d.ts [250ms] -``` +From here, you can use these types for any of the following (but not limited to): -_Thanks, [@psmyrdek](https://github.com/psmyrdek)!_ +- Using an OpenAPI-supported fetch client (like [openapi-fetch](https://openapi-ts.dev/openapi-fetch/)) +- Asserting types for other API requestBodies and responses +- Building core business logic based on API types +- Validating mock test data is up-to-date with the current schema +- Packaging API types into any npm packages you publish (such as client SDKs, etc.) ## 📓 Docs