Speakeasy Logo
Skip to Content
OpenAPI HubFrameworksZod

How to generate an OpenAPI document with Zod

Zod is a powerful and flexible schema validation library for TypeScript, which many developers use to define their TypeScript data parsing schemas.

This tutorial demonstrates how to use another TypeScript library, the zod-openapi npm package, to convert Zod schemas into a complete OpenAPI document, and then how to use Speakeasy to generate a production-ready SDK from that document.

Why use Zod with OpenAPI?

Combining Zod with OpenAPI generation offers the best of both worlds: runtime validation and automatic API documentation. Instead of writing schemas twice – once for runtime validation and again for your OpenAPI document – you define your data models once in Zod and generate both TypeScript types and OpenAPI documentation from the same source.

This eliminates the task of keeping hand-written OpenAPI documents in sync with your actual API implementation. When paired with Speakeasy’s SDK generation, you get type-safe client libraries that automatically stay up to date with your API changes.

zod-openapi overview

The zod-openapi package is a TypeScript library that helps developers define OpenAPI schemas as Zod schemas. The stated goal of the project is to cut down on code duplication, and it does a wonderful job of this.

Zod schemas map well to OpenAPI schemas, and the changes required to extract OpenAPI documents from a schema defined in Zod are often small.

Key concepts

Here’s an overview of some key concepts in Zod and how they relate to Zod versioning.

Schemas and z.strictObject

Zod v4 introduces top-level helpers like z.strictObject() for objects that reject unknown keys and z.email() for email validation.

Field metadata

The .openapi() method adds OpenAPI-specific metadata like descriptions and examples to any Zod schema. Use z3 for OpenAPI schemas.

Operation objects

Use ZodOpenApiOperationObject to define API endpoints with request and response schemas.

Adding tags to operations

Tags help organize your API operations in the generated documentation and SDKs. You can add a tags array to each operation object:

Using Zod v4 features alongside OpenAPI documents

While your OpenAPI documents must use the z3 instance for compatibility, you can use z4 features for internal validation, type checking, or other parts of your application:

Step-by-step tutorial: From Zod to OpenAPI to an SDK

Now let’s walk through the process of generating an OpenAPI document and SDK for our Burgers and Orders API.

Requirements

This tutorial assumes basic familiarity with TypeScript and Node.js development.

The following should be installed on your machine:

Creating your Zod project

Alternatively, you can initialize a new npm project and install the required dependencies if you’re not using our burgers example.

If you’re following along, start by cloning the speakeasy-api/examples repository.

Next, install the dependencies:

Installing TypeScript development tools

For this tutorial, we’ll use tsx for running TypeScript directly:

Creating your app’s first Zod schema

Save this TypeScript code in a new file called index.ts. Note the dual import strategy:

Extending Zod with OpenAPI

We’ll add the openapi method to Zod by calling extendZodWithOpenApi once. Update index.ts to import extendZodWithOpenApi from zod-openapi, then call extendZodWithOpenApi on the z3 instance.

Registering and generating a component schema

Next, we’ll use the new openapi method provided by extendZodWithOpenApi to register an OpenAPI schema for the burgerSchema. Edit index.ts and add .openapi({ref: "Burger"} to the burgerSchema schema object.

We’ll also add an OpenAPI generator, OpenApiGeneratorV31, and log the generated component to the console as YAML.

Adding metadata to components

To generate an SDK that offers a great developer experience, we recommend adding descriptions and examples to all fields in OpenAPI components.

With zod-openapi, we’ll call the .openapi method on each field, and add an example and description to each field.

We’ll also add a description to the Burger component itself.

Edit index.ts and edit burgerSchema to add OpenAPI metadata.

Preparing to generate an OpenAPI document

Now that we know how to register components with metadata for our OpenAPI schema, let’s generate a complete schema document.

Import yaml and createDocument.

Generating an OpenAPI document

We’ll use the createDocument method to generate an OpenAPI document. We’ll pass in the burgerSchema and a title for the document.

Adding a burger ID schema

To make the burger ID available to other schemas, we’ll define a burger ID schema. We’ll also use this schema to define a path parameter for the burger ID later on.

Update the burgerSchema to use the BurgerIdSchema.

Adding a schema for creating burgers

We’ll add a schema for creating burgers that doesn’t include an ID. We’ll use this schema to define the request body for the create burger path.

Adding order schemas

To match the final OpenAPI output, let’s add schemas and endpoints for orders.

Defining burger and order operations

Now, define the operations for creating and getting burgers and orders, and listing burgers:

Adding a webhook that runs when a burger is created

We’ll add a webhook that runs when a burger is created. We’ll use the ZodOpenApiOperationObject type to define the webhook.

Registering all paths, webhooks, and extensions

Now, register all schemas, paths, webhooks, and the x-speakeasy-retries extension:

Speakeasy will read the x-speakeasy-* extensions to configure the SDK. In this example, the x-speakeasy-retries extension will configure the SDK to retry failed requests. For more information on the available extensions, see the extensions guide.

Generating the OpenAPI document

Run the index.ts file to generate the OpenAPI document.

The output will be a YAML file that looks like this:

Generating an SDK

With our OpenAPI document complete, we can now generate an SDK using the Speakeasy SDK generator.

Installing the Speakeasy CLI

First, install the Speakeasy CLI:

Linting your OpenAPI document

Before generating SDKs, lint your OpenAPI document to catch common issues:

Using AI to improve your OpenAPI document

The Speakeasy CLI now includes AI-powered suggestions to automatically improve your OpenAPI documents:

Follow the onscreen prompts to provide the necessary configuration details for your new SDK, such as the schema and output path.

Read the Speakeasy Suggest documentation for more information on how to use Speakeasy Suggest.

Generating your SDK

Now you can generate your SDK using the quickstart command:

Follow the onscreen prompts to provide the necessary configuration details for your new SDK, such as the name, schema location, and output path. Enter openapi.yaml (or your improved OpenAPI document if you used suggestions) when prompted for the OpenAPI document location, and select your preferred language when prompted.

Using your generated SDK

Once you’ve generated your SDK, you can publish it for use. For TypeScript, you can publish it as an npm package.

TypeScript SDKs generated with Speakeasy include an installable Model Context Protocol (MCP) server where the various SDK methods are exposed as tools that AI applications can invoke. Your SDK documentation includes instructions for installing the MCP server.

Adding SDK generation to your CI/CD pipeline

The Speakeasy sdk-generation-action repository provides workflows for integrating the Speakeasy CLI into CI/CD pipelines to automatically regenerate SDKs when your Zod schemas change.

You can set up Speakeasy to automatically push a new branch to your SDK repositories so that your engineers can review and merge the SDK changes.

For an overview of how to set up automation for your SDKs, see the Speakeasy SDK workflow syntax reference.

Summary

In this tutorial, we learned how to generate OpenAPI schemas from Zod and create client SDKs with Speakeasy.

By following these steps, you can ensure that your API is well-documented, easy to use, and offers a great developer experience.

Further reading

This guide covered the basics of generating an OpenAPI document using zod-openapi. Here are some resources to help you learn more about Zod, OpenAPI, and Speakeasy:

Last updated on