From a48372a9b8cf77aa99b17611c7199d56cee6d4ad Mon Sep 17 00:00:00 2001
From: Phil Sturgeon <67381+philsturgeon@users.noreply.github.com>
Date: Thu, 24 Sep 2026 12:06:05 +0100
Subject: [PATCH 1/3] framework: fast api
---
openapi/frameworks/fastapi.mdx | 422 ++++-----
openapi/frameworks/pydantic.mdx | 1579 +++++++++++++------------------
2 files changed, 849 insertions(+), 1152 deletions(-)
diff --git a/openapi/frameworks/fastapi.mdx b/openapi/frameworks/fastapi.mdx
index 67540385..c27be716 100644
--- a/openapi/frameworks/fastapi.mdx
+++ b/openapi/frameworks/fastapi.mdx
@@ -1,72 +1,58 @@
---
-title: How To Generate an OpenAPI Document With FastAPI
+title: How to generate an OpenAPI document with FastAPI
description: "Creating an OpenAPI document with FastAPI and using it to generate SDKs with Speakeasy."
---
import { Callout, YouTube } from "@/mdx/components";
-# How to generate an OpenAPI document with FastAPI
+FastAPI has rapidly gained traction in the Python community for its excellent performance, intuitive design, and flexibility. With OpenAPI support out of the box, FastAPI can build an APIs with matching SDKs and documentation providing convenient integration, all powered by the same source of truth.
+
+With the FastAPI generated OpenAPI document available out of the box, there is only minor customization and improvement needed to make the document usable with other tooling.
+
+To show this off check out our video guide on using FastAPI to produce top quality OpenAPI and generate SDKs with Speakeasy.
-Many developers start their API development with FastAPI, and with good reason. FastAPI has rapidly gained traction in the Python community for its excellent performance, intuitive design, and flexibility. It enables developers to craft API solutions that not only run fast but also meet their users' unique needs.
-
-FastAPI is great for building your core API, but you'll want to layer on SDKs and docs to provide your users with easy integration. For that, you'll want an OpenAPI document.
-
-The good news is that FastAPI provides you with an OpenAPI document out of the box. The less good news is that you'll need some tweaking to get the OpenAPI document to a level where it becomes usable with other tooling.
+For more in depth on the latest versions of the tools, follow along with this tutorial.
-This article will show you how to improve the default OpenAPI document generation to make the most of the generated schema.
+## Introduction to FastAPI and OpenAPI
-## Generating an OpenAPI document with FastAPI
+Understanding how FastAPI generates OpenAPI documents supports informed decisions when customizing a FastAPI setup.
-Understanding how FastAPI generates OpenAPI documents can help you make more informed decisions when you customize your FastAPI setup.
+The process is straightforward: FastAPI builds the OpenAPI document from application routes and models. Each route adds an operation to the OpenAPI document. Each model used by these routes adds a schema definition. Request and response bodies, parameters, and headers draw from these schema definitions.
-The process is fairly straightforward: FastAPI builds the OpenAPI document based on the routes and models you've defined in your application. For every route in your FastAPI application, FastAPI adds an operation to the OpenAPI document. For every model used in these routes, FastAPI adds a schema definition. The request and response bodies, parameters, and headers all draw from these schema definitions.
+While this process works well out of the box, FastAPI also offers several customization options that can change the generated OpenAPI document. The following sections cover several options.
-While this process works well out of the box, FastAPI also offers several customization options that can change the generated OpenAPI document. We'll cover some of these options in the following sections.
+## The FastAPI example app: Train Travel API
-## Our FastAPI example app: APItizing Burgers
+The example FastAPI application is following the common Train Travel API, which includes models for stations, trips, bookings, and payments, and provides operations for finding trips and managing bookings.
-Let's get this out of the way: The name came in a daydream shortly before lunchtime.
-
-To guide us through this journey, we'll use a simple example FastAPI application: the "APItizing Burgers" burger shop API. This API includes two models, `Burger` and `Order`, and provides basic CRUD operations for managing burgers and orders at our hypothetical burger shop. Additionally, we have a webhook defined for order status events.
-
-We'll look at how we optimized this FastAPI application and refined our models and routes so that the generated OpenAPI document is intuitive and easy to use. We will also explore how we can use this schema to generate SDKs using Speakeasy. The source code for our example API is available in the [framework-fastapi](https://github.com/speakeasy-api/examples/tree/main/framework-fastapi) folder of the Speakeasy Examples repository.
+The guide examines how this FastAPI application uses refined models and routes to produce an intuitive OpenAPI document. The schema also supports SDK generation with Speakeasy. Source code is available in the [framework-fastapi](https://github.com/speakeasy-api/examples/tree/main/framework-fastapi) folder of the Speakeasy Examples repository.
The `framework-fastapi` directory consists of two directories: `app` and `sdk`.
-The `app` directory contains the FastAPI server definition: `app/main.py`. This is where we'll look at what we customized.
+The `app` directory contains the FastAPI server definition: `app/main.py`, including the customizations described in this guide.
The `sdk` directory and the two OpenAPI documents, `openapi.yaml` and `openapi.json`, are generated by running `gen.sh` in the root of the project.
-Join us as we dive into FastAPI customization and discover how these tweaks can streamline your SDK generation process.
+The following sections explain how FastAPI customization can streamline SDK generation.
-
- When using Pydantic to define models, a known issue is that the serialization
- of `datetime` objects is not timezone-aware. This will cause a mismatch with
- the OpenAPI format `date-time`, which requires RFC 3339 date-time strings with
- timezones included. Consider using
- [`AwareDatetime`](https://docs.pydantic.dev/2.5/api/types/#pydantic.types.AwareDatetime)
- fields in Pydantic models to enable the appropriate
- [validation](https://docs.pydantic.dev/latest/errors/validation_errors/#timezone_aware)
- and ensure your SDK behavior matches the response definition from your server.
-
## Basic FastAPI setup
-Let's get started with the basics – some things you probably do already.
+The basics provide a foundation for the remaining examples.
-These straightforward examples are trivial but will help you better understand the three steps in the automation pipeline: How FastAPI setup influences OpenAPI documents, which, in turn, influences SDK code.
+These straightforward examples illustrate the three steps in the automation pipeline: FastAPI setup influences OpenAPI documents, which in turn influence SDK code.
### Scalar API documentation
-FastAPI automatically generates API documentation using Swagger UI. This example also has [Scalar](https://scalar.com/) API documentation. Scalar is an alternative to Swagger UI. Its standout feature, as explained in our blog post, [Choosing a docs vendor: Mintlify vs Scalar vs Bump vs ReadMe vs Redocly](https://www.speakeasy.com/blog/choosing-a-docs-vendor#mintlify-seriously-beautiful-docs), is that it can be used as a standalone API client. Scalar is also easy to use and has a modern UI that can be customized to create branded documentation. We use it for our [Speakeasy docs](https://www.speakeasy.com/blog/release-speakeasy-docs#why-we-partnered-with-scalar).
+FastAPI automatically generates API documentation using Swagger UI. This example also has [Scalar](https://scalar.com/) API documentation. Scalar is an alternative to Swagger UI. Its standout feature, as explained in the Speakeasy blog post, [Choosing a docs vendor: Mintlify vs Scalar vs Bump vs ReadMe vs Redocly](https://www.speakeasy.com/blog/choosing-a-docs-vendor#mintlify-seriously-beautiful-docs), is that it can be used as a standalone API client. Scalar is also easy to use and has a modern UI that can be customized to create branded documentation. Scalar also powers [Speakeasy docs](https://www.speakeasy.com/blog/release-speakeasy-docs#why-we-partnered-with-scalar).
-We added Scalar to the FastAPI app by installing the [Scalar FastAPI plugin](https://github.com/scalar/scalar/blob/main/integrations/fastapi/README.md).
+Scalar is added to the FastAPI app by installing the [Scalar FastAPI plugin](https://github.com/scalar/scalar/blob/main/integrations/fastapi/README.md).
-After installing the plugin, we added a "/scalar" route, in `app/main.py`, that returns the Scalar API Reference:
+After installing the plugin, add a `/scalar` route in `app/main.py` to return the Scalar API Reference:
```python
from scalar_fastapi import get_scalar_api_reference
@@ -88,18 +74,19 @@ async def scalar_html():
### Server configuration
-This may seem obvious, but while first working with FastAPI in development, the generated docs, development server, and API operations all work out of the box without the need to manually specify your server address.
+While working with FastAPI in development, generated docs, the development server, and API operations work out of the box without manually specifying a server address.
-However, when generating SDKs, your OpenAPI document needs to list servers.
+When generating SDKs, the OpenAPI document needs to list servers.
-In our `app/main.py`, we added our local server as shown:
+A common convention is to pop in the local and production servers (local can be stripped out with [overlays](https://www.speakeasy.com/openapi/overlays) later if they are not wanted showing up on live documentation) are configured in `app/main.py` as follows:
```python
from fastapi import FastAPI
app = FastAPI(
servers=[
- {"url": "http://127.0.0.1:8000", "description": "Local server"},
+ {"url": "http://localhost:8080", "description": "Local Server"},
+ {"url": "https://api.example.com", "description": "Production"},
],
)
```
@@ -109,49 +96,48 @@ This leads to the following generated output in `openapi.yaml`:
```yaml
# The basic server configuration in OpenAPI
servers:
- - description: Local server
- url: http://127.0.0.1:8000/
- # You can add additional servers if needed
- # - description: Production server
- # url: https://api.example.com/
+ - description: Local Server
+ url: http://localhost:8080
+ - description: Production
+ url: https://api.example.com
```
### Application information
-In our `app/main.py`, if we have the following:
+The following configuration belongs in `app/main.py`:
```python
from fastapi import FastAPI
app = FastAPI(
- summary="A simple API to manage burgers and orders",
- description="This API is used to manage burgers and orders in a restaurant",
- version="0.1.0",
- title="APItizing Burger API",
+ summary="Find and book train trips across Europe",
+ description="API for finding and booking train trips across Europe.",
+ version="1.2.1",
+ title="Train Travel API",
)
```
-FastAPI generates the following YAML in our `openapi.yaml` file:
+FastAPI generates the following YAML in `openapi.yaml`:
```yaml
info:
- description: This API is used to manage burgers and orders in a restaurant
- summary: A simple API to manage burgers and orders
- title: APItizing Burger API
- version: 0.1.0
+ description: API for finding and booking train trips across Europe.
+ summary: Find and book train trips across Europe
+ title: Train Travel API
+ version: 1.2.1
```
### Route customizations
-With the basics out of the way, let's look at a few more substantial recommendations.
+The following sections cover more substantial recommendations.
### Typed responses
-When developers use your generated SDK, they may wish to see what all the possible responses for an API call could be.
+SDK users may want to see all possible responses for an API call.
-With FastAPI, you can add additional responses to each route by specifying a response type.
+FastAPI supports additional responses on each route through response types.
-In our `app/main.py`, we added this abbreviated code:
+The following abbreviated code belongs in `app/main.py`:
```python
from fastapi import FastAPI
@@ -163,20 +149,20 @@ class ResponseMessage(BaseModel):
message: str = Field(description="The response message")
-OPENAPI_RESPONSE_BURGER_NOT_FOUND = {
+OPENAPI_RESPONSE_STATION_NOT_FOUND = {
"model": ResponseMessage,
- "description": "Burger not found",
+ "description": "Station not found",
}
-def response_burger_not_found(burger_id: int):
- """Response for burger not found"""
+def response_station_not_found(station_id: int):
+ """Response for station not found"""
return JSONResponse(
status_code=404,
- content=f"Burger with id {burger_id} does not exist",
+ content=f"Station with id {station_id} does not exist",
)
-class Burger(BaseModel):
+class Station(BaseModel):
id: int
name: str
description: str = None
@@ -184,21 +170,21 @@ class Burger(BaseModel):
app = FastAPI()
@app.get(
- "/burger/{burger_id}",
- response_model=BurgerOutput,
- responses={404: OPENAPI_RESPONSE_BURGER_NOT_FOUND},
- tags=["burger"],
+ "/stations/{station_id}",
+ response_model=Station,
+ responses={404: OPENAPI_RESPONSE_STATION_NOT_FOUND},
+ tags=["Stations"],
)
-def read_burger(burger_id: Annotated[int, Path(title="Burger ID")]):
- """Read a burger"""
+ def get_station(station_id: Annotated[int, Path(title="Station ID")]):
+ """Read a station"""
- for burger in burgers_db:
- if burger.id == burger_id:
- return burger
- return response_burger_not_found(burger_id)
+ for station in stations_db:
+ if station.id == station_id:
+ return station
+ return response_station_not_found(station_id)
```
-FastAPI adds a schema for our specific error message to `openapi.yaml`:
+FastAPI adds a schema for the specific error message to `openapi.yaml`:
```yaml
components:
@@ -218,17 +204,23 @@ components:
### Operation tags
-As your API develops and grows bigger, you're likely to split it into separate files. FastAPI [provides conveniences](https://fastapi.tiangolo.com/tutorial/bigger-applications/) to help reduce boilerplate and repetition when splitting an API into multiple modules.
+As an API develops and grows, routes are often split into separate files. FastAPI [provides conveniences](https://fastapi.tiangolo.com/tutorial/bigger-applications/) to reduce boilerplate and repetition when splitting an API into multiple modules.
-While this separation may reduce cognitive overhead while you're working in particular sections of the API code, it doesn't mean similar groups are automatically created in your documentation and SDK code.
+This separation may reduce cognitive overhead during work on particular sections of API code, but similar groups are not automatically created in documentation and SDK code.
-We recommend you add tags to all operations in FastAPI, whether you're building a big application or only have a handful of operations, so that operations can be grouped by tag in generated SDK code and documentation.
+Add tags to all operations in FastAPI, whether the application is large or contains only a handful of operations, so that operations can be grouped by tag in generated SDK code and documentation.
```yaml filename="operation-tags.yaml"
# Tags help organize operations into logical groups
tags:
- - name: burger
- - name: order
+ - name: Stations
+ description: Find and filter train stations across Europe.
+ - name: Trips
+ description: Timetables and routes for train trips between stations.
+ - name: Bookings
+ description: Create and manage bookings for train trips.
+ - name: Payments
+ description: Pay for bookings and view payment status.
```
The most straightforward way to add tags is to edit each operation and add a list of tags. This example highlights the tags list:
@@ -239,20 +231,20 @@ from fastapi import FastAPI
app = FastAPI()
@app.get(
- "/burger/{burger_id}",
- tags=["burger"],
+ "/stations",
+ tags=["Stations"],
)
-def read_burger(burger_id: int):
+ def get_stations():
return {
- "burger_id": burger_id,
+ "data": [],
}
```
### Tag metadata
-You can add metadata to your tags to further improve the developer experience.
+Tag metadata can further improve the developer experience.
-FastAPI accepts a parameter called `openapi_tags`, which we can use to add metadata, such as a description and a list of external documentation links.
+FastAPI accepts an `openapi_tags` parameter for metadata such as a description and a list of external documentation links.
Here's how to add metadata to tags:
@@ -261,64 +253,66 @@ from fastapi import FastAPI
tags_metadata = [
{
- "name": "burger",
- "description": "Operations related to burgers",
+ "name": "Stations",
+ "description": "Find and filter train stations across Europe.",
"externalDocs": {
- "description": "Burger external docs",
- "url": "https://en.wikipedia.org/wiki/Hamburger",
+ "description": "Train station external docs",
+ "url": "https://en.wikipedia.org/wiki/Train_station",
},
},
{
- "name": "order",
- "description": "Operations related to orders",
- },
+ "name": "Trips",
+ "description": "Timetables and routes for train trips between stations.",
+ )
]
app = FastAPI(
openapi_tags=tags_metadata,
)
+app = FastAPI(
+ openapi_tags=tags_metadata,
+)
+
@app.get(
- "/burger/{burger_id}",
- tags=["burger"],
+ "/trips",
+ tags=["Trips"],
)
-def read_burger(burger_id: int):
+ def get_trips():
return {
- "burger_id": burger_id,
+ "data": [],
}
```
-When we add metadata to tags, FastAPI adds a top-level `tags` section to our OpenAPI document:
+When metadata is added to tags, FastAPI adds a top-level `tags` section to the OpenAPI document:
```yaml
tags:
- - description: Operations related to burgers
+ - description: Find and filter train stations across Europe.
externalDocs:
- description: Burger external docs
- url: https://en.wikipedia.org/wiki/Hamburger
- name: burger
- - description: Operations related to orders
- name: order
+ description: Train station external docs
+ url: https://en.wikipedia.org/wiki/Train_station
+ name: Stations
+ - description: Timetables and routes for train trips between stations.
+ name: Trips
```
-Each tagged path in our OpenAPI document also gets a list of tags:
+Each tagged path in the OpenAPI document also gets a list of tags:
```yaml
paths:
- /burger/{burger_id}:
+ /trips:
get:
- description: Read a burger
- operationId: readBurger
- summary: Read Burger
+ description: Find available trips
+ operationId: get-trips
+ summary: Get Trips
tags:
- - burger
+ - Trips
# ...
```
### Operation ID customization
-When FastAPI outputs an OpenAPI document, it generates a unique OpenAPI `operationId` for each path. By default, this unique ID is generated by the FastAPI `generate_unique_id` function:
-
```python
def generate_unique_id(route: "APIRoute") -> str:
operation_id = route.name + route.path_format
@@ -328,14 +322,14 @@ def generate_unique_id(route: "APIRoute") -> str:
return operation_id
```
-This can often lead to cumbersome and unintuitive names. To improve usability, we have two methods of customizing these generated strings:
+This can often lead to cumbersome and unintuitive names. Two methods are available for customizing these generated strings:
1. Using a custom `generate_unique_id_function`
2. Specifying `operation_id` per operation
-The preferred method is to use a custom function when you generate unique IDs for paths.
+The preferred method is a custom function for generating unique IDs for paths.
-The example below is an illustrative function that doesn't generate guaranteed-unique IDs and doesn't handle method names without an underscore. However, it demonstrates how you can add a function that generates IDs based on an operation's method name:
+The following illustrative function does not generate guaranteed-unique IDs or handle method names without an underscore. It demonstrates how a function can generate IDs based on an operation's method name:
```python
from fastapi import FastAPI
@@ -358,7 +352,7 @@ app = FastAPI(
)
```
-With FastAPI, you can also specify the `operationId` per operation. For our example, we'll add a new parameter called `operation_id` to the operation decorator:
+FastAPI also supports specifying the `operationId` per operation. The following example adds an `operation_id` parameter to the operation decorator:
```python
from fastapi import FastAPI
@@ -366,16 +360,16 @@ from fastapi import FastAPI
app = FastAPI()
@app.get(
- "/burger/{burger_id}",
- operation_id="readBurger",
+ "/trips",
+ operation_id="get-trips",
)
-def read_burger(burger_id: int):
+ def get_trips():
pass
```
### Webhooks
-Starting with OpenAPI version 3.1.0, it is possible to specify webhooks for your application in OpenAPI.
+Starting with OpenAPI version 3.1.0, applications can specify webhooks in OpenAPI.
Here's how to add a webhook to FastAPI:
@@ -385,20 +379,20 @@ from fastapi import FastAPI
app = FastAPI()
-class Order(BaseModel):
+class Booking(BaseModel):
id: int
note: str
@app.webhooks.post(
- "order-status-changed",
- operation_id="webhookOrderStatusChanged",
+ "booking-status-changed",
+ operation_id="webhookBookingStatusChanged",
)
-def webhook_order_status_changed(body: Order):
+ def webhook_booking_status_changed(body: Booking):
"""
- When an order status is changed, this webhook will be triggered.
+ When a booking status is changed, this webhook will be triggered.
- The server will send a `POST` request with the order details to the webhook URL.
+ The server will send a `POST` request with the booking details to the webhook URL.
"""
pass
```
@@ -407,20 +401,20 @@ FastAPI generates the following top-level `webhooks` section in `openapi.yaml`:
```yaml
webhooks:
- order-status-changed:
+ booking-status-changed:
post:
description:
- "When an order status is changed, this webhook will be triggered.
+ "When a booking status is changed, this webhook will be triggered.
- The server will send a `POST` request with the order details to the webhook
+ The server will send a `POST` request with the booking details to the webhook
URL."
- operationId: webhookOrderStatusChanged
+ operationId: webhookBookingStatusChanged
requestBody:
content:
application/json:
schema:
- $ref: "#/components/schemas/Order"
+ $ref: "#/components/schemas/Booking"
required: true
responses:
"200":
@@ -434,22 +428,22 @@ webhooks:
schema:
$ref: "#/components/schemas/HTTPValidationError"
description: Validation Error
- summary: Webhook Order Status Changed
+ summary: Webhook Booking Status Changed
```
## Speakeasy integration
-Now that we have a customized OpenAPI document, we can use Speakeasy to generate SDKs based on it. You can generate an SDK by running the `gen.sh` bash script, which runs the `speakeasy generate` command. Alternatively, you can use the Speakeasy quick start command for a guided SDK setup:
+With a customized OpenAPI document, Speakeasy can generate SDKs from the schema. Run the `gen.sh` bash script, which runs the `speakeasy generate` command. Alternatively, use the Speakeasy quick start command for guided SDK setup:
```bash filename="Terminal"
speakeasy quickstart
```
-Following the prompts, provide the OpenAPI document location, name your SDK, and select the SDK language.
-In the terminal, you'll see the steps taken by Speakeasy to create the SDK:
+Following the prompts, provide the OpenAPI document location, SDK name, and SDK language.
+The terminal displays the steps Speakeasy takes to generate the SDK:
```
-│ └─Source: APItizing Burgers API - success
+│ └─Source: Train Travel API - success
│ └─Validating Document - success
│ └─Diagnosing OpenAPI - success
│ └─Tracking OpenAPI Changes - success
@@ -470,22 +464,22 @@ In the terminal, you'll see the steps taken by Speakeasy to create the SDK:
│ └─Uploading Code Samples - success
```
-Speakeasy [validates](/docs/concepts#validation) the OpenAPI document to check that it's ready for code generation. Validation issues will be printed in the terminal and the generated SDK will be saved as a folder in your project.
-Speakeasy also suggests improvements for your SDK using [Speakeasy Suggest](/docs/prep-openapi/maintenance), which is an AI-powered tool in Speakeasy Studio. You can see suggestions by opening the link to your Speakeasy Studio workspace in the terminal.
+Speakeasy [validates](/docs/concepts#validation) the OpenAPI document to check that it is ready for code generation. Validation issues are printed in the terminal, and the generated SDK is saved as a folder in the project.
+Speakeasy also suggests improvements for SDKs using [Speakeasy Suggest](/docs/prep-openapi/maintenance), an AI-powered tool in Speakeasy Studio. Open the Speakeasy Studio workspace link in the terminal to view suggestions.
-Let's take a look at how the information we detailed in the OpenAPI document affects how Speakeasy generates SDKs.
+The following sections show how information in the OpenAPI document affects SDK generation.
-Adding the local server information leads to the following generated output in the `openapi.yaml` file:
+Adding the server information leads to the following generated output in the `openapi.yaml` file:
```yaml
# This server configuration will be used by Speakeasy when generating SDKs
openapi: 3.1.0
info:
- title: APItizing Burgers API
- version: 0.1.0
+ title: Train Travel API
+ version: 1.2.1
servers:
- - description: Local server
- url: http://127.0.0.1:8000/
+ - description: Local Server
+ url: http://localhost:8080
```
After Speakeasy generates the SDK, this leads to the following abbreviated code in `sdk/src/openapi/sdkconfiguration.py`:
@@ -494,8 +488,8 @@ After Speakeasy generates the SDK, this leads to the following abbreviated code
from dataclasses import dataclass
SERVERS = [
- 'http://127.0.0.1:8000/',
- # Local server
+ 'http://localhost:8080',
+ # Local Server
]
"""Contains the list of servers available to the SDK"""
@@ -518,14 +512,14 @@ class SDKConfiguration:
return SERVERS[self.server_idx], {}
```
-You'll find calls to `SDKConfiguration.get_server_details()` when the SDK builds API URLs:
+Calls to `SDKConfiguration.get_server_details()` appear when the SDK builds API URLs:
```python
from dataclasses import dataclass
SERVERS = [
- 'http://127.0.0.1:8000/',
- # Local server
+ 'http://localhost:8080',
+ # Local Server
]
"""Contains the list of servers available to the SDK"""
@@ -548,13 +542,13 @@ class SDKConfiguration:
return SERVERS[self.server_idx], {}
```
-Speakeasy uses the title, summary, and descriptions we provided earlier to add helpful text to the generated SDK documentation, including comments in the SDK code. For example, in `sdk/src/openapi/sdk.py`:
+Speakeasy uses the title, summary, and descriptions from the document to add helpful text to generated SDK documentation, including comments in SDK code. For example, in `sdk/src/openapi/sdk.py`:
```python
class SDK(BaseSDK):
- r"""APItizing Burgers API: A simple API to manage burgers and orders
+ r"""Train Travel API: Find and book train trips across Europe
- This API is used to manage burgers and orders in a restaurant
+ API for finding and booking train trips across Europe.
"""
```
@@ -566,12 +560,12 @@ from dataclasses import dataclass
@dataclass
class SDKConfiguration:
...
- openapi_doc_version: str = '0.1.0'
- user_agent: str = "speakeasy-sdk/python 0.2.0 2.607.0 0.1.0 openapi"
+ openapi_doc_version: str = '1.2.1'
+ user_agent: str = "speakeasy-sdk/python 0.2.0 2.607.0 1.2.1 openapi"
...
```
-When users call your API using the generated SDK, the `user_agent` from `SDKConfiguration` is automatically added to the `user-agent` header. The `_build_request_with_client` method in `BaseSDK` constructs the HTTP request and sets the header using `headers[user_agent_header] = self.sdk_configuration.user_agent`:
+When an API is called using the generated SDK, the `user_agent` from `SDKConfiguration` is automatically added to the `user-agent` header. The `_build_request_with_client` method in `BaseSDK` constructs the HTTP request and sets the header using `headers[user_agent_header] = self.sdk_configuration.user_agent`:
```python
def _build_request_with_client(
@@ -588,9 +582,9 @@ def _build_request_with_client(
### Operation ID issues and solutions
-The unique `operation_id` generated by FastAPI does not translate well into an SDK. We need to customize the unique `operation_id` that FastAPI generates for better readability.
+The unique `operation_id` generated by FastAPI does not translate well into an SDK. Customize the generated `operation_id` for better readability.
-For instance, in the operation that returns a burger by `burger_id`, the default unique ID would be `read_burger_burger__burger_id__get`. This makes its way into SDK code, leading to class names such as `ReadBurgerBurgerBurgerIDGetRequest` or function names like `read_burger_burger_burger_id_get`.
+For instance, in the operation that returns a station by `station_id`, the default unique ID would be `read_station_stations__station_id__get`. This makes its way into SDK code, leading to class names such as `ReadStationStationsStationIDGetRequest` or function names like `read_station_stations_station_id_get`.
Here's a usage example after generating an SDK without customizing the `operationId`:
@@ -600,14 +594,14 @@ from sdk.models import operations
s = sdk.SDK()
-req = operations.ReadBurgerBurgerBurgerIDGetRequest(
- burger_id=847252,
+req = operations.ReadStationStationsStationIDGetRequest(
+ station_id=847252,
)
-res = s.burger.read_burger_burger_burger_id_get(req)
+res = s.stations.read_station_stations_station_id_get(req)
```
-However, after using the custom function `generate_unique_id` we defined previously, the `read_burger` operation gets a friendlier operation ID, `readBurger`, and the usage example becomes easier to read:
+After applying the previously defined `generate_unique_id` function, the `get_station` operation receives the friendlier `getStation` operation ID, making the usage example easier to read:
```python
import sdk
@@ -615,29 +609,29 @@ from sdk.models import operations
s = sdk.SDK()
-req = operations.ReadBurgerRequest(
- burger_id=847252,
+req = operations.GetStationRequest(
+ station_id=847252,
)
-res = s.burger.read_burger(req)
+res = s.stations.get_station(req)
```
-In addition to the two methods described earlier, there is a third way to customize the `operation_id`. We can add the top-level `x-speakeasy-name-override` [Speakeasy extension](https://www.speakeasy.com/docs/speakeasy-reference/extensions) to our OpenAPI document, allowing Speakeasy to override the generated names when it generates SDK code.
+In addition to the two methods described earlier, a third way to customize the `operation_id` is available. Add the top-level `x-speakeasy-name-override` [Speakeasy extension](https://www.speakeasy.com/docs/speakeasy-reference/extensions) to the OpenAPI document, allowing Speakeasy to override generated names during SDK generation.
To add this extension, follow the Speakeasy guide to [changing method names](/docs/customize-sdks/methods).
```yaml filename="name-override.yaml"
# Example of x-speakeasy-name-override extension
x-speakeasy-name-override:
operations:
- readBurger: getBurger
- createBurger: addBurger
+ getStation: getStationDetails
+ createBooking: addBooking
```
### Adding retry functionality
-Speakeasy can generate SDKs that follow custom rules for retrying failed requests. For instance, if your server fails to return a response within a specified time, you may want your users to retry their request without clobbering your server.
+Speakeasy can generate SDKs that follow custom rules for retrying failed requests. For instance, if a server fails to return a response within a specified time, retrying the request can avoid unnecessary load.
-To add retries to SDKs generated by Speakeasy, add a top-level `x-speakeasy-retries` schema to your OpenAPI document. You can also override the retry strategy per operation by adding `x-speakeasy-retries` to each operation:
+To add retries to SDKs generated by Speakeasy, add a top-level `x-speakeasy-retries` schema to the OpenAPI document. The retry strategy can also be overridden per operation by adding `x-speakeasy-retries` to each operation:
```yaml filename="speakeasy-retries.yaml"
# Speakeasy retries can be configured with a top-level extension
@@ -647,17 +641,17 @@ x-speakeasy-retries:
retryConnectionErrors: true
```
-To add global retries, we need to customize the schema generated by the FastAPI `get_openapi` function:
+To add global retries, customize the schema generated by the FastAPI `get_openapi` function:
```python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
app = FastAPI(
- summary="A simple API to manage burgers and orders",
- description="This API is used to manage burgers and orders in a restaurant",
- version="0.1.0",
- title="APItizing Burger API",
+ summary="Find and book train trips across Europe",
+ description="API for finding and booking train trips across Europe.",
+ version="1.2.1",
+ title="Train Travel API",
)
def custom_openapi():
@@ -694,7 +688,7 @@ def custom_openapi():
app.openapi = custom_openapi
```
-Keep in mind that you'll need to add this customization _after_ declaring your operation routes.
+Add this customization _after_ declaring the operation routes.
This change adds the following top-level section to `openapi.yaml`:
@@ -719,7 +713,7 @@ from fastapi import FastAPI
app = FastAPI()
@app.get(
- "/burger/",
+ "/bookings",
openapi_extra={
"x-speakeasy-retries": {
"strategy": "backoff",
@@ -736,7 +730,7 @@ app = FastAPI()
}
},
)
-def list_burgers():
+def list_bookings():
return []
```
@@ -744,46 +738,46 @@ def list_burgers():
FastAPI supports several authentication mechanisms that can easily be integrated into your API.
-The example below demonstrates adding an API key authentication scheme to the `/burger/` endpoint of our API. We use the `APIKeyHeader` dependency to validate the API key passed in the `Authorization` header:
+The following example adds an API key authentication scheme to the `/bookings` endpoint. The `APIKeyHeader` dependency validates the API key passed in the `Authorization` header:
```python
from fastapi.security import APIKeyHeader
-API_KEY = "your-apitizing-api-key"
+API_KEY = "your-train-travel-api-key"
header_scheme = APIKeyHeader(
name=API_KEY,
auto_error=True,
- description="API Key for the Burger listing API. API Key should be sent as a header, with the value 'your-apitizing-api-key'",
+ description="API Key for the booking API. API Key should be sent as a header, with the value 'your-train-travel-api-key'",
scheme_name="api_key",
)
```
-We can pass a `key` parameter to the `list_burgers` function, retrieve the API key from the header, and perform validation:
+Pass a `key` parameter to the `list_bookings` function to retrieve and validate the API key from the header:
```python
@app.get(
- "/burger/",
- response_model=List[BurgerOutput],
- tags=["burger"],
+ "/bookings",
+ response_model=List[Booking],
+ tags=["Bookings"],
...
)
-def list_burgers(key: str = Depends(header_scheme)):
- """List all burgers"""
+def list_bookings(key: str = Depends(header_scheme)):
+ """List all bookings"""
if key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid API Key")
- return [BurgerOutput(**burger_data.dict()) for burger_data in burgers_db]
+ return [Booking(**booking_data.dict()) for booking_data in bookings_db]
```
-Now when generating the OpenAPI document, the API key authentication scheme will be included and only required for the listing on the `/burger/` endpoint.
+Now when generating the OpenAPI document, the API key authentication scheme will be included and only required for the listing on the `/bookings` endpoint.
### Handling form data
Form data is a common way to receive information from clients, particularly in web applications. FastAPI provides robust support for form data through its `Form` class, and it correctly documents these form fields in the OpenAPI schema.
-When working with form data in FastAPI, you need to use the `Form` class from the `fastapi` module. This ensures that FastAPI correctly adds the appropriate schema information to your OpenAPI document.
+When working with form data in FastAPI, use the `Form` class from the `fastapi` module. This ensures that FastAPI adds the appropriate schema information to the OpenAPI document.
```python
from fastapi import FastAPI, Form
@@ -791,13 +785,13 @@ from typing import Annotated
app = FastAPI()
-@app.post("/burger/create/")
-async def create_burger_form(
+@app.post("/bookings/create/")
+async def create_booking_form(
name: Annotated[str, Form()],
description: Annotated[str, Form()],
price: Annotated[float, Form()]
):
- """Create a new burger using form data"""
+ """Create a new booking using form data"""
return {
"name": name,
"description": description,
@@ -809,10 +803,10 @@ In the OpenAPI document, FastAPI correctly identifies this endpoint as accepting
```yaml
paths:
- /burger/create/:
+ /bookings/create/:
post:
- summary: Create Burger Form
- operationId: createBurgerForm
+ summary: Create Booking Form
+ operationId: createBookingForm
requestBody:
content:
application/x-www-form-urlencoded:
@@ -836,7 +830,7 @@ paths:
application/json:
schema: {}
tags:
- - burger
+ - Bookings
```
When Speakeasy generates an SDK from this OpenAPI document, it will correctly handle form data submissions. The generated SDK will provide a clean interface for submitting form data:
@@ -847,13 +841,13 @@ from sdk.models import operations
s = sdk.SDK()
-req = operations.CreateBurgerFormRequest(
- name="Classic Burger",
- description="Our signature burger with special sauce",
+req = operations.CreateBookingFormRequest(
+ name="John Doe",
+ description="Booking for a train trip",
price=8.99
)
-res = s.burger.create_burger_form(req)
+res = s.bookings.create_booking_form(req)
```
#### File uploads
@@ -866,16 +860,16 @@ from typing import Annotated
app = FastAPI()
-@app.post("/burger/image/")
-async def upload_burger_image(
- burger_id: Annotated[int, Form()],
+@app.post("/bookings/document/")
+async def upload_booking_document(
+ booking_id: Annotated[int, Form()],
image: Annotated[UploadFile, File()]
):
- """Upload an image for a burger"""
+ """Upload a document for a booking"""
contents = await image.read()
# Process file contents...
return {
- "burger_id": burger_id,
+ "booking_id": booking_id,
"filename": image.filename,
"content_type": image.content_type,
"size": len(contents)
@@ -886,12 +880,12 @@ This endpoint will be documented in the OpenAPI schema with `multipart/form-data
#### Advanced form validation
-For form data that needs validation beyond simple type checking, you can combine Pydantic models with the `Form` class. First, define your model with the validation rules:
+For form data requiring validation beyond simple type checking, combine Pydantic models with the `Form` class. First, define the model with validation rules:
```python
from pydantic import BaseModel, Field
-class BurgerFormData(BaseModel):
+class BookingFormData(BaseModel):
name: str = Field(..., min_length=3, max_length=50)
description: str = Field(..., min_length=10, max_length=200)
price: float = Field(..., gt=0, le=100)
@@ -900,22 +894,26 @@ class BurgerFormData(BaseModel):
Then use the model fields with form data:
```python
-@app.post("/burger/create/validated/")
-async def create_burger_validated(
+@app.post("/bookings/create/validated/")
+async def create_booking_validated(
name: Annotated[str, Form()],
description: Annotated[str, Form()],
price: Annotated[float, Form()]
):
- burger_data = BurgerFormData(
+ booking_data = BookingFormData(
name=name,
description=description,
price=price
)
- return burger_data
+ return booking_data
```
FastAPI will generate an OpenAPI document that includes these validation constraints, allowing SDK users to understand the requirements before submitting the form.
## Summary
-In this post, we've explored how you can set up a FastAPI-based SDK generation pipeline without hand-editing or updating OpenAPI documents. By using existing FastAPI methods for extending and customizing OpenAPI documents, you can improve the usability of your generated client SDKs.
+This post explored how to set up a FastAPI-based SDK generation pipeline without hand-editing or updating OpenAPI documents. Existing FastAPI methods for extending and customizing OpenAPI documents improve the usability of generated SDKs.
+
+## Further reading
+
+FastAPI can work with multiple validation libraries. Learn more about [working with Pydantic](/docs/openapi/frameworks/pydantic).
diff --git a/openapi/frameworks/pydantic.mdx b/openapi/frameworks/pydantic.mdx
index 1d342e1d..3dbcc0ea 100644
--- a/openapi/frameworks/pydantic.mdx
+++ b/openapi/frameworks/pydantic.mdx
@@ -1,25 +1,60 @@
---
-title: How To Generate an OpenAPI Document With Pydantic V2
-description: "How to generate OpenAPI documents and great SDKs for your Pydantic V2 Models"
+title: How To Generate an OpenAPI Document With Pydantic
+description: "Generate OpenAPI from Pydantic models for SDK generation all from the same source of truth."
---
-# How to generate an OpenAPI document with Pydantic V2
+import { Callout } from "@/mdx/components";
-[Pydantic](https://docs.pydantic.dev/latest/) is considered by many API developers to be the best data validation library for Python, and with good reason. By defining an application's models in Pydantic, developers benefit from a vastly improved development experience, runtime data validation and serialization, and automatic OpenAPI document generation.
+# How to generate an OpenAPI document with Pydantic
-However, many developers don't realize they can generate OpenAPI documents from their Pydantic models, which they can then use to create SDKs, documentation, and server stubs.
+[Pydantic](https://docs.pydantic.dev/latest/) is considered by many API
+developers to be the best data validation library for Python, and with good
+reason. By defining an application's models in Pydantic, developers benefit from
+a vastly improved development experience, runtime data validation and
+serialization, and automatic OpenAPI document generation.
-In this guide, you'll learn how to create new Pydantic models, generate an OpenAPI document from them, and use the generated schema to create an SDK for your API. We'll start with the simplest possible Pydantic model and gradually add more features to show how Pydantic models translate to OpenAPI documents.
+However, many developers don't realize they can generate OpenAPI documents from
+their Pydantic models, which they can then use to create SDKs, documentation,
+and server stubs, all of which are powered by the same source of truth.
+
+This guide uses a simple train travel sample app to show how Pydantic models
+become OpenAPI schemas that can be used for SDK generation. The example project
+lives in
+[examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic),
+and it exposes endpoints for stations, trips, and bookings.
+
+## Pydantic, JSON Schema, and OpenAPI
+
+Pydantic is a Python library for validating and shaping data. It can generate a
+JSON Schema from Python models, which is useful for a lot more than just API
+descriptions: code generation, form validation, documentation, and data contract
+tooling all benefit from being able to describe a model in a standard, portable
+way.
+
+JSON Schema is the standard for describing the shape of structured data. JSON
+Schema can describe any sort of data, but in the context of HTTP APIs it's a
+powerful way to describe types, constraints, enums, nested objects, arrays,
+defaults, and examples.
+
+OpenAPI is an API description format which describes the entire surface of a
+HTTP API. Since OpenAPI 3.1, the "Schema Object" is explicitly a JSON Schema
+vocabulary, which means it inherits the JSON Schema keywords and semantics.
+
+Putting all of that together, it;s possible to turn Pydantic models into JSON
+Schema, inspect the JSON Schema they generate, and convert that schema
+information into an OpenAPI document suitable for SDK generation and API
+tooling.
## Prerequisites
-Before we get started, make sure you have [Python](https://www.python.org/downloads/) 3.10 or higher installed on your machine. Check your Python version by running the following command:
+Python 3.9 or higher is required. Run the following command to confirm the
+Python version:
```bash filename="Terminal"
python --version
```
-We use Python 3.13.3 in this guide, but any version of Python 3.10 or higher should work.
+This guide uses Python 3.14.7, though any version of Python 3.9 or higher works.
## Creating a new Python project
@@ -39,135 +74,233 @@ source venv/bin/activate
## Install the required libraries
-We'll install Pydantic and PyYAML to generate and pretty-print the OpenAPI document:
+Pydantic, FastAPI, and PyYAML support schema generation and OpenAPI document
+formatting:
```bash filename="Terminal"
# Install the Pydantic library
-pip install pydantic
+pip install "pydantic>=2.13.4,<3"
# Install the PyYAML library for pretty-printing the OpenAPI schema
-pip install pyyaml
+pip install "pyyaml>=6.0.3"
+
+# Install FastAPI for the API
+pip install "fastapi>=0.115.6"
```
## Pydantic to OpenAPI document walkthrough
-Let's follow a step-by-step process to generate an OpenAPI document from a Pydantic model without any additional libraries.
+The following steps generate an OpenAPI document from a Pydantic model without
+additional libraries and improve the result in stages.
-### Defining a simple Pydantic model
+## Generating the first OpenAPI document
-Create a new Python file called `models.py` and define a simple Pydantic model.
+The sample app in [examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic) exposes a minimal train travel API with stations, trips, and bookings.
-In this example, we define a Pydantic model called `Pet` with three fields: `id`, `name`, and `breed`. The `id` field is an integer, and the `name` and `breed` fields are strings.
+```bash filename="Terminal"
+cd examples/framework-pydantic
+python -m venv .venv
+source .venv/bin/activate
+pip install -e .
-```python
-from pydantic import BaseModel
+python generate_openapi.py
+```
+
+The generated document is intentionally basic at this stage: the endpoints
+exist, but the schema metadata is still minimal.
+
+## Previewing the OpenAPI document
+
+The team at [Scalar](https://scalar.com/) has built a CLI and documentation
+tool that can serve an OpenAPI document as a web app with a three-column API
+documentation layout.
+
+Generate and preview the latest OpenAPI document:
+
+```bash filename="Terminal"
+python generate_openapi.py
+npx @scalar/cli document serve openapi.yaml
+```
+
+
+
+The API routes are listed in the navigation pane on the left. Select
+**`/bookings` POST** to inspect one of the Train Travel API operations:
+
+
+
+As the OpenAPI is improved throughout this guide, the preview can be run again to see how it's improving.
+
+### Defining a simple Pydantic model
+
+Create a new Python file called `models.py` and define a simple model. This
+example starts with a `Station` model, a straightforward schema that becomes a
+useful OpenAPI object.
+```python
+from pydantic import BaseModel, Field
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.", examples=["efdbb9d1-02c2-4bc3-afb7-6788d8782b1e"])
+ name: str = Field(..., description="Station name.", examples=["Berlin Hauptbahnhof"])
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.", examples=["DE"])
+ timezone: str = Field(..., description="IANA timezone of the station.", examples=["Europe/Berlin"])
```
-### Generating a JSON schema for the Pydantic model
+### Generating JSON Schema for the Pydantic model
-Add a new function called `print_json_schema` to the `models.py` file that prints the JSON schema for the `Pet` model.
+Add a function called `print_json_schema` to inspect the generated schema before
+expanding the sample app further.
-This function uses the `model_json_schema` method provided by Pydantic to generate the JSON schema, which Python then prints to the console as YAML. We use YAML for readability, but the output is still a valid JSON schema.
+This function uses the `model_json_schema` method provided by Pydantic to
+generate the schema and print it as YAML for readability.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import AwareDatetime, BaseModel, Field
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.", examples=["efdbb9d1-02c2-4bc3-afb7-6788d8782b1e"])
+ name: str = Field(..., description="Station name.", examples=["Berlin Hauptbahnhof"])
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.", examples=["DE"])
+ timezone: str = Field(..., description="IANA timezone of the station.", examples=["Europe/Berlin"])
def print_json_schema():
- print(yaml.dump(Pet.model_json_schema()))
+ print(yaml.dump(Station.model_json_schema()))
if __name__ == "__main__":
print_json_schema()
```
-Run `python models.py` to generate the JSON schema for the `Pet` model and print it as YAML:
+Running `python models.py` generates the JSON schema for the train station model:
```yaml
properties:
- breed:
- title: Breed
+ country_code:
+ description: ISO 3166-1 alpha-2 country code.
+ examples:
+ - DE
+ title: Country Code
type: string
id:
+ description: Unique station ID.
+ examples:
+ - efdbb9d1-02c2-4bc3-afb7-6788d8782b1e
title: Id
- type: integer
+ type: string
name:
+ description: Station name.
+ examples:
+ - Berlin Hauptbahnhof
title: Name
type: string
+ timezone:
+ description: IANA timezone of the station.
+ examples:
+ - Europe/Berlin
+ title: Timezone
+ type: string
required:
- id
- name
- - breed
-title: Pet
+ - country_code
+ - timezone
+title: Station
type: object
```
-### Multiple Pydantic models
+This is the core workflow for the rest of the article: define Pydantic models,
+inspect the JSON Schema, and convert that schema into an OpenAPI document for a
+train travel API.
-Let's add another Pydantic model called `Owner` to the `models.py` file.
+### Multiple Pydantic models
-The `Owner` model has two fields: `id` and `name`. Both fields are integers. Additionally, the `Owner` model has a list of `Pet` objects.
+Let's add a second model called `Trip` to the `models.py` file. A trip
+references one station as the origin and another as the destination, which is a
+useful pattern for real-world rail data.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
- id: int
- name: str
- pets: list[Pet]
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: AwareDatetime = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: AwareDatetime = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema():
- print(yaml.dump(Pet.model_json_schema()))
+ print(yaml.dump(Station.model_json_schema()))
if __name__ == "__main__":
print_json_schema()
```
+
+ When using Pydantic to define models, a known issue is that the serialization
+ of `datetime` objects is not timezone-aware. This will cause a mismatch with
+ the OpenAPI format `date-time`, which requires RFC 3339 date-time strings with
+ timezones included. Consider using
+ [`AwareDatetime`](https://docs.pydantic.dev/2.12/api/types/#pydantic.types.AwareDatetime)
+ fields in Pydantic models to enable the appropriate
+ [validation](https://docs.pydantic.dev/latest/errors/validation_errors/#timezone_aware)
+ and ensure SDK behavior matches the response definition from the server.
+
+
+The `AwareDatetime` fields generate date-time schemas with an explicit `date-time`
+format:
+
+```yaml
+departure_time:
+ type: string
+ format: date-time
+ description: Departure time in ISO 8601 format.
+arrival_time:
+ type: string
+ format: date-time
+ description: Arrival time in ISO 8601 format.
+```
+
### Generating a JSON schema for multiple Pydantic models
-Update the `print_json_schema` function to print the JSON schema for both the `Pet` and `Owner` models.
+Update the `print_json_schema` function to print the JSON schema for both the `Station` and `Trip` models.
-Note that we're now calling the [`models_json_schema`](https://docs.pydantic.dev/2.7/api/json_schema/#pydantic.json_schema.models_json_schema) function from `pydantic.json_schema` instead of the `model_json_schema` method.
+The [`models_json_schema`](https://docs.pydantic.dev/latest/api/json_schema/#pydantic.json_schema.models_json_schema) function from `pydantic.json_schema` replaces the `model_json_schema` method for multi-model output.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
- id: int
- name: str
- pets: list[Pet]
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema(models):
@@ -178,77 +311,98 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-Run `python models.py` to generate the JSON schema for both the `Pet` and `Owner` models and print it as YAML:
+Run `python models.py` to generate the JSON schema for both the `Station` and
+`Trip` models and print it as YAML:
```yaml
$defs:
- Owner:
+ Station:
properties:
+ country_code:
+ title: Country Code
+ type: string
id:
title: Id
- type: integer
+ type: string
name:
title: Name
type: string
- pets:
- items:
- $ref: "#/$defs/Pet"
- title: Pets
- type: array
+ timezone:
+ title: Timezone
+ type: string
required:
- id
- name
- - pets
- title: Owner
+ - country_code
+ - timezone
+ title: Station
type: object
- Pet:
+ Trip:
properties:
- breed:
- title: Breed
+ arrival_time:
+ title: Arrival Time
+ type: string
+ departure_time:
+ title: Departure Time
+ type: string
+ destination:
+ title: Destination
type: string
id:
title: Id
- type: integer
- name:
- title: Name
type: string
+ origin:
+ title: Origin
+ type: string
+ price:
+ title: Price
+ type: number
required:
- id
- - name
- - breed
- title: Pet
+ - origin
+ - destination
+ - departure_time
+ - arrival_time
+ - price
+ title: Trip
type: object
```
-The generated schema includes definitions for both the `Pet` and `Owner` models. The `Owner` model has a reference to the `Pet` model, indicating that the `Owner` model contains a list of `Pet` objects.
-
-Note that the root of the schema includes a `$defs` key that contains the definitions for both models, and the `Owner` model references the `Pet` model using the `$ref` keyword.
+The generated schema includes definitions for both the `Station` and `Trip`
+models. The `Trip` model captures the route information that a train travel API needs
+for timetables and pricing.
### Customizing Pydantic JSON schema generation
-Let's customize the generated JSON schema to reference the `Pet` model using the `#/components/schemas` path instead of `$defs`.
+Let's customize the generated JSON schema to reference the `Station` model using
+the `#/components/schemas` path instead of `$defs`.
-We'll use the `ref_template` parameter of the `models_json_schema` function to specify the reference template.
+The `ref_template` parameter of the `models_json_schema` function specifies the
+reference template.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
- id: int
- name: str
- pets: list[Pet]
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema(models):
@@ -260,27 +414,32 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-Next, we'll update the `print_json_schema` function to print a JSON schema that resembles an OpenAPI document's `components` section.
+The next step updates the `print_json_schema` function to print a JSON schema
+that resembles an OpenAPI document's `components` section.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
- id: int
- name: str
- pets: list[Pet]
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema(models):
@@ -290,81 +449,102 @@ def print_json_schema(models):
)
openapi_schema = {
"components": {
- "schemas": schemas.get('$defs'),
+ "schemas": schemas.get("$defs"),
}
}
print(yaml.dump(openapi_schema))
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-Run `python models.py` to generate the OpenAPI document for both the `Pet` and `Owner` models.
+Run `python models.py` to generate the OpenAPI document for both the `Station` and `Trip` models.
-The generated OpenAPI document includes the `components` section, with definitions for both the `Pet` and `Owner` models.
+The generated OpenAPI document includes the `components` section, with
+definitions for both the `Station` and `Trip` models.
```yaml
components:
schemas:
- Owner:
+ Station:
properties:
+ country_code:
+ title: Country Code
+ type: string
id:
title: Id
- type: integer
+ type: string
name:
title: Name
type: string
- pets:
- items:
- $ref: "#/components/schemas/Pet"
- title: Pets
- type: array
+ timezone:
+ title: Timezone
+ type: string
required:
- id
- name
- - pets
- title: Owner
+ - country_code
+ - timezone
+ title: Station
type: object
- Pet:
+ Trip:
properties:
- breed:
- title: Breed
+ arrival_time:
+ title: Arrival Time
+ type: string
+ departure_time:
+ title: Departure Time
+ type: string
+ destination:
+ title: Destination
type: string
id:
title: Id
- type: integer
- name:
- title: Name
type: string
+ origin:
+ title: Origin
+ type: string
+ price:
+ title: Price
+ type: number
required:
- id
- - name
- - breed
- title: Pet
+ - origin
+ - destination
+ - departure_time
+ - arrival_time
+ - price
+ title: Trip
type: object
```
-The JSON schema we generated resembles an OpenAPI document's `components` section, but to generate a valid OpenAPI document, we need to add the `openapi` and `info` sections.
+The generated JSON schema resembles an OpenAPI document's `components` section,
+but a valid OpenAPI document also needs the `openapi` and `info` sections.
-Edit the `print_json_schema` function in `models.py` to include the `openapi` and `info` sections in the generated OpenAPI document.
+Edit the `print_json_schema` function in `models.py` to include the `openapi`
+and `info` sections in the generated OpenAPI document.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- id: int
- name: str
- breed: str
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
- id: int
- name: str
- pets: list[Pet]
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema(models):
@@ -375,105 +555,68 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
- "schemas": schemas.get('$defs'),
- }
+ "schemas": schemas.get("$defs"),
+ },
}
- print(yaml.dump(openapi_schema))
+ print(yaml.dump(openapi_schema, sort_keys=False))
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-Run `python models.py` to generate the complete OpenAPI document for both the `Pet` and `Owner` models.
+Run `python models.py` to generate the complete OpenAPI document for both the
+`Station` and `Trip` models.
-The generated OpenAPI document includes the `openapi`, `info`, and `components` sections with definitions for both the `Pet` and `Owner` models.
+The generated OpenAPI document includes the `openapi`, `info`, and `components`
+sections with definitions for both the `Station` and `Trip` models.
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- properties:
- id:
- title: Id
- type: integer
- name:
- title: Name
- type: string
- pets:
- items:
- $ref: "#/components/schemas/Pet"
- title: Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- properties:
- id:
- title: Id
- type: integer
- name:
- title: Name
- type: string
- breed:
- title: Breed
- type: string
- required:
- - id
- - name
- - breed
- title: Pet
- type: object
-```
-
-Now we have a complete OpenAPI document that we can use to generate SDK clients for our API. However, the generated OpenAPI document does not contain descriptions or example values for the models. We can add these details to the Pydantic models to improve the generated OpenAPI document.
+A complete OpenAPI document now exists for SDK generation. The generated
+document does not yet include descriptions or example values for the models,
+though those details can be added directly to the Pydantic models to improve the
+resulting OpenAPI output.
### Adding descriptions to Pydantic models
-Let's add docstrings to the `Pet` and `Owner` models to include additional information in the generated OpenAPI document.
+Let's add docstrings to the `Station` and `Trip` models to include additional
+information in the generated OpenAPI document.
```python
import yaml
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
+class Station(BaseModel):
"""
- A Pet in the system.
+ A train station in the network.
- ID is unique.
- Can have multiple owners.
+ Every station is uniquely identified and belongs to a country.
"""
- id: int
- name: str
- breed: str
+ id: str = Field(..., description="Unique station ID.")
+ name: str = Field(..., description="Station name.")
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., description="IANA timezone of the station.")
-class Owner(BaseModel):
+class Trip(BaseModel):
"""
- An Owner of Pets in the system.
+ A scheduled train trip between two stations.
- ID is unique.
- Can have multiple pets.
+ Includes departure and arrival times, and the trip fare.
"""
- id: int
- name: str
- pets: list[Pet]
+ id: str = Field(..., description="Unique trip ID.")
+ origin: str = Field(..., description="Origin station ID.")
+ destination: str = Field(..., description="Destination station ID.")
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., description="Trip price in EUR.")
def print_json_schema(models):
@@ -484,7 +627,7 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
@@ -495,75 +638,18 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-If we run `python models.py`, we see that our `Owner` schema now includes a description field, derived from the docstring we added to the `Owner` Pydantic model.
-
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- description: "An Owner of Pets in the system.
-
-
- ID is unique.
-
- Can have multiple pets."
- properties:
- id:
- title: Id
- type: integer
- name:
- title: Name
- type: string
- pets:
- items:
- $ref: "#/components/schemas/Pet"
- title: Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- description: "A Pet in the system.
-
-
- ID is unique.
-
- Can have multiple owners."
- properties:
- id:
- title: Id
- type: integer
- name:
- title: Name
- type: string
- breed:
- title: Breed
- type: string
- required:
- - id
- - name
- - breed
- title: Pet
- type: object
-```
-
-The `Pet` schema now also includes a description field, derived from the docstring we added to the `Pet` Pydantic model.
+Running `python models.py` shows a `Trip` schema description derived from the
+docstring added to the `Trip` model.
### Adding OpenAPI titles and descriptions to Pydantic fields
-Let's add titles and descriptions to the fields of the `Pet` and `Owner` models to include additional information in the generated OpenAPI document.
+Let's add titles and descriptions to the fields of the `Station` and `Trip`
+models to provide richer schema metadata.
-We'll use the `Field` class from Pydantic to add descriptions to the fields.
+The `Field` class from Pydantic adds descriptions to the fields.
```python
import yaml
@@ -571,32 +657,20 @@ from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- """
- A Pet in the system.
+class Station(BaseModel):
+ id: str = Field(..., title="Station ID", description="Unique station ID.")
+ name: str = Field(..., title="Station Name", description="Station name.")
+ country_code: str = Field(..., title="Country Code", description="ISO 3166-1 alpha-2 country code.")
+ timezone: str = Field(..., title="Timezone", description="IANA timezone of the station.")
- ID is unique.
- Can have multiple owners.
- """
- id: int = Field(..., title="Pet ID", description="The pet's unique identifier")
- name: str = Field(..., title="Pet Name", description="Name of the pet")
- breed: str = Field(..., title="Pet Breed", description="Breed of the pet")
-
-
-class Owner(BaseModel):
- """
- An Owner of Pets in the system.
-
- ID is unique.
- Can have multiple pets.
- """
-
- id: int = Field(..., title="Owner ID", description="Owner's unique identifier")
- name: str = Field(..., title="Owner Name", description="The owner's full name")
- pets: list[Pet] = Field(
- ..., title="Owner's Pets", description="The pets that belong to this owner"
- )
+class Trip(BaseModel):
+ id: str = Field(..., title="Trip ID", description="Unique trip ID.")
+ origin: str = Field(..., title="Origin", description="Origin station ID.")
+ destination: str = Field(..., title="Destination", description="Destination station ID.")
+ departure_time: str = Field(..., title="Departure Time", description="Departure time in ISO 8601 format.")
+ arrival_time: str = Field(..., title="Arrival Time", description="Arrival time in ISO 8601 format.")
+ price: float = Field(..., title="Price", description="Trip price in EUR.")
def print_json_schema(models):
@@ -607,7 +681,7 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
@@ -618,81 +692,18 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip])
```
-If we run `python models.py`, we see that our `Pet` schema now includes descriptions for each field.
-
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- description: "An Owner of Pets in the system.
-
-
- ID is unique.
-
- Can have multiple pets."
- properties:
- id:
- description: Owner's unique identifier
- title: Owner ID
- type: integer
- name:
- description: The owner's full name
- title: Owner Name
- type: string
- pets:
- description: The pets that belong to this owner
- items:
- $ref: "#/components/schemas/Pet"
- title: Owner's Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- description: "A Pet in the system.
-
-
- ID is unique.
-
- Can have multiple owners."
- properties:
- id:
- description: The pet's unique identifier
- title: Pet ID
- type: integer
- name:
- description: Name of the pet
- title: Pet Name
- type: string
- breed:
- description: Breed of the pet
- title: Pet Breed
- type: string
- required:
- - id
- - name
- - breed
- title: Pet
- type: object
-```
+Running `python models.py` shows a `Trip` schema with descriptions for each field.
### Adding OpenAPI example values to Pydantic models
-Examples help API users understand your API's data structures, and some SDK and documentation generators use OpenAPI example values to generate useful code snippets and documentation.
-
-Let's add example values to the `Pet` and `Owner` Pydantic models. Once again, we'll use the `Field` class from Pydantic to add example values to the fields.
+Examples help API users understand data structures. For a train API, example
+values make station and trip records much easier to interpret.
-Note that the examples are added as a list per field, using the `examples` parameter.
+The following example adds example values to the `Station` and `Trip` Pydantic
+models by using the `Field` class from Pydantic.
```python
import yaml
@@ -700,60 +711,20 @@ from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- """
- A Pet in the system.
-
- ID is unique.
- Can have multiple owners.
- """
-
- id: int = Field(
- ...,
- title="Pet ID",
- description="The pet's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Pet Name",
- description="Name of the pet",
- examples=["Fido"],
- )
- breed: str = Field(
- ...,
- title="Pet Breed",
- description="Breed of the pet",
- examples=["Golden Retriever", "Siamese", "Parakeet"],
- )
-
-
-class Owner(BaseModel):
- """
- An Owner of Pets in the system.
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.", examples=["ber-001"])
+ name: str = Field(..., description="Station name.", examples=["Berlin Hauptbahnhof"])
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.", examples=["DE"])
+ timezone: str = Field(..., description="IANA timezone of the station.", examples=["Europe/Berlin"])
- ID is unique.
- Can have multiple pets.
- """
- id: int = Field(
- ...,
- title="Owner ID",
- description="Owner's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Owner Name",
- description="The owner's full name",
- examples=["John Doe"],
- )
- pets: list[Pet] = Field(
- ...,
- title="Owner's Pets",
- description="The pets that belong to this owner",
- examples=[{"id": 1}],
- )
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.", examples=["trip_001"])
+ origin: str = Field(..., description="Origin station ID.", examples=["ber-001"])
+ destination: str = Field(..., description="Destination station ID.", examples=["muc-017"])
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.", examples=["2026-08-24T08:15:00Z"])
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.", examples=["2026-08-24T10:05:00Z"])
+ price: float = Field(..., description="Trip price in EUR.", examples=[89.0])
def print_json_schema(models):
@@ -764,7 +735,7 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
@@ -775,93 +746,16 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
-```
-
-If we run `python models.py`, we see that our `Pet` schema now includes example values for each field.
-
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- description: "An Owner of Pets in the system.
-
-
- ID is unique.
-
- Can have multiple pets."
- properties:
- id:
- description: Owner's unique identifier
- examples:
- - 1
- title: Owner ID
- type: integer
- name:
- description: The owner's full name
- examples:
- - John Doe
- title: Owner Name
- type: string
- pets:
- description: The pets that belong to this owner
- examples:
- - id: 1
- items:
- $ref: "#/components/schemas/Pet"
- title: Owner's Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- description: "A Pet in the system.
-
-
- ID is unique.
-
- Can have multiple owners."
- properties:
- id:
- description: The pet's unique identifier
- examples:
- - 1
- title: Pet ID
- type: integer
- name:
- description: Name of the pet
- examples:
- - Fido
- title: Pet Name
- type: string
- breed:
- description: Breed of the pet
- examples:
- - Golden Retriever
- - Siamese
- - Parakeet
- title: Pet Breed
- type: string
- required:
- - id
- - name
- - breed
- title: Pet
- type: object
+ print_json_schema([Station, Trip])
```
### Marking fields as optional in Pydantic models
-By default, Pydantic marks all fields as required. You can mark a field as optional by setting the `default` parameter to `None`.
+Pydantic marks all fields as required by default. A field becomes optional when
+the `default` parameter is set to `None`.
-Let's mark the `breed` field in the `Pet` model as optional by setting the `default` parameter to `None`.
+The `timezone` field in the `Station` model becomes optional in the schema with
+a default value of `None`.
```python
import yaml
@@ -869,60 +763,20 @@ from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class Pet(BaseModel):
- """
- A Pet in the system.
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.", examples=["ber-001"])
+ name: str = Field(..., description="Station name.", examples=["Berlin Hauptbahnhof"])
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.", examples=["DE"])
+ timezone: str | None = Field(None, description="IANA timezone of the station.", examples=["Europe/Berlin"])
- ID is unique.
- Can have multiple owners.
- """
-
- id: int = Field(
- ...,
- title="Pet ID",
- description="The pet's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Pet Name",
- description="Name of the pet",
- examples=["Fido"],
- )
- breed: str | None = Field(
- None,
- title="Pet Breed",
- description="Breed of the pet",
- examples=["Golden Retriever", "Siamese", "Parakeet"],
- )
-
-class Owner(BaseModel):
- """
- An Owner of Pets in the system.
-
- ID is unique.
- Can have multiple pets.
- """
-
- id: int = Field(
- ...,
- title="Owner ID",
- description="Owner's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Owner Name",
- description="The owner's full name",
- examples=["John Doe"],
- )
- pets: list[Pet] = Field(
- ...,
- title="Owner's Pets",
- description="The pets that belong to this owner",
- examples=[{"id": 1}],
- )
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.", examples=["trip_001"])
+ origin: str = Field(..., description="Origin station ID.", examples=["ber-001"])
+ destination: str = Field(..., description="Destination station ID.", examples=["muc-017"])
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.", examples=["2026-08-24T08:15:00Z"])
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.", examples=["2026-08-24T10:05:00Z"])
+ price: float = Field(..., description="Trip price in EUR.", examples=[89.0])
def print_json_schema(models):
@@ -933,7 +787,7 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
@@ -944,95 +798,13 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
-```
-
-If we run `python models.py`, we see that the `breed` field in the `Pet` schema now has two types: `string` and `null`, and it has been removed from the `required` list. Only `id` and `name` are required fields after marking `breed` as optional.
-
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- description: "An Owner of Pets in the system.
-
-
- ID is unique.
-
- Can have multiple pets."
- properties:
- id:
- description: Owner's unique identifier
- examples:
- - 1
- title: Owner ID
- type: integer
- name:
- description: The owner's full name
- examples:
- - John Doe
- title: Owner Name
- type: string
- pets:
- description: The pets that belong to this owner
- examples:
- - id: 1
- items:
- $ref: "#/components/schemas/Pet"
- title: Owner's Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- description: "A Pet in the system.
-
-
- ID is unique.
-
- Can have multiple owners."
- properties:
- id:
- description: The pet's unique identifier
- examples:
- - 1
- title: Pet ID
- type: integer
- name:
- description: Name of the pet
- examples:
- - Fido
- title: Pet Name
- type: string
- breed:
- anyOf:
- - type: string
- - type: "null"
- default: null
- description: Breed of the pet
- examples:
- - Golden Retriever
- - Siamese
- - Parakeet
- title: Pet Breed
- required:
- - id
- - name
- title: Pet
- type: object
+ print_json_schema([Station, Trip])
```
### Adding enums to OpenAPI using Pydantic models
Enums in OpenAPI are useful for defining a set of possible values for a field.
-
-Let's add an enum called `PetType` to the `Pet` model to represent different types of pets.
+For a train travel API, a `BookingStatus` enum is a natural fit.
```python
from enum import StrEnum
@@ -1041,76 +813,33 @@ from pydantic import BaseModel, Field
from pydantic.json_schema import models_json_schema
-class PetType(StrEnum):
- """
- An enumeration of pet types.
- """
-
- DOG = "dog"
- CAT = "cat"
- BIRD = "bird"
-
-
-class Pet(BaseModel):
- """
- A Pet in the system.
+class BookingStatus(StrEnum):
+ CONFIRMED = "confirmed"
+ PENDING = "pending"
+ CANCELLED = "cancelled"
- ID is unique.
- Can have multiple owners.
- """
- pet_type: PetType = Field(
- ...,
- title="Pet Type",
- description="Type of pet",
- examples=["dog", "cat", "bird"],
- )
- id: int = Field(
- ...,
- title="Pet ID",
- description="The pet's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Pet Name",
- description="Name of the pet",
- examples=["Fido"],
- )
- breed: str | None = Field(
- None,
- title="Pet Breed",
- description="Breed of the pet",
- examples=["Golden Retriever", "Siamese", "Parakeet"],
- )
+class Station(BaseModel):
+ id: str = Field(..., description="Unique station ID.", examples=["ber-001"])
+ name: str = Field(..., description="Station name.", examples=["Berlin Hauptbahnhof"])
+ country_code: str = Field(..., description="ISO 3166-1 alpha-2 country code.", examples=["DE"])
+ timezone: str | None = Field(None, description="IANA timezone of the station.", examples=["Europe/Berlin"])
-class Owner(BaseModel):
- """
- An Owner of Pets in the system.
+class Trip(BaseModel):
+ id: str = Field(..., description="Unique trip ID.", examples=["trip_001"])
+ origin: str = Field(..., description="Origin station ID.", examples=["ber-001"])
+ destination: str = Field(..., description="Destination station ID.", examples=["muc-017"])
+ departure_time: str = Field(..., description="Departure time in ISO 8601 format.", examples=["2026-08-24T08:15:00Z"])
+ arrival_time: str = Field(..., description="Arrival time in ISO 8601 format.", examples=["2026-08-24T10:05:00Z"])
+ price: float = Field(..., description="Trip price in EUR.", examples=[89.0])
- ID is unique.
- Can have multiple pets.
- """
- id: int = Field(
- ...,
- title="Owner ID",
- description="Owner's unique identifier",
- examples=[1],
- )
- name: str = Field(
- ...,
- title="Owner Name",
- description="The owner's full name",
- examples=["John Doe"],
- )
- pets: list[Pet] = Field(
- ...,
- title="Owner's Pets",
- description="The pets that belong to this owner",
- examples=[{"id": 1}],
- )
+class Booking(BaseModel):
+ id: str = Field(..., description="Unique booking ID.", examples=["booking_123"])
+ trip_id: str = Field(..., description="Trip ID for the selected route.", examples=["trip_001"])
+ passenger_name: str = Field(..., description="Passenger name on the booking.", examples=["Ada Lovelace"])
+ status: BookingStatus = Field(..., description="Current booking status.", examples=["confirmed"])
def print_json_schema(models):
@@ -1121,7 +850,7 @@ def print_json_schema(models):
openapi_schema = {
"openapi": "3.1.0",
"info": {
- "title": "Pet Sitter API",
+ "title": "Train Travel API",
"version": "0.0.1",
},
"components": {
@@ -1132,127 +861,37 @@ def print_json_schema(models):
if __name__ == "__main__":
- print_json_schema([Pet, Owner])
+ print_json_schema([Station, Trip, Booking, BookingStatus])
```
-In our generated OpenAPI document, we have a new `pet_type` field in the `Pet` schema.
-
-```yaml
-openapi: 3.1.0
-info:
- title: Pet Sitter API
- version: 0.0.1
-components:
- schemas:
- Owner:
- description: "An Owner of Pets in the system.
-
-
- ID is unique.
-
- Can have multiple pets."
- properties:
- id:
- description: Owner's unique identifier
- examples:
- - 1
- title: Owner ID
- type: integer
- name:
- description: The owner's full name
- examples:
- - John Doe
- title: Owner Name
- type: string
- pets:
- description: The pets that belong to this owner
- examples:
- - id: 1
- items:
- $ref: "#/components/schemas/Pet"
- title: Owner's Pets
- type: array
- required:
- - id
- - name
- - pets
- title: Owner
- type: object
- Pet:
- description: "A Pet in the system.
-
-
- ID is unique.
-
- Can have multiple owners."
- properties:
- pet_type:
- allOf:
- - $ref: "#/components/schemas/PetType"
- description: Type of pet
- examples:
- - dog
- - cat
- - bird
- title: Pet Type
- id:
- description: The pet's unique identifier
- examples:
- - 1
- title: Pet ID
- type: integer
- name:
- description: Name of the pet
- examples:
- - Fido
- title: Pet Name
- type: string
- breed:
- anyOf:
- - type: string
- - type: "null"
- default: null
- description: Breed of the pet
- examples:
- - Golden Retriever
- - Siamese
- - Parakeet
- title: Pet Breed
- required:
- - pet_type
- - id
- - name
- title: Pet
- type: object
- PetType:
- description: An enumeration of pet types.
- enum:
- - dog
- - cat
- - bird
- title: PetType
- type: string
-```
-
-This enum is represented as a separate schema in the OpenAPI document.
+This enum is represented as a separate schema in the OpenAPI document and makes
+the booking state explicit to both SDK generators and API consumers.
## Adding paths and operations to the OpenAPI document
-Now that we have generated an OpenAPI document from our Pydantic models, we can use the schema to generate SDK clients for our API.
+A generated OpenAPI document from the Pydantic models is ready for SDK usage,
+but it does not yet include the `paths` section that defines the API endpoints
+and operations.
-However, the OpenAPI document we generated, while valid, does not include the `paths` section, which defines the API endpoints and operations.
+Pydantic with FastAPI supports direct endpoint and operation definition in a
+FastAPI application. [FastAPI automatically generates the OpenAPI document for
+the API](/openapi/frameworks/fastapi#speakeasy-integration), including the
+`paths` section.
-When using Pydantic with FastAPI, you can define your API endpoints and operations directly in your FastAPI application. [FastAPI automatically generates the OpenAPI document for your API](/openapi/frameworks/fastapi#speakeasy-integration), including the `paths` section.
-
-Let's see how we can define API endpoints and operations in a framework-agnostic way and add them to the OpenAPI document.
+The next section defines API endpoints and operations in a framework-agnostic
+way and adds them to the OpenAPI document.
### Installing openapi-pydantic
-We'll use the [`openapi-pydantic`](https://github.com/mike-oakley/openapi-pydantic/) library to define a complete OpenAPI document with paths and operations.
+The [`openapi-pydantic`](https://github.com/mike-oakley/openapi-pydantic/)
+library defines a complete OpenAPI document with paths and operations.
-The benefit of using `openapi-pydantic` is that it allows you to define the API endpoints and operations in a Python dictionary while still getting the benefit of Pydantic's IDE support and type checking.
+The benefit of using `openapi-pydantic` is support for defining API endpoints
+and operations in a Python dictionary while preserving Pydantic IDE support and
+type checking.
-The library includes convenience methods to convert Pydantic models to OpenAPI document components and to add them to the OpenAPI document.
+The library includes convenience methods to convert Pydantic models to OpenAPI
+document components and to add them to the OpenAPI document.
Install the `openapi-pydantic` library:
@@ -1262,7 +901,8 @@ pip install openapi-pydantic
### Defining API endpoints
-Create a new file called `api.py` to define the API endpoints using the `openapi-pydantic` library:
+Create a new file called `api.py` to define the API endpoints using the
+`openapi-pydantic` library:
```python filename="api.py"
from typing import List
@@ -1270,93 +910,110 @@ import yaml
from pydantic import BaseModel, Field
from openapi_pydantic.v3 import OpenAPI, Info, PathItem, Operation
from openapi_pydantic.util import PydanticSchema, construct_open_api_with_schema_class
-from models import Pet, Owner
+from models import Station, Trip, Booking
# Define response wrapper models
-class PetsResponse(BaseModel):
- """A response containing a list of pets"""
- pets: List[Pet] = Field(..., description="List of pets")
+class StationsResponse(BaseModel):
+ """A response containing a list of stations."""
+ stations: List[Station] = Field(..., description="List of train stations")
+
+class TripsResponse(BaseModel):
+ """A response containing a list of trips."""
+ trips: List[Trip] = Field(..., description="List of train trips")
-class OwnersResponse(BaseModel):
- """A response containing a list of owners"""
- owners: List[Owner] = Field(..., description="List of owners")
+class BookingsResponse(BaseModel):
+ """A response containing a list of bookings."""
+ bookings: List[Booking] = Field(..., description="List of bookings")
def construct_base_open_api() -> OpenAPI:
return OpenAPI(
openapi="3.1.0",
- info=Info(title="Pet Sitter API", version="0.0.1"),
+ info=Info(title="Train Travel API", version="0.0.1"),
servers=[{"url": "http://127.0.0.1:4010", "description": "Local prism server"}],
paths={
- # GET and POST endpoints for pets collection
- "/pets": PathItem(
+ "/stations": PathItem(
get=Operation(
- operationId="listPets",
- description="List all pets",
+ operationId="listStations",
+ description="List all stations",
responses={
"200": {
- "description": "A list of pets",
+ "description": "A list of stations",
"content": {
"application/json": {
- "schema": PydanticSchema(schema_class=PetsResponse)
+ "schema": PydanticSchema(schema_class=StationsResponse)
}
},
}
},
),
- post=Operation(
- operationId="createPet",
- description="Create a pet",
- requestBody={
- "content": {
- "application/json": {"schema": PydanticSchema(schema_class=Pet)}
- }
- },
+ ),
+ "/trips": PathItem(
+ get=Operation(
+ operationId="listTrips",
+ description="List all trips",
responses={
- "201": {
- "description": "Pet created",
+ "200": {
+ "description": "A list of trips",
"content": {
- "application/json": {"schema": PydanticSchema(schema_class=Pet)}
+ "application/json": {
+ "schema": PydanticSchema(schema_class=TripsResponse)
+ }
},
}
},
),
),
- # GET endpoint for a specific pet by ID
- "/pets/{pet_id}": PathItem(
+ "/trips/{trip_id}": PathItem(
get=Operation(
- operationId="getPetById",
- description="Get a pet by ID",
+ operationId="getTripById",
+ description="Get a trip by ID",
parameters=[
{
- "name": "pet_id",
+ "name": "trip_id",
"in": "path",
- "description": "ID of pet to return",
+ "description": "ID of trip to return",
"required": True,
- "schema": {"type": "integer", "format": "int64"},
- "examples": {"1": {"value": 1}},
+ "schema": {"type": "string"},
+ "examples": {"trip_001": {"value": "trip_001"}},
},
],
responses={
"200": {
- "description": "A pet",
+ "description": "A trip",
"content": {
- "application/json": {"schema": PydanticSchema(schema_class=Pet)}
+ "application/json": {"schema": PydanticSchema(schema_class=Trip)}
},
}
},
),
),
- # GET endpoint for owners collection
- "/owners": PathItem(
+ "/bookings": PathItem(
+ post=Operation(
+ operationId="createBooking",
+ description="Create a booking",
+ requestBody={
+ "content": {
+ "application/json": {"schema": PydanticSchema(schema_class=Booking)}
+ }
+ },
+ responses={
+ "201": {
+ "description": "Booking created",
+ "content": {
+ "application/json": {"schema": PydanticSchema(schema_class=Booking)}
+ },
+ }
+ },
+ ),
get=Operation(
- operationId="listOwners",
- description="List all owners",
+ operationId="listBookings",
+ description="List all bookings",
responses={
"200": {
- "description": "A list of owners",
+ "description": "A list of bookings",
"content": {
"application/json": {
- "schema": PydanticSchema(schema_class=OwnersResponse)
+ "schema": PydanticSchema(schema_class=BookingsResponse)
}
},
}
@@ -1366,7 +1023,6 @@ def construct_base_open_api() -> OpenAPI:
},
)
-# Generate the complete OpenAPI document
open_api = construct_base_open_api()
open_api = construct_open_api_with_schema_class(open_api)
@@ -1384,12 +1040,12 @@ if __name__ == "__main__":
This code defines:
-1. Response models that wrap our Pydantic models (like `PetsResponse`) for consistent API responses
+1. Response models that wrap our Pydantic models for consistent API responses
2. A function that builds the OpenAPI document with four endpoints:
- - `GET /pets`: Lists all pets
- - `POST /pets`: Creates a new pet
- - `GET /pets/{pet_id}`: Gets a pet by ID
- - `GET /owners`: Lists all owners
+ - `GET /stations`: Lists all stations
+ - `GET /trips`: Lists available trips
+ - `GET /trips/{trip_id}`: Gets a trip by ID
+ - `GET /bookings` and `POST /bookings`: Lists and creates bookings
3. Each endpoint includes:
- An `operationId` for SDK generation
- A description of what the endpoint does
@@ -1401,88 +1057,101 @@ When run, this generates an `openapi.yaml` file with the full API specification:
```yaml filename="openapi.yaml"
openapi: 3.1.0
info:
- title: Pet Sitter API
+ title: Train Travel API
version: 0.0.1
servers:
- url: http://127.0.0.1:4010
description: Local prism server
paths:
- /pets:
+ /stations:
get:
- description: List all pets
- operationId: listPets
+ description: List all stations
+ operationId: listStations
responses:
"200":
- description: A list of pets
+ description: A list of stations
content:
application/json:
schema:
- $ref: "#/components/schemas/PetsResponse"
- post:
- description: Create a pet
- operationId: createPet
- requestBody:
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/Pet"
+ $ref: "#/components/schemas/StationsResponse"
+ /trips:
+ get:
+ description: List all trips
+ operationId: listTrips
responses:
- "201":
- description: Pet created
+ "200":
+ description: A list of trips
content:
application/json:
schema:
- $ref: "#/components/schemas/Pet"
- /pets/{pet_id}:
+ $ref: "#/components/schemas/TripsResponse"
+ /trips/{trip_id}:
get:
- description: Get a pet by ID
- operationId: getPetById
+ description: Get a trip by ID
+ operationId: getTripById
parameters:
- - name: pet_id
+ - name: trip_id
in: path
- description: ID of pet to return
+ description: ID of trip to return
required: true
schema:
- type: integer
- format: int64
+ type: string
examples:
- "1":
- value: 1
+ trip_001:
+ value: trip_001
responses:
"200":
- description: A pet
+ description: A trip
content:
application/json:
schema:
- $ref: "#/components/schemas/Pet"
- /owners:
+ $ref: "#/components/schemas/Trip"
+ /bookings:
get:
- description: List all owners
- operationId: listOwners
+ description: List all bookings
+ operationId: listBookings
responses:
"200":
- description: A list of owners
+ description: A list of bookings
content:
application/json:
schema:
- $ref: "#/components/schemas/OwnersResponse"
+ $ref: "#/components/schemas/BookingsResponse"
+ post:
+ description: Create a booking
+ operationId: createBooking
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Booking"
+ responses:
+ "201":
+ description: Booking created
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Booking"
components:
schemas:
# Schemas for our models are included here
- # (Pet, Owner, PetType, PetsResponse, OwnersResponse)
+ # (Station, Trip, Booking, BookingStatus, StationsResponse, TripsResponse, BookingsResponse)
```
-The generated OpenAPI document includes all the components from our Pydantic models, along with the API endpoints we defined. The schemas include all the titles, descriptions, examples, and other details we added to our Pydantic models.
+The generated OpenAPI document includes all the components from the Pydantic
+models along with the defined API endpoints. The schemas include titles,
+descriptions, examples, and other details added to the Pydantic models.
## Generating an SDK from the OpenAPI document
-Now that we have a complete OpenAPI document with paths and operations, we can use it to generate an SDK client for our API.
+A complete OpenAPI document with paths and operations is ready for SDK generation.
### Prerequisites for SDK generation
-Install Speakeasy by following the [Speakeasy installation instructions](/docs/speakeasy-reference/cli/getting-started#install)
+Install Speakeasy by following the [Speakeasy installation
+instructions](/docs/speakeasy-reference/cli/getting-started#install)
-On macOS, you can install Speakeasy using Homebrew:
+On macOS, Homebrew installs Speakeasy:
```bash filename="Terminal"
brew install speakeasy-api/tap/speakeasy
@@ -1502,33 +1171,51 @@ Run the following command to generate an SDK from the `openapi.yaml` file:
speakeasy quickstart
```
-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` when prompted for the OpenAPI document location and select TypeScript when prompted for which language you would like to generate.
+Use the onscreen prompts to provide the required SDK configuration details,
+including the name, schema location, and output path. Enter `openapi.yaml` as
+the OpenAPI document location and select TypeScript as the generation language.
-Speakeasy [validates](/docs/sdks/core-concepts#validation) the OpenAPI document to check that it's ready for code generation. Validation issues will be printed in the terminal. The generated SDK will be saved as a folder in your project.
+Speakeasy [validates](/docs/sdks/core-concepts#validation) the OpenAPI document
+to confirm readiness for code generation. Validation issues appear in the
+terminal, and the generated SDK saves as a folder in the project.
-
+
-Speakeasy also suggests improvements for your SDK using [Speakeasy Suggest](/docs/prep-openapi/maintenance), which is an AI-powered tool in Speakeasy Studio. You can view the suggestions in Speakeasy Studio:
+Speakeasy also suggests improvements for the SDK using [Speakeasy
+Suggest](/docs/prep-openapi/maintenance), an AI-powered tool in Speakeasy
+Studio. Suggestions appear in Speakeasy Studio:
-
+
### Adding Speakeasy extensions to the OpenAPI document
-Speakeasy uses [OpenAPI extensions](/openapi/extensions) to provide additional information for generating SDKs.
+Speakeasy uses [OpenAPI extensions](/openapi/extensions) to provide additional
+information for generating SDKs.
-We can add extensions using [OpenAPI overlays](/openapi/overlays), which are YAML files that [Speakeasy lays on top of the OpenAPI document](/docs/prep-openapi/overlays/create-overlays).
+Extensions can be added with [OpenAPI overlays](/openapi/overlays), which are
+YAML files that [Speakeasy lays on top of the OpenAPI
+document](/docs/prep-openapi/overlays/create-overlays).
-We can use overlays alongside [OpenAPI transformations](/docs/prep-openapi/transformations) to improve the OpenAPI document for SDK generation.
+Overlays can be used alongside [OpenAPI
+transformations](/docs/prep-openapi/transformations) to improve the OpenAPI
+document for SDK generation.
-Transformations are predefined functions that allow you to remove unused components, filter operations, and format your OpenAPI document. Unlike overlays, transformations directly modify the OpenAPI document itself.
+Transformations are predefined functions that remove unused components, filter
+operations, and format the OpenAPI document. Unlike overlays, transformations
+directly modify the OpenAPI document itself.
-Note that for Speakeasy OpenAPI extensions, you can also add extensions directly to the OpenAPI document using the `x-` prefix.
+For Speakeasy OpenAPI extensions, add extensions directly to the OpenAPI
+document using the `x-` prefix.
-For example, you can add the [`x-speakeasy-retries`](/docs/customize/runtime/retries) extension to have Speakeasy generate retry logic in the SDK.
+For example, add the [`x-speakeasy-retries`](/docs/customize/runtime/retries)
+extension to enable retry logic in the generated SDK.
-Import the `Dict` and `Any` types from the `typing` module in `api.py`, and `ConfigDict` from `pydantic`.
+Import the `Dict` and `Any` types from the `typing` module in `api.py`, and
+`ConfigDict` from `pydantic`.
-We'll use these types to define the `x-speakeasy-retries` extension in the OpenAPI document.
+These types define the `x-speakeasy-retries` extension in the OpenAPI document.
```python filename="api.py"
from typing import List, Dict, Any
@@ -1536,16 +1223,20 @@ import yaml
from pydantic import BaseModel, Field, ConfigDict
from openapi_pydantic.v3 import OpenAPI, Info, PathItem, Operation
from openapi_pydantic.util import PydanticSchema, construct_open_api_with_schema_class
-from models import Pet, Owner
+from models import Station, Trip, Booking
# Define response models
-class PetsResponse(BaseModel):
- """A response containing a list of pets"""
- pets: List[Pet] = Field(..., description="List of pets")
+class StationsResponse(BaseModel):
+ """A response containing a list of stations."""
+ stations: List[Station] = Field(..., description="List of stations")
+
+class TripsResponse(BaseModel):
+ """A response containing a list of trips."""
+ trips: List[Trip] = Field(..., description="List of trips")
-class OwnersResponse(BaseModel):
- """A response containing a list of owners"""
- owners: List[Owner] = Field(..., description="List of owners")
+class BookingsResponse(BaseModel):
+ """A response containing a list of bookings."""
+ bookings: List[Booking] = Field(..., description="List of bookings")
# Define OpenAPI class with retry extension
class OpenAPIwithRetries(OpenAPI):
@@ -1560,7 +1251,7 @@ class OpenAPIwithRetries(OpenAPI):
def construct_base_open_api() -> OpenAPIwithRetries:
return OpenAPIwithRetries(
openapi="3.1.0",
- info=Info(title="Pet Sitter API", version="0.0.1"),
+ info=Info(title="Train Travel API", version="0.0.1"),
servers=[{"url": "http://127.0.0.1:4010", "description": "Local prism server"}],
# Add retry configuration
xSpeakeasyRetries={
@@ -1598,29 +1289,32 @@ x-speakeasy-retries:
### Adding tags to the OpenAPI document
-To group operations in the OpenAPI document, you can use tags. This also allows Speakeasy to structure the generated SDK code and documentation logically.
+Tags group operations in the OpenAPI document and help structure generated SDK
+code and documentation logically.
-Add a `tags` field to the `OpenAPIwithRetries` object, then add a `tags` field to each operation in the `construct_base_open_api` function:
+Add a `tags` field to the `OpenAPIwithRetries` object, then add a `tags` field
+to each operation in the `construct_base_open_api` function:
```python filename="api.py"
def construct_base_open_api() -> OpenAPIwithRetries:
return OpenAPIwithRetries(
# Basic API info
openapi="3.1.0",
- info=Info(title="Pet Sitter API", version="0.0.1"),
+ info=Info(title="Train Travel API", version="0.0.1"),
# Define tags for grouping operations
tags=[
- {"name": "pets", "description": "Operations about pets"},
- {"name": "owners", "description": "Operations about owners"},
+ {"name": "stations", "description": "Operations about stations"},
+ {"name": "trips", "description": "Operations about trips"},
+ {"name": "bookings", "description": "Operations about bookings"},
],
# API endpoints with tags applied
paths={
- "/pets": PathItem(
+ "/stations": PathItem(
get=Operation(
- operationId="listPets",
- tags=["pets"],
+ operationId="listStations",
+ tags=["stations"],
# other properties...
),
),
@@ -1636,24 +1330,29 @@ python api.py
speakeasy quickstart
```
-Speakeasy will detect the changes to your OpenAPI document, generate the SDK with the updated tags, and automatically increment the SDK's version number.
+Speakeasy detects the OpenAPI changes, generates the SDK with updated tags, and
+increments the SDK version number automatically.
Take a look at the generated SDK to see how Speakeasy groups operations by tags.
-In the SDK `README.md` file, you'll find documentation about your Speakeasy SDK. TypeScript SDKs generated with Speakeasy include an installable [Model Context Protocol (MCP) server](/docs/standalone-mcp/build-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.
-
-Note that the SDK is not ready for production use. To get it production-ready, follow the steps outlined in your Speakeasy Studio workspace.
+The SDK `README.md` file includes documentation for the Speakeasy SDK.
+TypeScript SDKs generated with Speakeasy include an installable [Model Context
+Protocol (MCP) server](/docs/standalone-mcp/build-server) where SDK methods are
+exposed as tools for AI applications. The SDK documentation includes
+instructions for installing the MCP server.
-## How Speakeasy helps get your Pydantic models ready for SDK generation
+The SDK is not production-ready until the steps in the Speakeasy Studio
+workspace are completed.
-In this tutorial, we learned how to generate an OpenAPI document from Pydantic models and use it to generate an SDK client using Speakeasy.
+### Adding SDK generation to your CI/CD pipeline
-If you would like to discuss how to get your Pydantic models ready for SDK generation, give us feedback, or shoot the breeze about all things OpenAPI and SDKs, [join our Slack](https://go.speakeasy.com/slack).
+The Speakeasy
+[`sdk-generation-action`](https://github.com/speakeasy-api/sdk-generation-action)
+repository provides workflows for integrating the Speakeasy CLI into CI/CD
+pipelines to automatically regenerate SDKs when Pydantic schemas change.
-If you haven't already, take a look at our [blog](/blog) to learn more about API design, SDK generation, and our latest features, including:
+Speakeasy can be set up to automatically push a new branch to SDK repositories
+so that teammates can review and merge the SDK changes.
-- [Native JSONL support in your SDKs](/blog/release-jsonl-support)
-- [Introducing comprehensive SDK testing](/blog/release-sdk-testing)
-- [Model Context Protocol: TypeScript SDKs for the agentic AI ecosystem](/blog/release-model-context-protocol)
-- [Python generation with async and Pydantic support](/blog/release-python)
-- [Choosing your Python REST API framework](/blog/choosing-your-framework-python)
+For an overview of how to set up SDK automation, see the Speakeasy [SDK workflow
+syntax reference](/docs/speakeasy-reference/workflow-file).
From 29bfb136bc46ac8ec1a07575b23a917c9e1128db Mon Sep 17 00:00:00 2001
From: Phil Sturgeon <67381+philsturgeon@users.noreply.github.com>
Date: Wed, 9 Sep 2026 18:45:56 +0100
Subject: [PATCH 2/3] guide: pydantic update
---
openapi/frameworks/pydantic.mdx | 12 +++++-------
1 file changed, 5 insertions(+), 7 deletions(-)
diff --git a/openapi/frameworks/pydantic.mdx b/openapi/frameworks/pydantic.mdx
index 3dbcc0ea..857d5ba1 100644
--- a/openapi/frameworks/pydantic.mdx
+++ b/openapi/frameworks/pydantic.mdx
@@ -74,8 +74,7 @@ source venv/bin/activate
## Install the required libraries
-Pydantic, FastAPI, and PyYAML support schema generation and OpenAPI document
-formatting:
+Pydantic and PyYAML support schema generation and OpenAPI document formatting:
```bash filename="Terminal"
# Install the Pydantic library
@@ -83,19 +82,18 @@ pip install "pydantic>=2.13.4,<3"
# Install the PyYAML library for pretty-printing the OpenAPI schema
pip install "pyyaml>=6.0.3"
-
-# Install FastAPI for the API
-pip install "fastapi>=0.115.6"
```
## Pydantic to OpenAPI document walkthrough
The following steps generate an OpenAPI document from a Pydantic model without
-additional libraries and improve the result in stages.
+additional libraries and improve the result in stages. After the first pass, the
+API is previewed in Scalar so the generated document can be inspected and
+refined.
## Generating the first OpenAPI document
-The sample app in [examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic) exposes a minimal train travel API with stations, trips, and bookings.
+The sample app in [examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic) exposes a minimal train travel API with stations, trips, and bookings. After generating the initial OpenAPI document, the next step is to preview the API in Scalar and identify the gaps in the schema and documentation.
```bash filename="Terminal"
cd examples/framework-pydantic
From 6b571105c7feddbfb4ae2cd99675e9fcf3d95af1 Mon Sep 17 00:00:00 2001
From: Phil Sturgeon <67381+philsturgeon@users.noreply.github.com>
Date: Thu, 10 Sep 2026 07:44:06 +0100
Subject: [PATCH 3/3] added images and scalar mentions instead of swagger ui
---
openapi/frameworks/fastapi.mdx | 2 --
openapi/frameworks/pydantic.mdx | 12 +++++++-----
public/assets/openapi/pydantic/scalar-post.png | Bin 0 -> 407624 bytes
public/assets/openapi/pydantic/scalar.png | Bin 0 -> 148497 bytes
4 files changed, 7 insertions(+), 7 deletions(-)
create mode 100644 public/assets/openapi/pydantic/scalar-post.png
create mode 100644 public/assets/openapi/pydantic/scalar.png
diff --git a/openapi/frameworks/fastapi.mdx b/openapi/frameworks/fastapi.mdx
index c27be716..ced115c1 100644
--- a/openapi/frameworks/fastapi.mdx
+++ b/openapi/frameworks/fastapi.mdx
@@ -42,8 +42,6 @@ The following sections explain how FastAPI customization can streamline SDK gene
## Basic FastAPI setup
-The basics provide a foundation for the remaining examples.
-
These straightforward examples illustrate the three steps in the automation pipeline: FastAPI setup influences OpenAPI documents, which in turn influence SDK code.
### Scalar API documentation
diff --git a/openapi/frameworks/pydantic.mdx b/openapi/frameworks/pydantic.mdx
index 857d5ba1..3dbcc0ea 100644
--- a/openapi/frameworks/pydantic.mdx
+++ b/openapi/frameworks/pydantic.mdx
@@ -74,7 +74,8 @@ source venv/bin/activate
## Install the required libraries
-Pydantic and PyYAML support schema generation and OpenAPI document formatting:
+Pydantic, FastAPI, and PyYAML support schema generation and OpenAPI document
+formatting:
```bash filename="Terminal"
# Install the Pydantic library
@@ -82,18 +83,19 @@ pip install "pydantic>=2.13.4,<3"
# Install the PyYAML library for pretty-printing the OpenAPI schema
pip install "pyyaml>=6.0.3"
+
+# Install FastAPI for the API
+pip install "fastapi>=0.115.6"
```
## Pydantic to OpenAPI document walkthrough
The following steps generate an OpenAPI document from a Pydantic model without
-additional libraries and improve the result in stages. After the first pass, the
-API is previewed in Scalar so the generated document can be inspected and
-refined.
+additional libraries and improve the result in stages.
## Generating the first OpenAPI document
-The sample app in [examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic) exposes a minimal train travel API with stations, trips, and bookings. After generating the initial OpenAPI document, the next step is to preview the API in Scalar and identify the gaps in the schema and documentation.
+The sample app in [examples/framework-pydantic](https://github.com/speakeasy-api/examples/tree/main/examples/framework-pydantic) exposes a minimal train travel API with stations, trips, and bookings.
```bash filename="Terminal"
cd examples/framework-pydantic
diff --git a/public/assets/openapi/pydantic/scalar-post.png b/public/assets/openapi/pydantic/scalar-post.png
new file mode 100644
index 0000000000000000000000000000000000000000..49783fe0fd80055db9c249581a4f582bbe3a8f72
GIT binary patch
literal 407624
zcmbSy1yo#1wl)w58eD>Fu;A`aaQ9%rgG=KY+=4qa8a%kWyEGo$-QDf)+&eS(&Uq8JeI0tEn=GouREv3JoVFB)unxS_GLJFb*Zj=vNp(Aw|4mY<|^u&HcdsPU%h_1ZWvH|Rpp+xZMG**x0$T3K)}h8
zhZ#hc%URx}jw;4CKB+c34vKH=0^EV(?r#S=;J!lOeCfv-$OG=}!9fgvdAz;2!4rx<
zHi6CiCHVMiIe{Lw1qBiPHDoH#L71qg9r7C|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