new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

openapi/documentation

34 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Additional status codes not included in OpenAPI schema

When you return additional status codes and responses directly (without using OpenAPI documentation tools), they will not be included in the OpenAPI schema and API docs automatically. To document additional responses in OpenAPI, use the Additional Responses feature.

Docs UI server selection behavior

The FastAPI docs UI (Swagger UI) allows selecting between different servers configured in the OpenAPI schema. The selected server determines which server the docs UI will interact with when testing endpoints.

OpenAPI servers property is optional

The servers property in the OpenAPI specification is optional. If root_path equals "/" and no custom servers are specified, the servers property is omitted from the generated OpenAPI schema by default, which is equivalent to a single server with url "/".

FastAPI generates OpenAPI 3.1 specifications

FastAPI automatically generates OpenAPI 3.1 specifications. SDK generators and tools used to generate clients must support this OpenAPI version.

OpenAPI Generator for SDK generation

OpenAPI Generator is a versatile, open-source tool that supports many programming languages and can generate SDKs from OpenAPI specifications.

Hey API for TypeScript SDK generation

Hey API is a purpose-built, open-source solution optimized for generating TypeScript clients from OpenAPI specifications. It provides a better experience for the TypeScript ecosystem compared to generic generators.

Generate TypeScript SDK with Hey API using npx

To generate a TypeScript SDK with Hey API, use the command: npx @hey-api/openapi-ts -i http://localhost:8000/openapi.json -o src/client. This generates a TypeScript SDK in the ./src/client directory.

Hey API client generation with local OpenAPI file

To generate a TypeScript client from a local OpenAPI JSON file, use: npx @hey-api/openapi-ts -i ./openapi.json -o src/client

FastAPI path operations use tags for client organization

When a FastAPI app uses tags on path operations, generated TypeScript client code is automatically organized by tag. Each tag becomes a separate service class (e.g., ItemsService, UsersService).

Operation ID generation in FastAPI

FastAPI generates unique operation IDs for each path operation by combining the function name, the path, and the HTTP method. This ensures operation IDs are globally unique across all path operations.

Custom generate_unique_id_function parameter

FastAPI accepts a generate_unique_id_function parameter that customizes how operation IDs are generated. The function takes an APIRoute object and returns a string. This allows you to control operation ID format for better client method naming.

Custom operation ID function example using tag and name

A custom operation ID function can use the first tag and the path operation name (function name) to generate cleaner operation IDs. Pass this function to FastAPI via the generate_unique_id_function parameter.

Preprocess OpenAPI specification for cleaner client method names

You can download the OpenAPI JSON specification to a file and preprocess it with a script to remove redundant information (like tag prefixes) before generating the client. This produces cleaner method names while preserving unique operation IDs in the OpenAPI spec itself.

Generated TypeScript clients provide autocompletion

TypeScript clients generated from FastAPI apps provide autocompletion for methods, request payloads (including body, query parameters), and response payloads. They also show inline errors for data mismatches.

SDK generation benefits for error detection

Automatically generated clients detect many errors early in the development cycle. When backend code changes and the client is regenerated, any mismatches in data are caught during the build phase rather than in production.

OpenAPI.Tools SDK generator directory

Additional SDK generators can be discovered on OpenAPI.Tools website, which maintains a directory categorized by SDK generator tools.

OpenAPI callbacks overview and use case

OpenAPI callbacks document how an external API should look when your FastAPI app calls it back. In a callback pattern, your API receives a request from an external developer, processes it, and then sends a callback request to an external API endpoint provided by that developer. This is used to document the contract for what the external API should accept and return.

Invoice example with callbacks

An example use case is an invoicing app where: the external developer creates an invoice in your API with a POST request, your API processes it, then sends a notification callback to an external API endpoint (provided by the external developer) to report the result (e.g., payment received).

callback_url query parameter with Pydantic Url type

The path operation for creating an invoice should accept a query parameter called callback_url that uses Pydantic's Url type. This parameter contains the URL where your API will send the callback request.

Create APIRouter for callback documentation

Create a new APIRouter to contain the callback path operations. This router holds the documentation for how the external API should look, not the actual implementation of the callbacks.

Callback path operation structure

The callback path operation should look like a normal FastAPI path operation with a body parameter (e.g., InvoiceEvent model) and optional response model (e.g., InvoiceEventReceived). However, it does not need actual code in the function body since it is only for documentation; the function can just have `pass`.

OpenAPI 3 expressions in callback paths

The callback path can contain OpenAPI 3 expressions that reference parts of the original request sent to your API. These expressions use syntax like `{$callback_url}` to reference query parameters and `{$request.body.id}` to reference fields from the request body.

Callback path expression example

A callback path expression example is `"{$callback_url}/invoices/{$request.body.id}"`. If the callback_url query parameter is `https://www.external.org/events` and the request body contains `id: "2expen51ve"`, the resulting callback URL will be `https://www.external.org/events/invoices/2expen51ve`.

Using callbacks parameter in path operation decorator

Pass the callback router's routes to your API's path operation decorator using the `callbacks` parameter. The syntax is `callbacks=invoices_callback_router.routes`, passing the `.routes` attribute, not the router itself. FastAPI will use these routes to generate the callback OpenAPI documentation.

Callback documentation appears in Swagger UI

When you add callbacks to a path operation and view the documentation at `/docs`, a "Callbacks" section appears for that path operation showing how the external API should look according to the documented callback operations.

Callback implementation tools

When implementing the actual callback in your app (not just the documentation), you can use libraries like HTTPX or Requests to send the HTTP request to the external API.

operation_id parameter sets OpenAPI operationId

You can set the OpenAPI operationId for a path operation using the operation_id parameter in the path operation decorator. You must ensure that it is unique for each operation.

generate_unique_id_function for custom operationId generation

You can pass a custom generate_unique_id_function to FastAPI() to dynamically generate operationId values. The function receives each APIRoute and returns the operationId string to use for that path operation. If you use this approach, you must ensure that each path operation function has a unique name, even if they are in different modules.

include_in_schema=False excludes path operation from OpenAPI

To exclude a path operation from the generated OpenAPI schema and automatic documentation systems, set the include_in_schema parameter to False in the path operation decorator.

Docstring truncation with \f character in path operations

You can use an escaped form feed character (\f) in the docstring of a path operation function to truncate the text used for OpenAPI documentation at that point. The text after \f will not appear in the documentation but can be used by other tools like Sphinx.

openapi_extra parameter for extending OpenAPI schema

The openapi_extra parameter on a path operation allows you to extend or customize the OpenAPI schema for that operation. This dictionary will be deeply merged with the automatically generated OpenAPI schema for the path operation.

OpenAPI Extensions with openapi_extra

You can declare OpenAPI Extensions using the openapi_extra parameter. Extensions appear at the bottom of the specific path operation in the automatic API docs and are included in the OpenAPI schema at /openapi.json.

Custom OpenAPI schema for request body without Pydantic

You can use openapi_extra to define a custom request body schema in OpenAPI even when you are not using FastAPI's automatic features with Pydantic. This allows you to manually parse the request (such as reading it as bytes) while still documenting the expected schema in OpenAPI. The function can then handle parsing the data in its own way.

Custom content type with Pydantic model and openapi_extra

You can use a Pydantic model to generate JSON Schema that is included in openapi_extra to document a request with a custom content type (such as YAML instead of JSON). FastAPI will not automatically parse the request, but you can extract the body as bytes and manually parse it while still using the Pydantic model for validation.

Give your agent this brain