OpenAPI → TS
Generate TypeScript interfaces and Zod schemas from any OpenAPI spec.
Runs entirely in your browser. No server calls.
How to use OpenAPI → TS
Paste your spec
Drop an OpenAPI 3.x YAML or JSON spec into the left panel, or load one of the samples.
Set options and convert
Choose naming, HTTP client, and validation style, then click Convert or press ⌘↵.
Copy the output
Switch between types, schemas, client, and hooks tabs. Copy or download any tab.
Frequently asked questions
Is this free?↓
Yes, completely free. No sign-up, no rate limits.
Does my code get sent to a server?↓
No. All conversion runs entirely in your browser using JavaScript. Nothing is sent to any server.
Which OpenAPI versions are supported?↓
OpenAPI 3.x (3.0 and 3.1). YAML and JSON are both accepted.
Are $ref cross-file references supported?↓
Local $ref within the same document are resolved. External file or URL references are not supported.
Try other tools
View allLong-form guide
Turn an OpenAPI spec into TypeScript types and Zod schemas
OpenAPI → TypeScript generates the type system, runtime validators, and HTTP client that your frontend would otherwise hand-write to talk to a documented API. Drop in an OpenAPI 3.0 or 3.1 spec — YAML or JSON — and you'll get a tight set of TypeScript interfaces, optional Zod schemas, an HTTP client (fetch or axios), and TanStack Query hooks per operation. All of it runs in your browser; the spec never goes to a server.
How to use it
- Drop in or paste your spec. The left panel accepts either YAML or JSON. You can paste up to a few megabytes; the editor uses Monaco so very large specs feel responsive. Use the Sample selector to load a typical PetStore spec if you want to see what it produces before pasting your own.
- Pick options. Naming controls how operations and schemas are named —
PascalCaseis the default and produces names likeLoginRequestandUser. HTTP client toggles betweenfetch(zero dependencies) andaxios(usesaxios.create). Validation lets you emit Zod schemas alongside or instead of plain interfaces. Base URL gets prepended to every generated request URL — leave it empty for relative paths. - Click Convert (or press ⌘↵). The output panel splits into tabs: types, schemas, client, hooks. Each tab is independently copyable and downloadable, so you can drop just the types into one file and the client into another.
- Copy or download. Per-tab copy buttons live in the top-right of each output. The download button packages the active tab into a
.tsfile with the right header.
What the generator handles
Every schema in components.schemas becomes either a plain interface (when validation is off) or a Zod schema with an inferred type (when validation is on). oneOf, anyOf, and allOf map to TypeScript discriminated unions, intersections, and so on. Required vs optional properties are tracked, as are nullable types and enums. Format hints — uuid, email, date-time — propagate into Zod's z.string().uuid() etc.
Operations from paths become functions on the generated client. Path parameters are encoded into the URL, query parameters are appended, request bodies are serialized as JSON. Each operation also produces a TanStack Query hook (useQuery for GETs, useMutation for everything else) with the right cache key and the correct response type.
Local $ref is resolved fully, including recursive types and circular references. External references (other files, remote URLs) are not handled — bundle your spec first with a tool like swagger-cli bundle if you need them. OpenAPI 3.0 and 3.1 are both accepted; the tool autodetects.
When to reach for it
The classic case is starting a frontend against a finished backend. Instead of writing types by hand and watching them drift, you import the spec, generate the client, and ship. When the backend changes, you re-run the converter and TypeScript points to anything that broke.
Another good fit is contract testing. You can generate Zod schemas from your spec and run them as runtime checks in your tests, catching the moment a response stops matching documentation. And for documentation reviews, the generator shows you exactly which TypeScript shape a backend team's spec implies — useful when the words are vague but the schema is precise.
OpenAPI → TypeScript генерирует систему типов, рантайм-валидаторы и HTTP-клиент, которые иначе пришлось бы писать руками, чтобы фронтенд говорил с задокументированным API. Вставь OpenAPI 3.0 или 3.1 — YAML или JSON — и получи плотный набор TypeScript-интерфейсов, опционально Zod-схемы, HTTP-клиент (fetch или axios) и TanStack Query хуки на каждую операцию. Всё работает в браузере; спека никуда не отправляется.
Как использовать
- Вставь или перетащи спеку. Левая панель принимает YAML или JSON. Можно вставить несколько мегабайт — редактор на Monaco остаётся отзывчивым даже на больших спеках. В селекторе Sample есть стандартная PetStore спека, чтобы посмотреть результат до того, как вставлять свою.
- Настрой опции. Naming управляет именованием операций и схем —
PascalCaseпо умолчанию даётLoginRequest,User. HTTP client переключает междуfetch(без зависимостей) иaxios(axios.create). Validation включает Zod-схемы рядом с интерфейсами или вместо них. Base URL подставляется перед каждым URL запроса — оставь пустым для относительных путей. - Нажми Convert (или ⌘↵). Результат разделён на вкладки: types, schemas, client, hooks. Каждую можно скопировать и скачать отдельно — типы в один файл, клиент в другой.
- Скопируй или скачай. Кнопки копирования — в правом верхнем углу каждой вкладки. Кнопка скачивания запаковывает активную вкладку в
.tsфайл с правильным заголовком.
Что обрабатывает генератор
Каждая схема в components.schemas становится либо обычным интерфейсом (если валидация выключена), либо Zod-схемой с выводом типа (если включена). oneOf, anyOf, allOf маппятся в discriminated unions, intersections и т.д. Required vs optional поля отслеживаются, nullable-типы и enums тоже. Format-подсказки — uuid, email, date-time — пробрасываются в z.string().uuid().
Операции из paths становятся функциями сгенерированного клиента. Path-параметры кодируются в URL, query-параметры добавляются, request body сериализуется в JSON. Каждая операция даёт также TanStack Query хук (useQuery для GET, useMutation для остального) с правильным cache key и корректным response type.
Локальные $ref разрешаются полностью, включая рекурсивные и циклические типы. Внешние ссылки (другие файлы, удалённые URL) не обрабатываются — сначала собери спеку через swagger-cli bundle. OpenAPI 3.0 и 3.1 принимаются оба, формат определяется автоматически.
Когда это пригодится
Классика — старт фронтенда против готового бэкенда. Вместо того чтобы писать типы руками и наблюдать, как они отстают, импортируешь спеку, генерируешь клиент, поехали. Когда бэкенд меняется — пере-запускаешь конвертер и TypeScript указывает на всё, что сломалось.
Другой кейс — контрактное тестирование. Можно сгенерировать Zod-схемы из спеки и гонять их как рантайм-проверки в тестах, ловя момент, когда ответ перестаёт соответствовать документации. И для ревью документации генератор показывает, какую именно TypeScript-форму подразумевает спека команды — полезно, когда слова размыты, а схема точна.
Examples
openapi: 3.0.0
info:
title: My API
version: 1.0.0
components:
schemas:
User:
type: object
required: [id, email]
properties:
id:
type: string
email:
type: string
name:
type: stringexport interface User {
id: string;
email: string;
name?: string;
}components:
schemas:
Post:
type: object
required: [id, title]
properties:
id:
type: string
format: uuid
title:
type: string
body:
type: stringimport { z } from 'zod';
export const PostSchema = z.object({
id: z.string().uuid(),
title: z.string(),
body: z.string().optional(),
});
export type Post = z.infer<typeof PostSchema>;paths:
/users/{id}:
get:
operationId: getUser
parameters:
- in: path
name: id
required: true
schema: { type: string }
responses:
'200':
content:
application/json:
schema: { $ref: '#/components/schemas/User' }export function useGetUser(id: string) {
return useQuery({
queryKey: ['getUser', id],
queryFn: () => request<User>(`/users/${id}`),
});
}