Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
Let the API's OpenAPI spec write your React client: Orval turns /v3/api-docs into TypeScript types, useGetBooks and a Zod schema, and a renamed field becomes error TS2339 at BookList.tsx line 26.
What you will learn
- Explain why a hand-written client type drifts silently when the API changes
- Configure Orval to write model types, TanStack Query hooks and Zod schemas from /v3/api-docs
- Read a generated type, hook and Zod schema and map each back to the spec
- Turn a renamed backend field into a compile error at an exact line
Before you start
- Server State With TanStack Query
- Basic TypeScript types and interfaces
A hand-written client is a promise nobody checks. You type pages: number because that is what the server sent the day you wrote it. Then the backend team renames the field, your build still passes, and the page quietly loses a number.
The fix is to stop typing the server's shapes by hand. The API already describes itself in an OpenAPI spec, and a generator called Orval reads it and writes the types, the fetch functions, the TanStack Query hooks and the Zod schemas for you. When the server changes, you regenerate, and the compiler points at the exact line that broke.
A hand-written client drifts silently
export type Book = {
id: number
title: string
author: string
pages: number
}
export type BookPage = {
content: Book[]
page: { totalElements: number }
}
export async function getBooks(): Promise<BookPage> {
const res = await fetch('/api/books?size=50')
// fetch only throws on network errors, so we
// turn a 4xx or 5xx answer into an error here
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
}
Now the server renames pages to pageCount. The JSON for Matilda now ends with "pageCount": 240, while our type still says pages. return res.json() simply trusts that the text is a BookPage. Nothing checks it. The project's small demo script shows the result:
b.pages: undefined
page: Roald Dahl, pages
React draws nothing for undefined, so the row reads "Roald Dahl, pages" with a gap where the number was. No error anywhere.
The API describes itself
The Book API serves its contract at /v3/api-docs (how the FastAPI app is set up to do that is in The Book API in FastAPI). A GET there answers 200 with one JSON document:
api-docs: GET http://localhost:8080/v3/api-docs -> 200
openapi: 3.1.0 | paths: /api/books/{id}, /api/books, /api/books/{id}/cover
schemas: BookRequest, BookResponse, Pageable, PageMetadata, PagedModelBookResponse, BookResponseV2
BookResponse properties: id, title, author, pages
The paths list every address and method. The schemas give the exact shape of every object. The server wrote both itself.
src/api except fetcher.ts belongs to the generator.Orval reads the contract
import { defineConfig } from 'orval'
import { operationName } from './orval.names'
// the API describes itself here
const input = 'http://localhost:8080/v3/api-docs'
export default defineConfig({
books: {
input,
output: {
target: 'src/api/books.ts',
schemas: 'src/api/model',
client: 'react-query',
override: {
operationName,
// our own fetch wrapper (fetcher.ts)
mutator: {
path: 'src/api/fetcher.ts',
name: 'customFetch',
},
// hooks return the body, not { data, status }
fetch: {
includeHttpResponseReturnType: false,
},
},
},
},
booksZod: {
input,
output: {
target: 'src/api/books.zod.ts',
client: 'zod',
override: {
operationName,
// only request bodies: what a form needs
zod: {
generate: {
body: true,
param: false,
query: false,
header: false,
response: false,
},
},
},
},
},
})
inputpoints Orval at the live spec.schemaswrites one TypeScript type per schema intosrc/api/model.client: 'react-query'writes, for each operation, a fetch function and a TanStack Query hook intobooks.ts(713 lines in this run).mutatorsends every generated request throughcustomFetchin our ownfetcher.ts, so error handling stays in one file we control.- The second config,
booksZod, writes Zod schemas for the request bodies only.
npm run api
orval v8.46.0 - A swagger client generator for typescript
books - Library API - Your OpenAPI spec has been converted into ready to use orval!
booksZod - Library API - Your OpenAPI spec has been converted into ready to use orval!
Names come from the operation ids
Every operation in the spec has an id: list, create, delete, replace and oneV2. Left alone, Orval uses them as they are, which gives functions called list and create, and _delete, because delete is a reserved word in JavaScript. A small map fixes that:
import type { OperationObject } from 'orval'
// The spec names the operations list, create,
// delete ... These names make the code read well.
const names: Record<string, string> = {
list: 'getBooks',
create: 'createBook',
delete: 'deleteBook',
replace: 'replaceBook',
oneV2: 'getBook',
}
export const operationName = (op: OperationObject) =>
names[op.operationId ?? ''] ?? op.operationId ?? ''
Orval asks it once per operation, and every name built from it follows. The hook useList becomes useGetBooks, and the key function becomes getGetBooksQueryKey.
A spec field becomes a property
export interface BookResponse {
id?: number;
title?: string;
author?: string;
pages?: number;
}
The file starts with a comment header that says it plainly: generated by Orval, do not edit manually. The spec's integer (int64 for id, int32 for pages) becomes TypeScript's single number type, and strings stay string.
Every property here has a question mark because the spec this file was generated from had no required list for BookResponse, so each field may be missing. Run the same command against the FastAPI Book API and the fields come out required (id: number; title: string; ...), because the Pydantic models say they always have a value. The client code compiles either way.
Inside the generated hook
You never edit books.ts, but it is worth one look. This is an excerpt:
export const getBooks = async (params: GetBooksParams, options?: Parameters<typeof customFetch>[1]): Promise<PagedModelBookResponse> => {
return customFetch<PagedModelBookResponse>(getGetBooksUrl(params),
{
...options,
method: 'GET'
}
);}
export const getGetBooksQueryKey = (params?: GetBooksParams,) => {
return [
`/api/books`, ...(params ? [params] : [])
] as const;
}
getBooks calls customFetch with a URL built from the params, and getGetBooksQueryKey builds the cache key from the same params. Our params live in one small file:
import type { GetBooksParams } from './api/model'
// The API sends 5 books per page by default.
// Asking for 50 returns all the seeded books at once.
export const allBooks: GetBooksParams = {
pageable: { size: 50 },
}
A demo script prints what the generated code builds from them:
url: /api/books?size=50
key: ["/api/books",{"pageable":{"size":50}}]
useGetBooks is the same useQuery you would write by hand: a key and a fetch function, both built from the spec. Same params, same key, so every component that asks for the same list shares one cache entry.
The hook replaces api.ts
Here is src/BookList.tsx now:
import { allBooks } from './allBooks'
import { useGetBooks } from './api/books'
import { useRemoveBook } from './useRemoveBook'
type Props = { author: string }
export default function BookList({ author }: Props) {
// generated: typed data, key and fetch in one call
const { data, isPending, error } = useGetBooks(allBooks)
const remove = useRemoveBook()
if (isPending) return <p>Loading books...</p>
if (error) return <p>{error.message}</p>
const books = data.content.filter(
(b) => !author || b.author === author,
)
return (
<>
{remove.isError && (
<p className="toast">Could not delete</p>
)}
<ul>
{books.map((b) => (
<li key={b.id}>
<span>{b.title}</span>
<small>{b.author}, {b.pages} pages</small>
<button
onClick={() => remove.mutate({ id: b.id! })}
>
Remove
</button>
</li>
))}
</ul>
</>
)
}
The old useQuery({ queryKey: ['books'], queryFn: getBooks }) and the whole hand-written api.ts are gone. One thing to watch: the generated GetBooksParams says pageable is required, because the spec marks it so. Call useGetBooks() with nothing inside and the build stops:
src/BookCount.tsx(6,20): error TS2554: Expected 1-3 arguments, but got 0.
That is why every component passes allBooks.
The same rules at runtime with Zod
* @summary Add a book
*/
export const createBookBodyPagesExclusiveMin = 0;
export const CreateBookBody = zod.object({
"title": zod.string().min(1),
"author": zod.string().min(1),
"pages": zod.int().gt(createBookBodyPagesExclusiveMin).optional()
})
The spec says title and author have minLength 1, which becomes .min(1). pages has exclusiveMinimum 0, which becomes .gt(0), and since it is not in the required list it ends with .optional(). (Generated from the FastAPI Book API, pages is required and the .optional() goes away.)
Why a schema as well as types? Types vanish when the app runs. Zod checks real data while it runs:
// The generated Zod schema checks data while the app
// runs; the TypeScript types are gone by then.
import { CreateBookBody } from '../src/api/books.zod'
const book = { title: 'The Witches', author: 'Roald Dahl' }
const good = CreateBookBody.safeParse({ ...book, pages: 208 })
console.log('pages 208:', good.success)
const bad = CreateBookBody.safeParse({ ...book, pages: 0 })
console.log('pages 0:', bad.success, '-', bad.error?.issues[0].message)
pages 208: true
pages 0: false - Too small: expected number to be >0
A form can use this schema directly; that is the subject of Forms With React Hook Form and Zod.
The backend renames a field again
Back to the problem we started with. The spec's BookResponse.pages becomes pageCount. This time we run npm run api, and Orval rewrites the model file:
export interface BookResponse {
id?: number;
title?: string;
author?: string;
pageCount?: number;
}
BookList.tsx line 26 still says b.pages. Now the compiler has something to check it against:
npx tsc -b
src/BookList.tsx(26,35): error TS2339: Property 'pages' does not exist on type 'BookResponse'.
tsc exit code: 2
Line 26, column 35, exactly where pages starts. npm run build is tsc -b && vite build, so tsc fails first and the broken code never reaches a browser. Change the line to b.pageCount, run tsc -b again, and there are no errors.
One loop, two kinds of files
The server code produces the spec, npm run api turns it into src/api, tsc checks your code against it, and Vite builds. When the API changes, go round again.
| Generated (never edit) | Ours (never overwritten) |
|---|---|
src/api/books.ts | orval.config.ts |
src/api/books.zod.ts | orval.names.ts |
src/api/model/* | src/api/fetcher.ts |
Common mistakes
- Editing books.ts by hand. The next
npm run apiwrites the file again and your change is gone. Change the config or the spec instead. - Forgetting to regenerate. The types are only as new as the last
npm run api. - Trusting res.json() as a type. A cast is not a check. Use the generated types at build time and Zod at runtime.
Quick recap
| Piece | What it does |
|---|---|
/v3/api-docs | The API's own contract: paths and schemas |
npm run api | Orval writes types, hooks and Zod schemas |
orval.names.ts | Turns list into getBooks and useGetBooks |
useGetBooks(allBooks) | Replaces the hand-written fetch and useQuery |
CreateBookBody | The spec's rules, checked at runtime |
| Renamed field | TS2339 at an exact line, before the app runs |
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Server State With TanStack Query: One Key, One Request, One Cache
Three components need the same list of books. Fetch it by hand and you get three requests; ask TanStack Query for one key and you get one. With real request counts, retries and a quiet refetch on tab focus.
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Add a book with useMutation and let invalidateQueries refetch the list, then make delete instant: snapshot, remove the row in 3 ms, roll back on a 404 and refetch the truth in onSettled.
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Build the React screen before the API exists: Orval writes MSW handlers and faker data from the spec, a service worker answers GET /api/books inside the browser, and npm run dev:real switches back to the real server.
A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Generate a React client from FastAPI's /openapi.json, then hit the CORS wall: the API answers 200 but the browser blocks it. Fix it with CORSMiddleware, or avoid it with the Vite proxy and one VITE_API_URL variable.
