Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Working with APIs

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Working with APIs

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.

From spec to generated client Book API /v3/api-docs Orval npm run api model/ types books.ts: functions + hooks books.zod.ts: Zod schemas generated: do not edit
One command reads the spec and writes three things. Everything in 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,
          },
        },
      },
    },
  },
})
  • input points Orval at the live spec.
  • schemas writes one TypeScript type per schema into src/api/model.
  • client: 'react-query' writes, for each operation, a fetch function and a TanStack Query hook into books.ts (713 lines in this run).
  • mutator sends every generated request through customFetch in our own fetcher.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.tsorval.config.ts
src/api/books.zod.tsorval.names.ts
src/api/model/*src/api/fetcher.ts

Common mistakes

  • Editing books.ts by hand. The next npm run api writes 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

PieceWhat it does
/v3/api-docsThe API's own contract: paths and schemas
npm run apiOrval writes types, hooks and Zod schemas
orval.names.tsTurns list into getBooks and useGetBooks
useGetBooks(allBooks)Replaces the hand-written fetch and useQuery
CreateBookBodyThe spec's rules, checked at runtime
Renamed fieldTS2339 at an exact line, before the app runs

Keep going in React · 55 of 59

Previous
Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
Next post
A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A hand-written client drifts silently
  • The API describes itself
  • Orval reads the contract
  • Names come from the operation ids
  • A spec field becomes a property
  • Inside the generated hook
  • The hook replaces api.ts
  • The same rules at runtime with Zod
  • The backend renames a field again
  • One loop, two kinds of files
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.