Gathering detailed insights and metrics for @openapi-codegen/cli
Gathering detailed insights and metrics for @openapi-codegen/cli
Gathering detailed insights and metrics for @openapi-codegen/cli
Gathering detailed insights and metrics for @openapi-codegen/cli
@sschw/openapi-codegen-cli
OpenAPI Codegen cli
openapi-typescript-codegen
Library that generates Typescript clients based on the OpenAPI specification.
@hey-api/openapi-ts
π The OpenAPI to TypeScript codegen. Generate clients, SDKs, validators, and more.
@hey-api/client-fetch
π Fetch API client for `@hey-api/openapi-ts` codegen.
A tool for generating code base on an OpenAPI schema.
npm install @openapi-codegen/cli
typescript: v8.0.2
Published on 29 Apr 2024
cli: v2.0.2
Published on 29 Apr 2024
typescript: v8.0.1
Published on 03 Apr 2024
cli: v2.0.1
Published on 03 Apr 2024
typescript: v8.0.0
Published on 01 Nov 2023
typescript: v7.0.1
Published on 17 Sept 2023
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
509 Stars
222 Commits
64 Forks
5 Watching
4 Branches
20 Contributors
Updated on 24 Nov 2024
Minified
Minified + Gzipped
TypeScript (99.83%)
JavaScript (0.16%)
Shell (0.01%)
Cumulative downloads
Total Downloads
Last day
1%
4,807
Compared to previous day
Last week
10.5%
22,714
Compared to previous week
Last month
10.4%
86,305
Compared to previous month
Last year
163.5%
799,162
Compared to previous year
20
20
Initialize the generator
1$ 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
1$ 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 file
By 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:
1npm i @tanstack/react-query
QueryClient
as described here.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:
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:
For example, if you add this object to your schema:
1SignUpInput: 2 type: object 3 properties: 4 email: 5 type: string 6 format: email 7 maxLength: 255 8 password: 9 type: string 10 maxLength: 255 11 firstName: 12 type: string 13 pattern: ^[0-9a-zA-Z]*$ 14 maxLength: 255 15 lastName: 16 type: string 17 pattern: ^[0-9a-zA-Z]*$ 18 maxLength: 255 19 required: 20 - email 21 - password 22 - firstName 23 - 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)
1import { useListPets } from "./petStore/petStoreComponents"; // <- output from openapi-codegen 2 3const Example = () => { 4 const { data, loading, error } = useListPets(); 5 6 // `data` is fully typed and have all documentation from OpenAPI 7};
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:
1// openapi-codegen.config.ts
2import { defineConfig } from "@openapi-codegen/cli";
3import {
4 generateSchemaTypes,
5 generateReactQueryComponents,
6 /* generateExpressControllers, */
7 /* generateRestfulReactComponents, */
8 /* ... */
9} from "@openapi-codegen/typescript";
10
11export default defineConfig({
12 example: {
13 // can be overridden from cli
14 from: {
15 source: "github",
16 owner: "fabien0102",
17 repository: "openapi-codegen",
18 ref: "main",
19 specPath: "examples/spec.yaml",
20 },
21
22 // can be overridden from cli
23 outputDir: "src/queries",
24
25 to: async (context) => {
26 // You can transform the `context.openAPIDocument` here, can be useful to remove internal routes or fixing some known issues in the specs ;)
27
28 // Generate all the schemas types (components & responses)
29 const { schemasFiles } = await generateSchemaTypes(context, {
30 /* config */
31 });
32
33 // Generate all react-query components
34 await generateReactQueryComponents(context, {
35 /* config*/
36 schemasFiles,
37 });
38 },
39 },
40});
the @openapi-codegen/cli
supports these generator plugins:
generate all schema types for your specification:
1 const { schemasFiles } = await generateSchemaTypes(context, { 2 /* config */ 3 });
output: {namespace}Schemas.ts
generate all fetchers with types for your specification needs schemafiles
1 await generateFetchers(context, {
2 /* config */
3 schemasFiles,
4 });
output: {namespace}Fetchers.ts
generate all React Query Components for useQuery() and useMutation()
1 await generateReactQueryComponents(context, {
2 /* config*/
3 schemasFiles,
4 });
output: {namespace}Components.ts
generate all React Query Functions used for e.g. React-Router 6.6.0+ loader functions
1 await generateReactQueryFunctions(context, {
2 filenamePrefix,
3 schemasFiles,
4 });
output: {namespace}Functions.ts
example usage in react-route-loader:
1export const routeLoader = (queryClient: QueryClient) => 2 async ({ params }: MyParams) => 3 await queryClient.fetchQuery(...getYourQueryNameQuery({}), { 4 /*options*/ 5 })
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):
This project follows the all-contributors specification. Contributions of any kind welcome!
No vulnerabilities found.
No security vulnerabilities found.