FastAPI class main attributes and methods
The FastAPI class has the following attributes and methods: openapi_version, webhooks, state, dependency_overrides, openapi, websocket, include_router, frontend, get, put, post, delete, options, head, patch, trace, on_event, middleware, and exception_handler.
FastAPI class import
The FastAPI class can be imported directly from the fastapi module using: from fastapi import FastAPI
OpenAPI documentation endpoints defaults
FastAPI provides automatic UI documentation at default endpoints: Swagger UI is available at /docs and ReDoc is available at /redoc. These are OpenAPI automatic UI documentation tools.
OpenAPI docs module functions
The fastapi.openapi.docs module provides the following utility functions: get_swagger_ui_html, get_redoc_html, get_swagger_ui_oauth2_redirect_html, and swagger_ui_default_parameters.
OpenAPI models module
FastAPI provides OpenAPI Pydantic models used to generate and validate the generated OpenAPI schema. These models are available in the fastapi.openapi.models module.
Request class import
The Request class can be imported directly from fastapi using 'from fastapi import Request'.
Request parameter in path operation function
You can declare a parameter in a path operation function or dependency to be of type Request and access the raw request object directly without any validation.
Body parameter class
Body() is a special parameter class for extracting the request body from the request.
Request parameter classes available in FastAPI
FastAPI provides special parameter classes that can be used in path operation function parameters or dependency functions with Annotated to get data from the request. These classes are: Query, Path, Body, Cookie, Header, Form, and File. They can all be imported directly from fastapi.
Import request parameter classes
Request parameter classes can be imported with: from fastapi import Body, Cookie, File, Form, Header, Path, Query
Query parameter class
Query() is a special parameter class for extracting query parameters from the request.
Path parameter class
Path() is a special parameter class for extracting path parameters from the request.
Cookie parameter class
Cookie() is a special parameter class for extracting cookie data from the request.
Header parameter class
Header() is a special parameter class for extracting header data from the request.
Form parameter class
Form() is a special parameter class for extracting form data from the request.
File parameter class
File() is a special parameter class for extracting file uploads from the request.
Response class instantiation and return
You can create an instance of the Response class directly and return it from your path operations.
Import Response class
The Response class can be imported directly from the fastapi module using `from fastapi import Response`.
Response parameter in path operation functions
You can declare a parameter in a path operation function or dependency to be of type Response. This allows you to set data for the response such as headers or cookies.
Response classes importable from fastapi.responses
The following response classes can be imported directly from fastapi.responses: FileResponse, HTMLResponse, JSONResponse, ORJSONResponse, PlainTextResponse, RedirectResponse, Response, StreamingResponse, and UJSONResponse.
ORJSONResponse members
ORJSONResponse has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
FileResponse members
FileResponse has the following members: chunk_size, charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
HTMLResponse members
HTMLResponse has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
JSONResponse members
JSONResponse has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
PlainTextResponse members
PlainTextResponse has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
Response members
Response has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
RedirectResponse members
RedirectResponse has the following members: charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
StreamingResponse members
StreamingResponse has the following members: body_iterator, charset, status_code, media_type, body, background, raw_headers, render, init_headers, headers, set_cookie, delete_cookie.
Custom FastAPI JSON response classes are deprecated
UJSONResponse and ORJSONResponse were intended to optimize JSON performance but are now deprecated. Better performance is achieved by using a Response Model with return type annotations, which allows Pydantic to serialize data into JSON bytes on the Rust side.
Stream Server-Sent Events with EventSourceResponse
To stream Server-Sent Events (SSE), use yield in your path operation function and set response_class=EventSourceResponse.
Import EventSourceResponse and ServerSentEvent
EventSourceResponse and ServerSentEvent can be imported directly from fastapi.sse.
Use ServerSentEvent objects for SSE fields
If you need to set SSE fields like event, id, retry, or comment, you can yield ServerSentEvent objects instead of plain data.
Import StaticFiles from fastapi.staticfiles
The StaticFiles class can be imported directly from fastapi.staticfiles using: from fastapi.staticfiles import StaticFiles
StaticFiles class serves static files
The StaticFiles class from FastAPI is used to serve static files such as JavaScript, CSS, images, and other static assets.
Status code constants naming convention
Status codes in the status module are named constants prefixed with 'HTTP_' followed by the numeric code and descriptive text. For example, HTTP_200_OK represents status code 200, and HTTP_403_FORBIDDEN represents status code 403.
Using status codes with status_code parameter
The status module can be used to specify the HTTP status code for a route using the status_code parameter in the route decorator. Example: @app.get("/items/", status_code=status.HTTP_418_IM_A_TEAPOT)
Status module supports HTTP and WebSocket codes
The status module contains named constants for both HTTP and WebSocket status codes, allowing convenient access with autocompletion rather than memorizing integer values.
Importing status module from FastAPI
The status module can be imported from FastAPI using: from fastapi import status. The status module is provided directly by Starlette and contains named constants with integer HTTP status codes.
UploadFile import
UploadFile can be imported directly from the fastapi module using 'from fastapi import UploadFile'.
UploadFile class members
UploadFile has the following members: file, filename, size, headers, content_type, read, write, seek, and close.
UploadFile parameter for file reception
Path operation function parameters can be defined with the type UploadFile to receive files from the request.
FastAPI CLI automatic app detection
The fastapi CLI automatically detects the FastAPI app to run, assuming it is an object called 'app' in a file called 'main.py', with support for a couple of other variants.
fastapi dev command for development
The `fastapi dev` command starts a FastAPI application in development mode with auto-reload enabled by default. Auto-reload automatically reloads the server when you make changes to code. The server listens on 127.0.0.1 (localhost). The `fastapi dev` command sets the FASTAPI_ENV environment variable to 'development' before importing the app, preserving any existing value if already set.
fastapi run command for production
The `fastapi run` command starts a FastAPI application in production mode. Auto-reload is disabled by default. The server listens on 0.0.0.0, which means all available IP addresses, making it publicly accessible. The fastapi run command does not automatically set FASTAPI_ENV, so it should be set explicitly if the app needs to detect production mode.
Configure app entrypoint in pyproject.toml
The app entrypoint can be configured in a pyproject.toml file under [tool.fastapi] section with the key 'entrypoint'. The entrypoint value is specified as a string in the format 'module:app', for example 'main:app' or 'backend.main:app'. This tells the fastapi command which module and app object to import and use.
fastapi dev with --entrypoint option
You can pass the --entrypoint option to the `fastapi dev` command to specify the app location, for example: `fastapi dev --entrypoint main:app`. You can also pass a file path directly: `fastapi dev main.py`. However, configuring the entrypoint in pyproject.toml is recommended because other tools like VS Code Extension and FastAPI Cloud can find it there.
FastAPI CLI uses Uvicorn internally
The FastAPI CLI internally uses Uvicorn, which is a high-performance, production-ready ASGI server.
FASTAPI_ENV environment variable conventions
The conventional FASTAPI_ENV values are 'development' and 'production'. The `fastapi dev` command sets FASTAPI_ENV to 'development' before importing the app. The `fastapi run` command leaves FASTAPI_ENV unchanged.
Auto-reload behavior difference between dev and run
Auto-reload is enabled by default in `fastapi dev` and disabled by default in `fastapi run`. Auto-reload in development mode is resource-intensive and can be less stable, so it should only be used for development.
Default server addresses for dev and run modes
In `fastapi dev`, the server listens on 127.0.0.1 (localhost), which only allows communication from the same machine. In `fastapi run`, the server listens on 0.0.0.0, which listens on all available IP addresses and is publicly accessible to anyone that can communicate with the machine.
responses parameter for path operations
Path operation decorators accept a 'responses' parameter that takes a dictionary. The keys are HTTP status codes (such as 200 or 404) and the values are dictionaries containing information for each response. Each response dictionary can contain a 'model' key with a Pydantic model, similar to response_model.
Additional response with model parameter
To declare an additional response with a status code like 404 and a Pydantic model, pass a responses parameter to the path operation decorator with the status code as key and a dictionary containing a 'model' key as value. FastAPI will generate the JSON schema from the Pydantic model and include it in the OpenAPI schema at the correct location under the 'schema' key within 'content' -> media type.
Must return Response directly for additional responses
When using additional responses in the responses parameter, you must return a Response object directly (such as JSONResponse) with your desired status code and content. FastAPI will not automatically handle the response; you are responsible for returning it explicitly.
model key in responses is not part of OpenAPI
The 'model' key in responses dictionaries is not part of the OpenAPI specification. FastAPI uses it to extract the Pydantic model, generate its JSON schema, and insert a reference to it in the appropriate location in the OpenAPI schema (under components/schemas) rather than embedding it inline. This allows other applications and clients to use the JSON schemas directly and provide better code generation tools.
Additional media types for main response
Use the 'responses' parameter to add different media types for the same main response. For example, you can declare that a path operation returns either JSON (application/json) or a PNG image (image/png). When returning an image, use FileResponse directly.
Default media type behavior in responses parameter
If you do not explicitly specify a media type in the 'responses' parameter, FastAPI assumes the response has the same media type as the main response class (default is application/json). If you specified a custom response class with None as the media type, FastAPI uses application/json for any additional responses that have an associated model.
Combining response_model status_code and responses
You can combine information from response_model, status_code, and responses parameters. Declare response_model with the default status code 200 (or custom status code) and then add additional information for the same or different responses in the responses parameter. FastAPI will combine the additional information from responses with the JSON schema from your model.
Custom descriptions and examples in responses
In the responses parameter dictionary values, you can include custom 'description' and 'example' fields. FastAPI will combine these with the JSON schema generated from the Pydantic model and include them in the OpenAPI schema.
Reusing predefined responses with dict unpacking
To combine predefined responses that apply to multiple path operations with custom responses for each operation, use Python's dict unpacking syntax with **dict_to_unpack. This allows you to include all key-value pairs from a predefined responses dictionary while adding or overriding specific responses in individual path operations.
OpenAPI Response Object specification
The OpenAPI specification for Response Objects allows you to include 'description', 'headers', 'content' (where you declare different media types and JSON schemas), and 'links' fields directly in each response within the responses parameter.