Path operation decorator syntax
Use decorators like @app.get(), @app.post(), @app.put(), @app.delete(), @app.options(), @app.head(), @app.patch(), or @app.trace() to define path operations. The decorator syntax is @app.METHOD(path) where METHOD is the HTTP method and path is the URL path like '/'.
OpenAPI schema generation
FastAPI automatically generates an OpenAPI schema following the OpenAPI 3.1.0 specification. The schema is available as JSON at http://127.0.0.1:8000/openapi.json and includes all API paths, parameters, and data definitions using JSON Schema.
Path vs endpoint vs route terminology
In FastAPI, 'path' refers to the last part of the URL starting from the first forward slash, like /items/foo. The terms 'path', 'endpoint', and 'route' are commonly used interchangeably.
HTTP methods and their common uses
HTTP methods in FastAPI include GET (read data), POST (create data), PUT (update data), DELETE (delete data), OPTIONS, HEAD, PATCH, and TRACE. FastAPI does not enforce specific meanings for these methods; they are guidelines.
Configure app entrypoint in pyproject.toml
Set [tool.fastapi] entrypoint = 'main:app' in pyproject.toml to configure where the FastAPI app is located. For nested modules like backend/main.py, use entrypoint = 'backend.main:app' which is equivalent to 'from backend.main import app'.
FastAPI import and instance creation
Import the FastAPI class and create an instance called app. FastAPI is a Python class that provides all the functionality for your API and inherits directly from Starlette.
Automatic API documentation endpoints
FastAPI automatically provides interactive API documentation at http://127.0.0.1:8000/docs (Swagger UI) and http://127.0.0.1:8000/redoc (ReDoc).
Run FastAPI development server
Run the development server with the command 'uv run fastapi dev'. The server starts at http://127.0.0.1:8000 and automatically reloads on file changes.
Return types in path operation functions
Path operation functions can return dicts, lists, singular values as strings or integers, and Pydantic models. Many other objects and models including ORMs are automatically converted to JSON.
Path operation function definition
The function below a path operation decorator is the path operation function. It handles requests to that specific path and HTTP method. It can be defined as either an async function (async def) or a normal function (def).
Declare duplicate headers using list type
To receive duplicate headers (the same header appearing multiple times with different values), declare the parameter type as a list. FastAPI will return all values from the duplicate header as a Python list.
Import Header from fastapi
To use header parameters in FastAPI, import Header from the fastapi module.
Declare Header parameters same as Query, Path, Cookie
Header parameters are declared using the same structure as Path, Query, and Cookie parameters. You can define default values and all extra validation or annotation parameters using Header.
Header is a sister class to Path, Query, Cookie
Header is a sister class of Path, Query, and Cookie. It inherits from the same common Param class. When imported from fastapi, Header is actually a function that returns a special class.
Must use Header to declare headers, not query parameters
To declare headers, you must use Header. Otherwise, the parameters would be interpreted as query parameters.
Header automatic underscore to hyphen conversion
By default, Header automatically converts parameter names from underscore (_) to hyphen (-) to extract and document headers. This allows you to use Python-style snake_case variable names like user_agent instead of requiring hyphenated header names like user-agent. HTTP headers are case-insensitive, so you can declare them in standard Python style (snake_case).
Disable Header underscore to hyphen conversion with convert_underscores parameter
If you need to disable automatic conversion of underscores to hyphens in Header parameters, set the parameter convert_underscores to False. However, be aware that some HTTP proxies and servers disallow the usage of headers with underscores.
Duplicate header example response
When declaring a header like X-Token as a list type and receiving duplicate headers with values 'foo' and 'bar', the response returns the header values in a JSON array: {"X-Token values": ["bar", "foo"]}.
Documentation available at /docs endpoint
When running a FastAPI application with the development server, interactive API documentation is automatically available at http://127.0.0.1:8000/docs.
Run FastAPI examples with fastapi dev command
To run FastAPI code examples, copy the code to a file named main.py and start the development server using the command: uv run fastapi dev. This will start the server at http://127.0.0.1:8000 with automatic reloading for changes.
Install FastAPI with uv package manager
To set up a FastAPI project, first install uv, then create a project directory with uv init awesome-project --bare, navigate into it with cd awesome-project, and add FastAPI with uv add "fastapi[standard]". This creates a virtual environment in .venv and records dependencies in pyproject.toml and uv.lock.
FastAPI standard installation includes optional dependencies
Installing with uv add "fastapi[standard]" includes default optional standard dependencies such as fastapi-cloud-cli for FastAPI Cloud deployment. To avoid these, use uv add fastapi instead. To include standard dependencies without fastapi-cloud-cli, use uv add "fastapi[standard-no-fastapi-cloud-cli]".
Install FastAPI with pip as alternative
As an alternative to uv, you can install FastAPI using pip. Create and activate a virtual environment manually, then run pip install "fastapi[standard]".
FastAPI includes official skill for AI coding agents
FastAPI includes an official skill for AI coding agents that stays aligned with the installed version. After installing FastAPI, you can install the skill using: uvx library-skills. This skill is compatible with Codex, Claude Code, Cursor, GitHub Copilot, Gemini CLI, Pi, OpenCode, and most other coding agents.
FastAPI metadata parameters for OpenAPI and docs
FastAPI accepts the following metadata parameters in the FastAPI constructor: title (str, the title of the API), summary (str, a short summary of the API, available since OpenAPI 3.1.0 and FastAPI 0.99.0), description (str, a short description of the API that can use Markdown), version (str, the version of your own application), terms_of_service (str, a URL to the Terms of Service), contact (dict, contact information with optional name, url, and email fields), and license_info (dict, license information with required name field and optional identifier or url fields).
OpenAPI schema default URL in FastAPI
By default, the OpenAPI schema is served at /openapi.json. This can be configured with the openapi_url parameter, or disabled entirely by setting openapi_url=None.
Disabling OpenAPI schema disables documentation UIs
Setting openapi_url=None in FastAPI will disable the OpenAPI schema completely, which also disables the documentation user interfaces that depend on it (Swagger UI and ReDoc).
FastAPI Swagger UI documentation URL configuration
Swagger UI is served by default at /docs. The URL can be configured with the docs_url parameter or disabled by setting docs_url=None.
FastAPI ReDoc documentation URL configuration
ReDoc is served by default at /redoc. The URL can be configured with the redoc_url parameter or disabled by setting redoc_url=None.
Markdown support in openapi_tags descriptions
Descriptions in openapi_tags support Markdown formatting and will be rendered in the documentation UI, allowing for formatting such as bold and italic text.
Tags metadata not required for all tags
It is not necessary to add metadata for all tags used in your FastAPI application; you can add metadata selectively using openapi_tags.
contact dict fields in FastAPI metadata
The contact parameter accepts a dict with three optional fields: name (str, the identifying name of the contact person/organization), url (str, must be in URL format, pointing to contact information), and email (str, must be in email address format).
license_info dict fields in FastAPI metadata
The license_info parameter accepts a dict with three fields: name (str, REQUIRED if license_info is set, the license name used for the API), identifier (str, an SPDX license expression for the API, mutually exclusive with url field, available since OpenAPI 3.1.0 and FastAPI 0.99.0), and url (str, must be in URL format, a URL to the license used for the API).
Markdown in FastAPI description field
The description field in FastAPI metadata parameters supports Markdown formatting, which will be rendered in the output and API documentation user interfaces.
openapi_tags parameter for tag metadata
The openapi_tags parameter takes a list of dictionaries, with each dictionary containing metadata for a tag. Each dictionary must have: name (str, required, the same tag name used in path operations and APIRouters), description (str, optional, a short description for the tag that can have Markdown), and externalDocs (dict, optional, containing description and url fields).
externalDocs dict fields in openapi_tags
The externalDocs field in openapi_tags is a dict containing: description (str, optional, a short description for the external docs) and url (str, required, the URL for the external documentation).
Tag order in FastAPI documentation
The order of tag metadata dictionaries in the openapi_tags list defines the order in which tags are shown in the documentation UI, rather than alphabetical order.
Description from docstring in path operations
You can declare the path operation description in the function docstring (a multi-line string as the first expression inside the function) and FastAPI will read it from there. You can write Markdown in the docstring and it will be interpreted and displayed correctly in the interactive docs, accounting for docstring indentation.
Summary and description parameters
You can add summary and description parameters to a path operation decorator to provide metadata about the operation that appears in the OpenAPI schema and documentation.
Tags with Enums in path operations
FastAPI supports using an Enum for tags in path operations the same way as with plain strings. This allows you to store and reuse consistent tags across related path operations in large applications.
Path operation decorator parameters configuration
Path operation decorators accept parameters to configure the path operation. These parameters are passed directly to the path operation decorator, not to the path operation function itself.
Response status code in path operations
You can define the HTTP status_code to be used in the response of a path operation by passing the status_code parameter to the decorator. You can pass directly the integer code (like 404) or use shortcut constants from fastapi.status. The status code will be added to the OpenAPI schema.
fastapi.status provides Starlette status constants
FastAPI provides the same starlette.status as fastapi.status as a convenience. You can import status constants from either fastapi.status or starlette.status.
Tags parameter for path operations
You can add tags to a path operation by passing the tags parameter with a list of strings to the path operation decorator. Tags are added to the OpenAPI schema and used by automatic documentation interfaces to group related operations.
Response description parameter
You can specify the response description with the response_description parameter in the path operation decorator. This refers specifically to the response, while the description parameter refers to the path operation in general. If no response_description is provided, FastAPI automatically generates "Successful response".
Deprecating a path operation
You can mark a path operation as deprecated without removing it by passing the deprecated parameter set to True in the path operation decorator. Deprecated operations are clearly marked as such in the interactive documentation.
Query and Path are functions that return class instances
When you import Query, Path, and others from fastapi, they are actually functions. When called, these functions return instances of classes of the same name. They are implemented as functions (rather than using classes directly) so that editors don't mark type errors and you can use normal coding tools without custom configurations.
Import Path and Annotated for path parameter validation
To validate path parameters in FastAPI, import Path from fastapi and import Annotated. FastAPI added support for Annotated starting in version 0.95.0. If using an older version, you will get errors when trying to use Annotated. Upgrade FastAPI to at least version 0.95.1 before using Annotated.
Path parameters are always required
A path parameter is always required as it has to be part of the path. Even if you declare it with None or set a default value, it will not affect anything and the parameter will still always be required.
FastAPI detects parameters by name, type, and default declarations
FastAPI detects parameters by their names, types, and default declarations (Query, Path, etc). It does not care about the order of parameters in the function signature. This means you can reorder parameters as needed without affecting FastAPI's behavior.
Use * to declare keyword-only parameters without Annotated
If you want to declare query parameters without Query or default values, and path parameters using Path, and have them in a different order without using Annotated, you can pass * as the first parameter of the function. This tells Python that all following parameters must be called as keyword arguments (kwargs), even if they don't have a default value.
Annotated eliminates parameter ordering issues
When using Annotated, you do not use function parameter default values for Query() or Path(), so parameter ordering issues disappear. You won't need to use the * trick or worry about putting required parameters before optional ones.
Path supports same metadata and validation as Query
You can declare all the same parameters for Path as you can for Query, including metadata like title values and validation constraints.
Numeric validation operators: ge, gt, le, lt
FastAPI supports the following numeric validation operators for both Query and Path: ge (greater than or equal), gt (greater than), le (less than or equal), and lt (less than). These work with both integer and float values.
Use ge=1 to require integer greater than or equal to 1
To declare that a path parameter must be an integer greater than or equal to 1, use ge=1 in the Path declaration.
gt allows validation of floats between 0 and 1
The gt (greater than) operator is useful for float values because it allows you to require values greater than 0 without requiring them to be greater than or equal to 1. For example, 0.5 would be valid, but 0.0 or 0 would not be valid.
Query, Path, and other classes are subclasses of Param
Query, Path, and other validation classes you will see in FastAPI are subclasses of a common Param class. They all share the same parameters for additional validation and metadata.
Query parameter models supported since FastAPI 0.115.0
Query parameter models using Pydantic are supported starting with FastAPI version 0.115.0.
Query parameter optional syntax with str | None
To declare a query parameter as optional in FastAPI, use the type annotation `str | None` with a default value of `None`. FastAPI recognizes the `= None` default value and knows the parameter is not required. This allows the editor to provide better support and detect errors.
Import Query and Annotated for parameter validation
To add validation to query parameters, import `Query` from `fastapi` and `Annotated` from `typing`. FastAPI added support for `Annotated` in version 0.95.0 and recommends it starting from 0.95.1. Older versions will produce errors when attempting to use `Annotated`.