.../articles/
Generating FastAPI Schema Classes from OpenAPI

Generating FastAPI Schema Classes from OpenAPI

2022.03.04

What's good about generating the schema classes used by FastAPI from an OpenAPI definition?

  • You can verify the design using only the OpenAPI definition
  • No need to write the classes in FastAPI by hand

Preparing OpenAPI

We prepare the FastAPI source code and the OpenAPI definition with a layout like this. By the way, the definition file's path is generated/openapi.json because we use openapi-generator to generate openapi.json, and this is a common setup at our company.

project
  L api
    L main.py         : FastAPI's main.py
  L schema
    L generated
      L openapi.json  : OpenAPI definition file

Installing datamodel-code-generator

To generate schema classes from the OpenAPI definition, we use datamodel-code-generator. Run the following command to install it into your python environment.

# Install command
$ pip install datamodel-code-generator
$ datamodel-codegen --version
0.11.19

Outputting schemas.py

Next, run the following command to output the schema file into the FastAPI project.

datamodel-codegen  --input /schema/generated/openapi.json --input-file-type openapi --output api/schemas.py

As an example, running this against the following OpenAPI definition produced python source code like this.

schema/generated/openapi.json

{
  "openapi" : "3.0.3",
  "info" : {
    "title" : "api",
    "version" : "0.0.1"
  },
  "servers" : [ {
    "url" : "/"
  } ],
  "tags" : [ {
    "description" : "index",
    "name" : "index"
  } ],
  "paths" : {
    "/" : {
      "post" : {
        "description" : "POST",
        "operationId" : "IndexPost",
        "requestBody" : {
          "content" : {
            "application/json" : {
              "schema" : {
                "$ref" : "#/components/schemas/IndexPostRequest"
              }
            }
          },
          "description" : "POST",
          "required" : true
        },
        "responses" : {
          "200" : {
            "content" : {
              "application/json" : {
                "schema" : {
                  "$ref" : "#/components/schemas/IndexPostResponse"
                }
              }
            },
            "description" : "OK"
          }
        },
        "tags" : [ "index" ]
      }
    }
  },
  "components" : {
    "schemas" : {
      "IndexPostRequest" : {
        "properties" : {
          "name" : {
            "type" : "string"
          }
        },
        "type" : "object"
      },
      "IndexPostResponse" : {
        "properties" : {
          "hello" : {
            "type" : "string"
          }
        },
        "type" : "object"
      }
    }
  }
}

api/schemas.py

# generated by datamodel-codegen:
#   filename:  openapi.json
#   timestamp: 2022-02-25T07:02:11+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel

class IndexPostRequest(BaseModel):
    name: Optional[str] = None

class IndexPostResponse(BaseModel):
    hello: Optional[str] = None

Implementing in FastAPI

Let's implement the generated schemas.py in FastAPI. We changed api/main.py as follows.

api/main.py

from FastAPI import FastAPI

from schemas import IndexPostRequest, IndexPostResponse
app = FastAPI()

@app.post("/", response_model=IndexPostResponse)
def read_root(request:IndexPostRequest) -> IndexPostResponse:
    response = IndexPostResponse()
    response.hello = request.name
    return response

Verifying it works

We ran FastAPI locally and executed the following command to check that it behaves as expected.

$ curl -X 'POST' \
  'http://0.0.0.0:8000/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "name": "World"
}'

{"hello":"World"}

We got the expected value back.

Summary

OpenAPI has such a rich set of class generation tools available, which is really great.

written by

.../article/

Articles

All articles

From Firebase to Vercel, Contentful to microCMS — a migration log written with Claude Code

From Firebase to Vercel, Contentful to microCMS — a migration log written with Claude Code

We moved our corporate site's hosting and CMS, and made it bilingual along the way. The constraints we only found by running against real data were more useful than the migration itself, so this post focuses on where we got stuck.

Can't Read POST Data with Firebase Functions × Remix?

Can't Read POST Data with Firebase Functions × Remix?

How to read POST data from a Remix action when running on Firebase Functions.

Generative AI for Executives and Leaders: An Approach to Self-Driven DX

Generative AI for Executives and Leaders: An Approach to Self-Driven DX

Building a structure where executives and leaders themselves can identify issues and evaluate solutions using generative AI. We introduce how combining this with our hands-on support dramatically improves both the quality and speed of digital transformation.

Deploying a Monorepo Next.js App (App Router) to AWS Amplify

Deploying a Monorepo Next.js App (App Router) to AWS Amplify

Notes on the obstacles we hit while deploying a Next.js app managed in a monorepo to AWS Amplify.

Keeping Production Running Smoothly with Remote Work and Online Meetings [Documentation]

Keeping Production Running Smoothly with Remote Work and Online Meetings [Documentation]

Many production companies have adopted remote work as a result of the pandemic, and we are one of them.

Designing an E-Commerce Site That Sells: How to Find Great Reference Examples

Designing an E-Commerce Site That Sells: How to Find Great Reference Examples

There is no single formula for e-commerce design that sells. Driving revenue requires a solid concept, and getting to that concept requires thorough research.

Productivity Tools We Recommend as a Production Company, Including Services That Work Well Solo

Productivity Tools We Recommend as a Production Company, Including Services That Work Well Solo

With remote work becoming the norm during the COVID-19 pandemic, our team now works from home most days of the week.

We Released Thought Recorder, a Figma Plugin for Keeping a Commit History of Your Designs

We Released Thought Recorder, a Figma Plugin for Keeping a Commit History of Your Designs

We hope this helps web designers who work in Figma. Read on for how to use it.

How to Build an E-Commerce Site, and Which Platforms We Recommend

How to Build an E-Commerce Site, and Which Platforms We Recommend

Shopping online for fashion, appliances, and even groceries is now routine. With the pandemic accelerating the shift, we receive a steady stream of questions about which platform to use and how much it costs.

Generating FastAPI Schema Classes from OpenAPI

Generating FastAPI Schema Classes from OpenAPI

We chose FastAPI, a relatively modern framework, for a Python API project. FastAPI can generate an OpenAPI definition from your backend code, but here we do the opposite: generating FastAPI schema classes from an OpenAPI definition prepared in advance.

View all articles

Contact us