Loading OpenAPI to Python Converter...
Please wait a moment

How to Convert OpenAPI to Pydantic Models - Step by Step Guide

From an OpenAPI 3 or Swagger 2 file to Python classes that validate the JSON an API sends

Step 1

Paste or upload the spec

Paste an OpenAPI 3 or Swagger 2.0 file in YAML or JSON. The converter looks at components/schemas (OpenAPI 3) or definitions (Swagger 2) and writes one Python type per schema:

•
Paste it: copy the spec from Swagger Editor, your repository, or the /openapi.json a FastAPI app serves
•
Upload a file: click "Upload" to open an openapi.yaml, swagger.json or .yml file
•
Try the sample: click "Sample" to load a shop API with products, categories and orders

Example: a spec with one schema

A Product with an enum, a list and a key that isn't a Python name:

openapi: 3.0.3
info:
  title: Shop
  version: 1.0.0
paths: {}
components:
  schemas:
    Product:
      type: object
      description: A product in the catalogue
      required: [id, name, price]
      properties:
        id: { type: integer, format: int64 }
        name: { type: string }
        price: { type: number }
        currency:
          type: string
          enum: [USD, EUR, GBP]
        tags:
          type: array
          items: { type: string }
        first-seen: { type: string, format: date }
Step 2

Read the generated models

Each object schema becomes a Pydantic v2 BaseModel class:

•
Required vs optional: fields in required have no default; the rest are Optional[...] = None
•
Enums: become Literal[...], so any other value fails validation
•
Odd keys: first-seen becomes first_seen with Field(alias='first-seen'), so the JSON still matches

Example: the Python code for the spec above

This is exactly what the converter writes for the Step 1 example:

from __future__ import annotations

from typing import List, Literal, Optional

from pydantic import BaseModel, ConfigDict, Field

# Pydantic v2 models for the components/schemas of "Shop" 1.0.0.
# Read JSON with Product.model_validate_json(text); write it back with .model_dump_json(by_alias=True).


# A product in the catalogue
class Product(BaseModel):
    model_config = ConfigDict(populate_by_name=True)

    id: int
    name: str
    price: float
    currency: Optional[Literal['USD', 'EUR', 'GBP']] = None
    tags: Optional[List[str]] = None
    first_seen: Optional[str] = Field(default=None, alias='first-seen')


Product.model_rebuild()
Step 3

Copy the file into your Python project

Save the code as models.py and install pydantic 2. Reading a response with any HTTP client looks like this:

import httpx

from models import Product

resp = httpx.get("https://api.example.com/products/8901240544102066246")
product = Product.model_validate_json(resp.text)
print(product.id, product.first_seen)

# back to JSON with the original keys ("first-seen")
print(product.model_dump_json(by_alias=True, exclude_none=True))

The same classes work as request and response models in FastAPI. Want to check the spec first? The OpenAPI Validator points out structural problems before you generate code.

What is OpenAPI to Python Conversion?

An OpenAPI (or older Swagger) file describes the JSON an API sends and receives. Turning those schemas into Pydantic models gives you classes that check every response as it comes in: a missing required field or an enum value the spec doesn't allow raises a clear error instead of turning into a bug three functions later.

The output is a single plain Python file you can read and edit. Descriptions from the spec turn into comments, field names stay as the API spells them wherever Python allows it, and the few keys that can't be Python names get an alias, so model_dump_json(by_alias=True) writes the same JSON back.

This page writes the data models only. For a full client with a function for every endpoint, openapi-python-client is the usual choice. Got a Swagger 2 file you'd like to move to OpenAPI 3? Try Swagger to OpenAPI, or JSON to Python if all you have is a sample response.

Frequently Asked Questions

Which OpenAPI versions and formats can I paste?

OpenAPI 3.0 and 3.1 and Swagger 2.0, as YAML or JSON. The models come from components/schemas in OpenAPI 3 and from definitions in Swagger 2. Paths, parameters and inline request or response schemas are not turned into models; if you need one, move it into components/schemas and point at it with $ref.

How are OpenAPI types mapped to Python?

string becomes str, integer becomes int, number becomes float and boolean becomes bool. Python ints have no size limit, so a long ID like 8901240544102066246 is read and written back with every digit, whatever the format says. Arrays become List[...], an object with additionalProperties becomes Dict[str, ...], and an object with properties becomes its own class named after the parent and the field, such as OrderShippingAddress. Formats like date-time stay str, so the value comes back exactly as the API sent it.

What happens to required, nullable and optional fields?

A field listed in required has no default, so pydantic refuses a response that leaves it out. A field that is not required becomes Optional[...] = None. A required field that is also nullable (nullable: true, x-nullable, or "null" in an OpenAPI 3.1 type list) is Optional[...] with no default: it must be present but may be null.

How are $ref, allOf, oneOf and enums handled?

A $ref to another schema in the same file uses that model. Classes can refer to each other in any order, and model_rebuild() calls at the end of the file resolve the references. allOf is merged into one class with every property and required field from its parts. oneOf and anyOf become Union[...]. Enums of strings, integers or booleans become Literal[...] types, so pydantic rejects any other value; enums of decimal numbers stay float with the allowed values in a comment.

What happens to keys that are not valid Python names?

Keys like first-name, 2nd, class, json or _id are renamed to first_name, field_2nd, class_, json_ and id (or id_2 if id is taken), and the original key goes into Field(alias=...). The class then gets populate_by_name=True, so you can build it with either spelling, and model_dump_json(by_alias=True) writes the original keys back. Keys that are already fine Python names, including camelCase ones, are left as they are.

Are default and enum values copied exactly?

Yes. Enum values go into Literal[...] exactly as written, so 8901240544102066246 keeps every digit. Defaults are copied into a comment above the field, "00501" with its leading zeros and 14.50 with its trailing zero; the field itself still defaults to None, so add the default yourself if you want pydantic to fill it in.

Is my spec uploaded anywhere?

No. The spec is read and converted in your browser and is not sent to our server. Nothing is kept either: a reload starts with an empty editor.