Skip to content

Getting started ​

codegen-openapi reads an OpenAPI spec and writes the code your frontend needs to talk to that API:

nextjsnextjs-pagesreact
Route handlers (server proxy to your backend)✅ route.ts✅ pages/api/*.ts—
Typed services (one per OpenAPI tag)✅✅✅
React hooks——✅
apiClient.ts (browser Axios instance)✅✅✅
fetchBackend.ts (server HTTP helper)✅✅—

Installation ​

bash
npm install --save-dev codegen-openapi

The CLI itself has no runtime dependencies. The generated code imports a few libraries, which you install in your app — generate checks your package.json and prints the exact install command for anything missing:

PackageNeeded when
axiosalways (used by apiClient.ts and fetchBackend.ts)
js-cookiecookieName is set
server-onlyframework is nextjs or nextjs-pages
@tanstack/react-queryframework: 'react' with hooksMode: 'react-query' (default)
bash
# Next.js
npm install axios server-only js-cookie

# React + React Query
npm install axios js-cookie @tanstack/react-query

TIP

The spec must be OpenAPI 3.0 or 3.1, in JSON — or YAML with the yaml package installed in your project. Swagger 2.0 is not supported.

Quick start ​

Run the interactive wizard in your project root:

bash
npx openapi-gen run

In English or Portuguese, it detects your framework, loads the spec to check it, suggests every value, shows a review of what will be generated, saves openapi-gen.config.mjs, generates everything and offers to install the packages the code needs. Type ? at any question for help.

Add a script so the whole team regenerates the same way:

json
{
  "scripts": {
    "codegen": "openapi-gen generate"
  }
}

Everyday workflow ​

bash
npx openapi-gen diff       # what changed in the spec vs. the files on disk
npx openapi-gen generate   # regenerate all files (--prune removes deleted endpoints, --watch keeps running)
npx openapi-gen add        # connect another API to the same project
npx openapi-gen info       # where files go and which env variables to set

Generated files are overwritten

Every file starts with // Auto-generated by codegen-openapi — do not edit manually. Put your own logic in separate files that import the generated services and hooks.

Using the generated code ​

Next.js — call the typed service from a client component; it hits your generated route handler, which proxies to the backend:

tsx
'use client';
import usersService from '@/services/users';

const users = await usersService.list({ page: 1 });

React — use the generated hooks:

tsx
import { useList, useCreate } from './hooks/users';

function Users() {
  const { data, isLoading } = useList({ page: 1 });
  const create = useCreate();
  // create.mutate({ body: { name: 'Ana' } })
}

Next: see Commands and the Configuration reference.

Released under the MIT License.