Skip to main content

Generate FastAPI docs from msgspec.Struct json schema

· 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

FastAPI automatically generates documentation for msgspec.Struct models because msgspec provides a method to generate a JSON Schema for its structs. FastAPI and the underlying Pydantic library use JSON Schema to build the interactive API documentation (Swagger UI/OpenAPI). When you use a msgspec.Struct as a type hint in your endpoint, FastAPI calls msgspec to get the schema and incorporates it into the documentation.


How it Works​

The process is seamless and requires no extra configuration. msgspec models are first-class citizens in FastAPI because of the shared reliance on the OpenAPI standard and JSON Schema.

Here's the sequence of events:

  1. You define a data model using msgspec.Struct.
  2. You use this model as a request body or response model in your FastAPI endpoint.
  3. When FastAPI generates its OpenAPI schema, it inspects your function's type hints.
  4. If it sees a msgspec.Struct, it calls msgspec.json.schema() to get the JSON Schema representation of that struct.
  5. This schema is then embedded in the final OpenAPI documentation, which powers the interactive docs at /docs and /redoc.

Example​

This example demonstrates how a msgspec.Struct is automatically converted into a detailed JSON Schema that appears in your FastAPI documentation.

import msgspec
from fastapi import FastAPI
from typing import Optional

# Define a msgspec.Struct model
class User(msgspec.Struct):
name: str
email: str
age: Optional[int] = None
is_active: bool = True

# Create the FastAPI app
app = FastAPI()

# Use the msgspec.Struct as a request body
@app.post("/users/")
def create_user(user: User):
"""
Creates a new user with the provided data.
"""
return user

# Run the application
# uvicorn main:app --reload

After you run this application and navigate to http://127.0.0.1:8000/docs, you will see a fully-formed API endpoint with a detailed schema for the User model, including fields, types, and default values.

The Generated Schema​

Under the hood, when FastAPI generates its documentation, msgspec produces a schema similar to this:

{
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"age": {
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
]
},
"is_active": {
"type": "boolean",
"default": true
}
},
"required": [
"name",
"email"
],
"title": "User",
"type": "object"
}

This is the standard format that FastAPI understands and uses to render the interactive documentation. You can view the full OpenAPI schema yourself by navigating to http://127.0.0.1:8000/openapi.json.

Conclusion: The synergy between msgspec and FastAPI is a key benefit of using these libraries together. The documentation is a direct result of their shared commitment to the OpenAPI standard, making the process of generating accurate and useful API docs seamless.