Skip to content
Search

FastAPI

lastmod 2026-06-10created 2021-06-1029 edits

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python3.6+ based on standard Python type hints.

Categories

  • Tutorial - User Guide
    • FastAPI:FirstSteps
    • FastAPI:PathParameters
    • FastAPI:QueryParameters
    • FastAPI:RequestBody
    • FastAPI:QueryParameters and String Validations
    • FastAPI:PathParameters and Numeric Validations
    • FastAPI:Body:MultipleParameters
    • FastAPI:Body:Fields
    • FastAPI:Body:NestedModels
    • FastAPI:DeclareRequestExampleData
    • FastAPI:ExtraDataTypes
    • FastAPI:CookieParameters
    • FastAPI:HeaderParameters
    • FastAPI:ResponseModel:ReturnType
    • FastAPI:ExtraModels
    • FastAPI:ResponseStatusCode
    • FastAPI:FormData
    • FastAPI:RequestFiles
    • FastAPI:RequestForms
    • FastAPI:HandlingErrors
    • FastAPI:PathOperationConfiguration
    • FastAPI:JSONCompatibleEncoder
    • FastAPI:Body:Updates
    • FastAPI:Dependencies
      • Classes as Dependencies
      • Sub-dependencies
      • Dependencies in path operation decorators
      • Global Dependencies
      • Dependencies with yield
    • FastAPI:Security
      • Security - First Steps
      • Get Current User
      • Simple OAuth2 with Password and Bearer
      • OAuth2 with Password (and hashing), Bearer with JWT tokens
    • FastAPI:Middleware
    • FastAPI:CORS
    • FastAPI:SQLDatabases
    • FastAPI:BiggerApplications - Multiple Files
    • FastAPI:BackgroundTasks
    • FastAPI:Metadata
    • FastAPI:StaticFiles
    • FastAPI:Testing
    • FastAPI:Debugging
  • Advanced User Guide
    • FastAPI:PathOperationAdvancedConfiguration
    • FastAPI:AdditionalStatusCodes
    • FastAPI:ReturnResponseDirectly
    • FastAPI:CustomResponse - HTML, Stream, File, others
    • FastAPI:AdditionalResponsesInOpenAPI
    • FastAPI:ResponseCookies
    • FastAPI:ResponseHeaders
    • FastAPI:Response:ChangeStatusCode
    • FastAPI:AdvancedDependencies
    • FastAPI:AdvancedSecurity
      • OAuth2 scopes
      • HTTP Basic Auth
    • FastAPI:UsingTheRequestDirectly
    • FastAPI:UsingDataclasses
    • FastAPI:AdvancedMiddleware
    • FastAPI:SQL (Relational) Databases with Peewee
    • FastAPI:AsyncSQL (Relational) Databases
    • FastAPI:NoSQL (Distributed / Big Data) Databases
    • FastAPI:SubApplications - Mounts
    • FastAPI:BehindProxy
    • FastAPI:Templates
    • FastAPI:GraphQL
    • FastAPI:WebSockets
    • FastAPI:LifespanEvents - Lifespan events
    • FastAPI:CustomRequestAndAPIRouteClass
    • FastAPI:TestingWebSockets
    • FastAPI:TestingEvents: startup - shutdown
    • FastAPI:TestingDependenciesWithOverrides
    • FastAPI:TestingDatabase
    • FastAPI:AsyncTests
    • FastAPI:SettingsAndEnvironmentVariables
    • FastAPI:ConditionalOpenAPI
    • FastAPI:ExtendingOpenAPI
    • FastAPI:OpenAPICallbacks
    • FastAPI:OpenAPIWebhooks
    • FastAPI:IncludingWSGI - Flask, Django, others
    • FastAPI:GenerateClients
  • FastAPI:Deployment

Optional dependencies

Used by Pydantic:

  • email_validator - for email validation.

Used by Starlette:

  • HTTPX - Required if you want to use the TestClient.
  • jinja2 - Required if you want to use the default template configuration.
  • python-multipart - Required if you want to support form "parsing" with request.form().
  • itsdangerous - Required for SessionMiddleware support.
  • pyyaml - Required for Starlette's SchemaGenerator support (you probably don't need it with FastAPI).
  • graphene - Required for GraphQLApp support.
  • ujson - Required if you want to use UJSONResponse.

Used by FastAPI / Starlette:

  • uvicorn - for the server that loads and serves your application.
  • orjson - Required if you want to use ORJSONResponse.

You can install all of these with pip install fastapi[all].

Features

  • Python-based: Starlette, Pydantic, Uvicorn
    • Performance on par with Node and Go
  • Fast and easy development. Short code. Great reusability
  • Production Ready
  • Based on standards such as OpenAPI (Swagger) and JSON Schema
  • Great editor support (code autocompletion)
  • Supports asynchronous APIs and data validation

Running programmatically

See Uvicorn#Running programmatically:

import uvicorn
from fastapi import FastAPI  # type: ignore

certfile = "..."
keyfile = "..."

app = FastAPI()

# ...

if __name__ == "__main__":
    uvicorn.run(app, port=5000, log_level="info", ssl_certfile=certfile, ssl_keyfile=keyfile)

Class method routing

Use FastAPI:APIRouter#add_api_route.

In short:

from fastapi import FastAPI, APIRouter


class Hello:

    def __init__(self, name: str):
        self.name = name
        self.router = APIRouter()
        self.router.add_api_route("/hello", self.hello, methods=["GET"])

    def hello(self):
        return {"Hello": self.name}


app = FastAPI()
hello = Hello("World")
app.include_router(hello.router)

Request Validation and Serialization

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    # Access validated and deserialized item properties
    item_name = item.name
    item_price = item.price
    # ...

Cross-Origin Resource Sharing (CORS)

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Configure CORS settings
origins = [
    "http://localhost",
    "http://localhost:3000",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Authentication and Authorization

from fastapi import FastAPI
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")

@app.get("/items/")
async def get_items(token: str = Depends(oauth2_scheme)):
    # Validate and verify the token
    # Perform authorization checks
    # ...

Hiding the healthcheck access log

import logging
import uvicorn
from fastapi import FastAPI

app = FastAPI()

# Define the filter
class EndpointFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        return record.args and len(record.args) >= 3 and record.args[2] != "/health"

# Add filter to the logger
logging.getLogger("uvicorn.access").addFilter(EndpointFilter())

# Define the API endpoints
@app.get('/health')
def health():
    print('health endpoint')

@app.get('/test')
def test():
    print('test endpoint')

Graceful shutdown

The key libraries to achieve graceful shutting down to a Uvicorn server running a FastAPI application are the built in os and signal modules. Given an endpoint with which a client can request the server to shutdown.

os.kill(os.getpid(), signal.SIGTERM)

FastAPI example:

import os
import signal
import fastapi
import uvicorn

from fastapi.responses import JSONResponse

app = fastapi.FastAPI()

def hello():
    return fastapi.Response(status_code=200, content='Hello, world!')

def shutdown():
    os.kill(os.getpid(), signal.SIGTERM)
    return fastapi.Response(status_code=200, content='Server shutting down...')

@app.on_event('shutdown')
def on_shutdown():
    print('Server shutting down...')

app.add_api_route('/hello', hello, methods=['GET'])
app.add_api_route('/shutdown', shutdown, methods=['GET'])

if __name__ == '__main__':
    uvicorn.run(app, host='localhost', port=8000)

What makes FastAPI better than Flask?

WARNING

Needs verification.

  • A framework that makes up for the drawbacks of Flask, which was mainly used for Python web application development
  • Thanks to its DI-centered design, bugs are less likely, and productivity and performance are high
  • Summarizes how each Flask component can be replaced in FastAPI
  • Performance aside, good official documentation and powerful convenience features such as framework-level OpenAPI Specification are also advantages
  • Explains, along with the history of Python, why Flask could not do this and why Sanic, a similar framework, never became popular

Performance Tips

Various performance optimization tips

  • Depending on the situation, gc can be a bottleneck. In that case, you can tune the conditions that trigger gc.
  • The built-in list is not fast enough. Use array or numpy when needed.
  • multiprocess has high communication overhead, so use it carefully in low-latency scenarios.
  • If you use Pytorch in a multiprocess environment, adjust num_threads.
  • Pydantic is very slow. Avoid it where it isn't needed.
  • Pandas DataFrames take a long time to create, so use them with care.
  • The vanilla json package is slow. Use orjson or ujson.
  • Classes may not be fast enough. If it becomes too much of a problem, use dict.
  • Python 3.11 is less slow.
  • (Bonus) How to use line profiler

Troubleshooting

422 Unprocessable Entity

Indicates that the server understands the "content type" of the request entity, and the syntax of the request entity is correct, but it was unable to process the requested instructions.

In other words, double-check the Content-Type header.

307 Temporary Redirect

Remove the / suffix from the routing path.

See also

Favorite site

author Zer0 sitemap