- TypeScript types
- Type-safe Generic Fetchers
- Type-safe React Query hooks (https://github.com/tanstack/query)
-
Initialize the generator
$ npx @openapi-codegen/cli init
If you wish to change any of the selections made, you can do so in the generated
openapi-codegen.config.ts
file later.. -
Start Generation
$ npx openapi-codegen gen {namespace}
After the code generation is done, you will notice the following files:
{namespace}Fetcher.ts
- defines a function that will make requests to your API.{namespace}Context.tsx
- the context that provides{namespace}Fetcher
to other components.{namespace}Components.tsx
- generated React Query components (if you selected React Query as part of initialization).{namespace}Schemas.ts
- the generated Typescript types from the provided Open API schemas.
Warning
If
{namespace}Fetcher.ts
or{namespace}Context.tsx
already exist in the output folder, they will not be replaced. However,{namespace}Components.tsx
and{namespace}Schemas.ts
will be re-generated each time based on the Open API spec file provided. -
Configure the Fetcher (optional)
After the first step you should see a file called
{namespace}Fetcher.ts
in your ouput directory. This fileBy default it uses the built-in Fetch API, you are free to change this to your fetching library of choice (Axios, Got etc.)
If your Open API spec contains a configured server, then the base URL for all requests will default to that server's URL. If no such configuration exists, you'll need to specify the base URL value.
-
Install and Configure React Query (optional)
If during generator setup you picked
> React Query components
, then you will need to install and configure React Query in order for the generated React hooks to work properly:- Install the library
npm i @tanstack/react-query
- Wire up the
QueryClient
as described here.
- Install the library
In software development, communication between components and documentation around it is often no fun.
GraphQL did resolve this by making documentation a part of the tooling (introspection), sadly this is often harder with REST APIs. OpenAPI can be an amazing tool, if, and only if the documentation (spec) and the actual implementation are aligned!
There are two different approaches:
- The OpenAPI spec is generated from the code (code first)
- The code is generated from the OpenAPI spec (spec first)
In either case, there needs to be an integration with the type system of the language, so everything is connected, and as we remove or update something that impacts the final response, this is automatically reflected!
This library has chosen the second approach, spec first. By doing so, your documentation is not your final (boring) task on the list, but the first and exciting one when adding new functionality! Indeed, you can’t start coding without generating your types (models & controllers) from the specs.
This has multiple benefits:
- You can take your time to think about your API before writing any code!
- You can discuss the API with your team (and discover API design problems earlier)
- You can generate all your validation rules
For example, if you add this object to your schema:
SignUpInput:
type: object
properties:
email:
type: string
format: email
maxLength: 255
password:
type: string
maxLength: 255
firstName:
type: string
pattern: ^[0-9a-zA-Z]*$
maxLength: 255
lastName:
type: string
pattern: ^[0-9a-zA-Z]*$
maxLength: 255
required:
- email
- password
- firstName
- lastName
OpenAPI Codegen will be able to generate all the relevant validation (or at least give you the choice to do it).
Note You can also attach any custom logic by using the
x-*
tag, the possibilities are endless!
Having to reverse engineer a backend response is the least productive/fun task ever! However, given a nice OpenAPI specs, we can actually generate nicely typed code for you that lets you interact with your API in a safe manner.
Taking React as example, calling an API can be as simple as this: (this hooks are using Tanstack Query under the hood)
import { useListPets } from "./petStore/petStoreComponents"; // <- output from openapi-codegen
const Example = () => {
const { data, loading, error } = useListPets();
// `data` is fully typed and have all documentation from OpenAPI
};
Note You can also check this blog post about using generated hooks in React https://xata.io/blog/openapi-typesafe-react-query-hooks
And since this generated from the specs, everything is safe at build time!
Note If you can’t trust your backend, some runtime validation can be useful to avoid surprises in production 😅
The only thing you need to manage is the configuration. Everything is typed and self-documented, but just in case, you can find here example configuration below:
// openapi-codegen.config.ts
import { defineConfig } from "@openapi-codegen/cli";
import {
generateSchemaTypes,
generateReactQueryComponents,
/* generateExpressControllers, */
/* generateRestfulReactComponents, */
/* ... */
} from "@openapi-codegen/typescript";
export default defineConfig({
example: {
// can be overridden from cli
from: {
source: "github",
owner: "fabien0102",
repository: "openapi-codegen",
ref: "main",
specPath: "examples/spec.yaml",
},
// can be overridden from cli
outputDir: "src/queries",
to: async (context) => {
// You can transform the `context.openAPIDocument` here, can be useful to remove internal routes or fixing some known issues in the specs ;)
// Generate all the schemas types (components & responses)
const { schemasFiles } = await generateSchemaTypes(context, {
/* config */
});
// Generate all react-query components
await generateReactQueryComponents(context, {
/* config*/
schemasFiles,
});
},
},
});
the @openapi-codegen/cli
supports these generator plugins:
generate all schema types for your specification:
const { schemasFiles } = await generateSchemaTypes(context, {
/* config */
});
output: {namespace}Schemas.ts
generate all fetchers with types for your specification needs schemafiles
await generateFetchers(context, {
/* config */
schemasFiles,
});
output: {namespace}Fetchers.ts
generate all React Query Components for useQuery() and useMutation()
await generateReactQueryComponents(context, {
/* config*/
schemasFiles,
});
output: {namespace}Components.ts
generate all React Query Functions used for e.g. React-Router 6.6.0+ loader functions
await generateReactQueryFunctions(context, {
filenamePrefix,
schemasFiles,
});
output: {namespace}Functions.ts
example usage in react-route-loader:
export const routeLoader = (queryClient: QueryClient) =>
async ({ params }: MyParams) =>
await queryClient.fetchQuery(...getYourQueryNameQuery({}), {
/*options*/
})
more infos: https://reactrouter.com/en/main/guides/data-libs
You can import any generator into the to
section, those can be the ones provided by this project or your own custom ones. You have full control of what you are generating!
Have fun!
Thanks goes to these wonderful people (emoji key):
Fabien BERNARD 💻 🎨 📖 🤔 📆 👀 |
mpotomin 💻 🤔 👀 |
Michael Franzkowiak 📖 |
Alexis Rico 💻 🤔 |
Nedim Arabacı 💬 💻 🤔 |
Antoniel Magalhães 💡 |
Florian Dreier 💻 |
Fabian Althaus 💻 |
ci-vamp 🐛 💻 |
Alan Oliveira 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!