OpenAPI tutorial: document and validate a REST API

By

Updated

Tagged: Networking

Learn OpenAPI by building a books API with reusable schemas, request validation, interactive documentation, and generated TypeScript types.

Working with an HTTP API gets a whole lot easier when there’s an explicit contract behind it. Without one, you end up guessing which endpoints exist, what parameters they take, what a valid request body looks like, which fields are required, and what kind of responses come back.

OpenAPI gives you a machine-readable way to describe all of that in one place. From a single OpenAPI document, you can generate reference docs, validate incoming requests, produce typed clients, and catch accidental breaking changes before they ship.

In this tutorial, we’ll build a small books API with Hono, Zod, and OpenAPI. It will expose three endpoints:

GET  /books
GET  /books/{id}
POST /books

The nice part about this setup is that we define each route once, and that same definition handles both request validation and the OpenAPI document.

Create the project

Start by scaffolding a new Hono Node.js app:

npm create hono@latest books-api
cd books-api

Pick the Node.js template when prompted, then install the OpenAPI packages:

npm install @hono/zod-openapi @scalar/hono-api-reference

@hono/zod-openapi ties Hono routes, Zod validation, and OpenAPI metadata together. Scalar takes the generated document and renders it as an interactive API reference.

Create the first schema

Create src/app.ts and add our first schema:

import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi'
import { Scalar } from '@scalar/hono-api-reference'

const app = new OpenAPIHono()
export default app

const BookSchema = z
  .object({
    id: z.string().openapi({ example: 'book_1' }),
    title: z.string().openapi({ example: 'The Hobbit' }),
    author: z.string().openapi({ example: 'J. R. R. Tolkien' }),
    year: z.number().int().openapi({ example: 1937 }),
  })
  .openapi('Book')

const ErrorSchema = z
  .object({
    error: z.string(),
  })
  .openapi('Error')

const books = [
  {
    id: 'book_1',
    title: 'The Hobbit',
    author: 'J. R. R. Tolkien',
    year: 1937,
  },
]

Keep the Node.js server entry point separate in src/index.ts:

import { serve } from '@hono/node-server'
import app from './app.js'

serve({
  fetch: app.fetch,
  port: 3000,
})

Keeping the app separate from the server startup means we can import it directly in tests later without opening a network port.

A schema defines the shape of your data. Here, .openapi('Book') gives it a reusable name inside the generated document, and the example values make the API reference easier to read without affecting validation.

Describe GET /books

Start with the route definition for listing books:

const listBooksRoute = createRoute({
  method: 'get',
  path: '/books',
  operationId: 'listBooks',
  summary: 'List all books',
  responses: {
    200: {
      description: 'A list of books',
      content: {
        'application/json': {
          schema: z.object({
            books: z.array(BookSchema),
          }),
        },
      },
    },
    500: {
      description: 'Internal server error',
      content: {
        'application/json': {
          schema: ErrorSchema,
        },
      },
    },
  },
})

Now attach its handler:

app.openapi(listBooksRoute, (c) => {
  return c.json({ books }, 200)
})

The route declares that a 200 response returns JSON with a books array. In OpenAPI, those response keys are HTTP status codes that describe what the endpoint can return, though they don’t send the response for you.

Add a path parameter

GET /books/{id} needs an ID from the URL, so let’s define a schema for that path parameter first:

const BookParamsSchema = z.object({
  id: z.string().openapi({
    param: {
      name: 'id',
      in: 'path',
    },
    example: 'book_1',
  }),
})

Next, define the route with its success and error responses:

const getBookRoute = createRoute({
  method: 'get',
  path: '/books/{id}',
  operationId: 'getBook',
  summary: 'Get one book',
  request: {
    params: BookParamsSchema,
  },
  responses: {
    200: {
      description: 'The requested book',
      content: {
        'application/json': {
          schema: BookSchema,
        },
      },
    },
    404: {
      description: 'Book not found',
      content: {
        'application/json': {
          schema: ErrorSchema,
        },
      },
    },
    500: {
      description: 'Internal server error',
      content: {
        'application/json': {
          schema: ErrorSchema,
        },
      },
    },
  },
})

The curly braces in /books/{id} are OpenAPI’s syntax for a path parameter. Here’s the handler implementation:

app.openapi(getBookRoute, (c) => {
  const { id } = c.req.valid('param')
  const book = books.find((item) => item.id === id)

  if (!book) {
    return c.json({ error: 'Book not found' }, 404)
  }

  return c.json(book, 200)
})

c.req.valid('param') gives us the validated parameter value straight away, so we don’t have to parse the URL manually inside the handler.

Validate a request body

The create endpoint should accept a title, an author, and a year, and the client shouldn’t be allowed to pick the ID. Let’s create a separate input schema for that:

const NewBookSchema = z
  .object({
    title: z.string().min(1),
    author: z.string().min(1),
    year: z.number().int().min(1000).max(2100),
  })
  .openapi('NewBook')

Validation errors need a documented shape too, so define a schema for them as well:

const ValidationIssueSchema = z.object({
  code: z.string(),
  path: z.array(z.union([z.string(), z.number()])),
  message: z.string(),
})

const ValidationErrorSchema = z
  .object({
    error: z.string(),
    issues: z.array(ValidationIssueSchema),
  })
  .openapi('ValidationError')

Now wire both schemas into the POST /books route definition:

const createBookRoute = createRoute({
  method: 'post',
  path: '/books',
  operationId: 'createBook',
  summary: 'Create a book',
  request: {
    body: {
      required: true,
      content: {
        'application/json': {
          schema: NewBookSchema,
        },
      },
    },
  },
  responses: {
    201: {
      description: 'The created book',
      content: {
        'application/json': {
          schema: BookSchema,
        },
      },
    },
    400: {
      description: 'Malformed JSON request body',
      content: {
        'application/json': {
          schema: ErrorSchema,
        },
      },
    },
    422: {
      description: 'Request validation failed',
      content: {
        'application/json': {
          schema: ValidationErrorSchema,
        },
      },
    },
    500: {
      description: 'Internal server error',
      content: {
        'application/json': {
          schema: ErrorSchema,
        },
      },
    },
  },
})

And add the handler:

app.openapi(createBookRoute, (c) => {
  const input = c.req.valid('json')

  const book = {
    id: `book_${books.length + 1}`,
    ...input,
  }

  books.push(book)
  return c.json(book, 201)
})

If you try sending an invalid year or leaving out the author, the request gets rejected before the handler ever runs. Because the validation is driven by the contract itself, you don’t have to rely on comments or hope clients send the right fields.

Generate the OpenAPI document

Add this after your API routes to serve the generated spec:

app.doc('/openapi.json', {
  openapi: '3.1.0',
  info: {
    title: 'Books API',
    version: '1.0.0',
    description: 'A small API for managing books',
  },
})

Run the development server and open this URL in your browser (the entry point in src/index.ts runs on port 3000):

http://localhost:3000/openapi.json

You’ll see a JSON document containing four main sections:

  • openapi, the specification version
  • info, metadata about this API
  • paths, the available endpoints
  • components.schemas, reusable data shapes

OpenAPI 3.2 is the newest spec version, though tooling support tends to arrive gradually. We’re emitting 3.1 here because the libraries in this project support it well.

Notice that info.version is separate from the OpenAPI format version. 1.0.0 is the version of our books API.

Add interactive documentation

Raw OpenAPI JSON works fine for tooling, though nobody wants to read through it by hand while trying to use an endpoint. Mount Scalar to serve an interactive reference page:

app.get(
  '/docs',
  Scalar({
    url: '/openapi.json',
    pageTitle: 'Books API',
  })
)

Open /docs in your browser. You can browse every operation, inspect the schemas, look at examples, and send requests straight from the page. Scalar renders everything from the OpenAPI document, so that spec stays the single source of truth.

Add error responses for invalid input

Validation errors are part of your API’s public behavior too. By default, @hono/zod-openapi returns its own validation response, though for a real API you’ll want to pick and document the exact error shape yourself.

Replace the earlier const app = new OpenAPIHono() line with one that sets a default validation hook:

const app = new OpenAPIHono({
  defaultHook: (result, c) => {
    if (!result.success) {
      return c.json(
        {
          error: 'Invalid request',
          issues: result.error.issues,
        },
        422
      )
    }
  },
})

Malformed JSON fails during parsing, before Zod ever gets to validate the body. Import HTTPException to handle that case:

import { HTTPException } from 'hono/http-exception'

Then add an error handler right after initializing the app:

app.onError((error, c) => {
  if (error instanceof HTTPException && error.status === 400) {
    return c.json({ error: error.message }, 400)
  }

  return c.json({ error: 'Internal server error' }, 500)
})

Now POST /books documents and handles both failure modes: invalid JSON returns 400, and valid JSON with the wrong fields returns 422. Keeping errors predictable like this means clients don’t have to write three different error parsers for three different endpoints.

Generate TypeScript types

An OpenAPI document lets you generate client-side types without sharing any server source code. If you want to try that right in the browser without installing a generator, check out the OpenAPI to TypeScript tool.

To generate types locally, install openapi-typescript. Since the current release requires TypeScript 5, pin a compatible TypeScript version alongside it:

npm install --save-dev typescript@^5.9.3 openapi-typescript

With the server running, pull the spec and generate the types file:

npx openapi-typescript http://localhost:3000/openapi.json \
  --output src/api-types.d.ts

This creates runtime-free TypeScript types for your paths, operations, and schemas. The operation entries come from the unique operationId values in our route definitions.

Add a script to package.json so it’s easy to re-run:

{
  "scripts": {
    "generate:api": "openapi-typescript http://localhost:3000/openapi.json --output src/api-types.d.ts"
  }
}

Whenever the types need to change, update the API schema and regenerate this file instead of editing it by hand.

If your frontend lives in a separate repository, you can publish the OpenAPI document at a stable URL or save it as a CI artifact, then let the frontend generate its types from there. Keep in mind that openapi-typescript only produces types, not an HTTP client, so you’ll pair it with a runtime client like openapi-fetch.

Test the contract

Even though our routes and OpenAPI document come from the same definitions, you still want tests covering how the endpoints behave.

Hono can invoke the app in memory without starting a network server:

npm install --save-dev vitest

Use that to create src/app.test.ts:

import { describe, expect, test } from 'vitest'
import app from './app.js'

describe('POST /books', () => {
  test('rejects an invalid book', async () => {
    const response = await app.request('/books', {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        title: '',
        author: 'Someone',
        year: 20,
      }),
    })

    expect(response.status).toBe(422)
  })
})

Add a test script to package.json:

{
  "scripts": {
    "test": "vitest run src/app.test.ts"
  }
}

If your generated TypeScript config compiles every file under src, exclude test files from the production build:

{
  "exclude": ["node_modules", "src/**/*.test.ts"]
}

Write tests for every documented status code, especially the error cases.

One thing to watch out for: @hono/zod-openapi validates incoming requests at runtime, while response schemas only provide TypeScript checking and documentation. They don’t validate the returned JSON at runtime.

When a response payload matters, you can parse it explicitly in your tests with Zod:

return c.json(BookSchema.parse(book), 200)

Validating responses like this catches cases where your handler returns the wrong shape before any client runs into it.

Detect breaking changes

Suppose you rename author to authorName in the book schema. On the server side that looks like a quick refactor, until every client reading author breaks.

Save the released OpenAPI document in your repository or download it from production, then compare it against the new document in CI using an OpenAPI diff tool.

Changes that usually break clients include:

  • removing an endpoint
  • removing a response field
  • making an optional field required
  • changing a field’s type
  • removing an accepted enum value

Adding an optional response field is generally safe, as long as clients ignore unknown fields.

Treat the spec diff as one CI check alongside your tests, since a change can look non-breaking on paper and still change what an endpoint does.

Design the contract first or generate it from code?

In a design-first workflow, you write openapi.yaml before implementing the API. Teams review the contract up front and generate server stubs and clients from it.

In a code-first workflow, your route definitions generate the document, which is what we did here.

Neither workflow is automatically better. Design-first works well when several teams need to agree on the API before implementation starts, while code-first cuts down on duplication in a smaller TypeScript project.

What you want to avoid is keeping a handwritten document that nobody checks against the running API. It drifts out of date quickly and starts telling clients the wrong thing.

What to put in a production document

Our example document is intentionally small. A public API usually also describes:

  • authentication under components.securitySchemes
  • pagination parameters and metadata
  • rate-limit responses
  • idempotency keys for retryable writes
  • examples for important requests and errors
  • tags that group related operations
  • server URLs for development and production

When you write field descriptions, explain what the value means rather than repeating the field name.

This doesn’t tell the caller anything useful:

author:
  description: The author

This gives them context they can use right away:

author:
  description: The name printed as the book's primary author

Spending a few seconds on clear descriptions while you define each schema saves anyone calling your API from guessing how a field behaves.

Want me to talk about your product? You can sponsor this site.

Related posts about network: