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 · all subjects

architecture

72 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

FastAPI uses Pydantic for data validation and serialization

FastAPI uses Pydantic to handle all data validation, data serialization, and automatic model documentation based on JSON Schema. Pydantic is based on Python type hints and provides JSON Schema data that FastAPI incorporates into OpenAPI specifications.

FastAPI built on Starlette and Uvicorn

FastAPI is based on Starlette (a lightweight ASGI framework) and uses Uvicorn as its recommended web server. The FastAPI class inherits directly from Starlette, so anything possible with Starlette can be done with FastAPI.

Starlette ASGI framework capabilities

Starlette provides seriously impressive performance, WebSocket support, in-process background tasks, startup and shutdown events, test client built on HTTPX, CORS, GZip, static files, streaming responses, session and cookie support, 100% test coverage, and 100% type annotated codebase.

Uvicorn is a lightning-fast ASGI server

Uvicorn is a lightning-fast ASGI server built on uvloop and httptools. It is not a web framework but a server, and is the recommended server for Starlette and FastAPI. It supports a command line option --workers for asynchronous multi-process server deployment.

FastAPI development efficiency advantage

By using FastAPI instead of lower-level frameworks, developers save development time, reduce bugs, and write fewer lines of code. Applications built with FastAPI typically achieve the same or better performance than those built without it where developers would have to implement data validation and serialization manually.

Automatic documentation in FastAPI has no runtime overhead

FastAPI's automatic documentation is generated on startup and does not add any overhead to running applications.

Technology stack hierarchy

The FastAPI technology stack has a hierarchical relationship: Uvicorn is an ASGI server; Starlette is a web microframework that uses Uvicorn; FastAPI is an API microframework with data validation that uses Starlette.

Why FastAPI cannot be faster than Starlette

FastAPI uses Starlette internally and therefore cannot be faster than Starlette, as it adds additional features on top of Starlette such as data validation and serialization.

When to compare FastAPI in benchmarks

When comparing FastAPI performance, compare it against frameworks or tool sets that provide integrated automatic data validation, serialization, and documentation, such as Flask-apispec, NestJS, or Molten, not against simpler tools like Uvicorn or Starlette alone.

Starlette chosen as FastAPI key requirement

Starlette is a key requirement and dependency of FastAPI. The creator of FastAPI contributed to Starlette during its development.

FastAPI design based on standards investigation

Before coding FastAPI, the creator spent several months studying the specifications for OpenAPI, JSON Schema, and OAuth2 to understand their relationships, overlaps, and differences.

FastAPI based on Python 3.6+ type hints

FastAPI was designed to be based on standard Python type hints, which were available in Python 3.6 and later. The creator spent several months understanding existing standards like OpenAPI, JSON Schema, and OAuth2 before designing FastAPI to use these type hints as a core feature.

Pydantic chosen as FastAPI requirement

FastAPI uses Pydantic for data validation. The creator contributed to Pydantic to make it fully compliant with JSON Schema, support different constraint declaration methods, and improve editor support for type checks and autocompletion.

Pydantic complex nested structures

Pydantic supports validation of complex nested structures using hierarchical models, Python typing's List and Dict, and custom validators. Deeply nested JSON objects can be validated and annotated.

Pydantic custom data types and extensibility

Pydantic allows custom data types to be defined and enables validation extension with methods decorated with the validator decorator. Pydantic has 100% test coverage.

Python dict unpacking with ** operator

The `**dict_name` syntax unpacks dictionary keys and values as key-value arguments to a function or constructor. For example, `User(**second_user_data)` is equivalent to `User(id=4, name='Mary', joined='2018-11-30')` when `second_user_data` contains those keys and values.

FastAPI based on OpenAPI standard

FastAPI uses OpenAPI for API creation, including declarations of path operations, parameters, request bodies, and security. It includes automatic data model documentation with JSON Schema, as OpenAPI itself is based on JSON Schema.

FastAPI automatic API documentation options

FastAPI provides two interactive API documentation web user interfaces by default: Swagger UI for interactive exploration and testing directly from the browser, and ReDoc as an alternative API documentation option. Both are based on OpenAPI specification.

FastAPI validation for data types

FastAPI validates most Python data types including JSON objects (dict), JSON arrays (list with item types), strings (str) with min and max lengths, and numbers (int, float) with min and max values. It also validates exotic types like URL, Email, and UUID. All validation is handled by Pydantic.

FastAPI security and authentication schemes

FastAPI supports all OpenAPI-defined security schemes: HTTP Basic, OAuth2 (including with JWT tokens), and API keys in headers, query parameters, and cookies. It also includes Starlette security features like session cookies. Security tools are reusable and integrate with any database system.

FastAPI dependency injection system

FastAPI includes a dependency injection system that allows dependencies to have dependencies, creating a hierarchy or graph of dependencies. All dependencies are automatically handled by the framework and can require data from requests and augment path operation constraints and documentation. Automatic validation applies to path operation parameters defined in dependencies.

FastAPI plugin integration via dependencies

FastAPI allows simple integration of additional code through its dependency system. Any integration can be created as a plugin in two lines of code using the same structure and syntax used for path operations, with no separate plugin framework needed.

FastAPI test coverage and type annotations

FastAPI has 100% test coverage and 100% type-annotated codebase. It is used in production applications.

FastAPI is a Starlette subclass

FastAPI is a sub-class of Starlette and is fully compatible with it. Any additional Starlette code will work with FastAPI. FastAPI provides all Starlette features with additional enhancements.

Starlette features in FastAPI

FastAPI includes all Starlette features: serious performance (one of the fastest Python frameworks), WebSocket support, in-process background tasks, startup and shutdown events, test client built on HTTPX, CORS, GZip, Static Files, Streaming responses, Session and Cookie support, 100% test coverage, and 100% type-annotated codebase.

FastAPI based on Pydantic

FastAPI is fully compatible with and based on Pydantic. All Pydantic features are available in FastAPI. External libraries based on Pydantic, such as ORMs and ODMs for databases, also work with FastAPI.

Pydantic data validation and database integration

Pydantic validates all data in FastAPI. In many cases, objects received from requests can be passed directly to the database as everything is automatically validated. Similarly, objects from the database can often be passed directly to the client.

Pydantic schema definition using Python types

Pydantic uses standard Python type syntax for schema definition, with no separate micro-language to learn. IDE autocompletion, linting, and mypy work properly with Pydantic-validated data.

Custom route handler example: X-Response-Time header

A custom APIRoute class can be used to add extra headers to responses. For example, a TimedRoute class can measure the time it takes to generate a response and add an X-Response-Time header to the response.

Override Request and APIRoute classes

You can override the logic used by the Request and APIRoute classes. This is an advanced feature and may be a good alternative to middleware logic, for example when you want to read or manipulate the request body before it is processed by the application.

Custom Request class use cases

Use cases for custom Request subclasses include: converting non-JSON request bodies to JSON (e.g. msgpack), decompressing gzip-compressed request bodies, and automatically logging all request bodies.

GzipRequest class pattern

To create a custom GzipRequest class, subclass Request and overwrite the Request.body() method to decompress the body when an appropriate gzip header is present. If there is no gzip in the header, it will not try to decompress the body, allowing the same route class to handle both gzip compressed and uncompressed requests.

GzipRoute class pattern

To create a custom APIRoute subclass that uses a custom Request class, subclass fastapi.routing.APIRoute and overwrite the APIRoute.get_route_handler() method. This method returns a function that receives a request and returns a response. In the function, convert the original Request to your custom Request class (e.g., GzipRequest) before passing it to path operations.

Request.scope and Request.receive

A Request instance has a request.scope attribute, which is a Python dict containing metadata related to the request. A Request also has a request.receive, which is a function to receive the body of the request. The scope dict and receive function are both part of the ASGI specification and are what is needed to create a new Request instance.

Accessing request body in exception handler

When handling exceptions, you can access the request body by wrapping the request handling in a try/except block. If an exception occurs, the Request instance will still be in scope, allowing you to read and use the request body when handling the error.

APIRouter route_class parameter

You can set the route_class parameter of an APIRouter to specify a custom APIRoute subclass. Path operations registered under the router will use the custom route class.

Strawberry is the recommended GraphQL library for FastAPI

Strawberry is the recommended GraphQL library to use with FastAPI because it has a design closest to FastAPI's design and is entirely based on type annotations, making it a natural fit for FastAPI projects.

GraphQL libraries with ASGI support for FastAPI

Several GraphQL libraries have ASGI support and can be used with FastAPI: Strawberry (with dedicated FastAPI integration docs), Ariadne (with dedicated FastAPI integration docs), Tartiflette (with Tartiflette ASGI providing ASGI integration), and Graphene (with starlette-graphene3 wrapper).

Starlette GraphQLApp deprecation and migration path

The GraphQLApp class from previous versions of Starlette has been deprecated. Projects using it for Graphene integration can migrate to starlette-graphene3, which covers the same use case and has an almost identical interface.

FastAPI and GraphQL integration with ASGI

FastAPI is based on the ASGI standard, which makes it very easy to integrate any GraphQL library that is also compatible with ASGI. You can combine normal FastAPI path operations with GraphQL on the same application.

app.routes and get_openapi traversal

`app.routes` is a lower-level route tree that may include route candidates used internally for included routers, not only final `APIRoute` objects. When passing `app.routes` to `get_openapi()`, FastAPI traverses the route tree to collect the effective path operations.

Add ReDoc OpenAPI extensions to custom schema

To add ReDoc OpenAPI extensions like a custom logo, modify the OpenAPI schema dictionary by adding vendor-specific fields like `x-logo` to the `info` object before caching and returning the schema.

get_openapi function parameters

The `fastapi.openapi.utils.get_openapi()` function accepts the following parameters: `title` (the OpenAPI title shown in docs), `version` (the API version, e.g. '2.5.0'), `openapi_version` (OpenAPI specification version, defaults to '3.1.0'), `summary` (short API summary, available in OpenAPI 3.1.0+ and FastAPI 0.99.0+), `description` (API description supporting markdown), and `routes` (the routes from `app.routes` used to collect registered path operations including those from included routers).

FastAPI OpenAPI schema generation process

A FastAPI application has an `.openapi()` method that returns the OpenAPI schema. During application creation, a path operation for `/openapi.json` (or the configured `openapi_url`) is registered that returns a JSON response with the result of `.openapi()`. By default, `.openapi()` checks the property `.openapi_schema` for cached contents and returns them. If not cached, it generates the schema using `fastapi.openapi.utils.get_openapi()`.

Override FastAPI OpenAPI schema with custom_openapi function

To override the OpenAPI schema, create a `custom_openapi()` function that calls `get_openapi()` with the required parameters, modifies the returned schema dictionary as needed, caches it in `app.openapi_schema`, and returns the modified schema. Then assign this function to `app.openapi = custom_openapi` to replace the default `.openapi()` method.

Cache OpenAPI schema with .openapi_schema property

Use the `.openapi_schema` property as a cache to store the generated OpenAPI schema. This prevents the application from regenerating the schema on every request. The schema is generated once and the cached version is reused for subsequent requests.

FastAPI learning path is official recommended course

The FastAPI documentation Learn section functions as the official and recommended way to learn FastAPI. It is structured as introductory sections and tutorials, comparable to a book or course.

Full Stack FastAPI Template frontend stack

The frontend uses React with TypeScript, hooks, and Vite. It includes Tailwind CSS and shadcn/ui for components, an automatically generated frontend client, Playwright for End-to-End testing, and dark mode support.

Full Stack FastAPI Template repository

The Full Stack FastAPI Template is available at https://github.com/fastapi/full-stack-fastapi-template. It provides a complete starting point with initial setup, security, database, and API endpoints already implemented.

Full Stack FastAPI Template backend stack

The backend uses FastAPI for the Python API, SQLModel for SQL database interactions and ORM, Pydantic for data validation and settings management, and PostgreSQL as the SQL database.

Full Stack FastAPI Template deployment and infrastructure

The template uses Docker Compose for development and production, Traefik as a reverse proxy and load balancer, GitHub Actions for CI/CD, and includes deployment instructions for setting up automatic HTTPS certificates.

Request body with Pydantic model example

Example using Pydantic BaseModel for request bodies: ```Python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool | None = None @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} ``` This demonstrates: Pydantic model declaration, PUT operation, path parameter, and request body validation.

FastAPI definition and core purpose

FastAPI is a modern, fast, high-performance web framework for building APIs with Python, based on standard Python type hints. It is built on Starlette for web parts and Pydantic for data parts.

FastAPI key features

FastAPI provides: high performance on par with NodeJS and Go; fast development speed (about 200-300% faster); approximately 40% fewer human-induced errors; great editor support with completion everywhere; easy to learn and use; minimal code duplication; production-ready code with automatic interactive documentation; and standards-based compatibility with OpenAPI and JSON Schema.

Basic FastAPI path operation example

A simple FastAPI application: ```Python from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str | None = None): return {"item_id": item_id, "q": q} ``` This example demonstrates: GET path operations, path parameters (item_id as int), and optional query parameters (q with default None).

FastAPI parameter validation and conversion

FastAPI automatically: validates path parameters (e.g., item_id must be int); validates optional query parameters; validates request body from JSON; checks required vs optional attributes; provides clear error messages for invalid data; converts between JSON and Python types; converts Python types (str, int, float, bool, list), datetime objects, UUID objects, and database models.

FastAPI tutorial spoiler features

The FastAPI tutorial covers: parameters from headers, cookies, form fields, and files; validation constraints like maximum_length and regex; powerful dependency injection system; security and authentication including OAuth2 with JWT tokens and HTTP Basic auth; deeply nested JSON models using Pydantic; GraphQL integration with Strawberry; WebSockets; CORS; Cookie Sessions; testing with HTTPX and pytest.

FastAPI core dependencies

FastAPI depends on Pydantic (for data validation) and Starlette (for web framework components).

FastAPI CLI installation via pip

The FastAPI CLI is installed when you install FastAPI using `pip install "fastapi[standard]"`.

fastapi dev command for development

Use the command `fastapi dev` to run your FastAPI app in development mode. This starts a development server with auto-reload enabled by default.

Give your agent this brain