FastAPI Application Instance: Your API's Central Hub

The FastAPI instance is your API's central switchboard, connecting incoming requests to your code. You create it once (e.g., `app = FastAPI()`) and use its decorators like `@app.get` to define all your endpoints. The footgun is creating multiple instances.
WHY IT EXISTS: Web frameworks need a central point to manage configuration, routing, and lifecycle events. The FastAPI instance provides this single, authoritative object to orchestrate the entire application, from handling incoming requests to managing startup and shutdown procedures.
THE MENTAL MODEL: Think of the FastAPI instance as the general manager of your API service. All incoming requests (phone calls) are routed through this manager. It knows which department (a path operation function) should handle each request based on its path and method. It also manages shared resources and startup/shutdown procedures for the whole office.
HOW IT WORKS: You create an instance by importing the FastAPI class and calling it: from fastapi import FastAPI; app = FastAPI(). This app object then serves as the entry point for defining your API. You use its methods as decorators (@app.get, @app.post, etc.) to associate Python functions with specific URL paths and HTTP methods. The instance gathers all this routing information and uses it to handle incoming web requests, generate API documentation, and manage middleware.
WHEN TO USE IT: You use it in every FastAPI application; it's the foundational first step after your imports. You create one instance at the top level of your main application file (e.g., main.py). This single instance is then used to declare all your path operations, middleware, and event handlers.
WHEN NOT TO USE IT: You generally avoid creating multiple FastAPI instances within the same logical application. While you can "mount" sub-applications (which are themselves FastAPI instances), a beginner should stick to a single instance for the entire project to avoid complexity. To organize a large project, use APIRouter to split routes into different files, which then get included into the main app instance.
ONE CANONICAL EXAMPLE: from fastapi import FastAPI Step 1: Create the FastAPI instance app = FastAPI() Step 2: Use the instance to define a route @app.get("/") def read_root(): return {"Hello": "World"}
In this code, app is the FastAPI instance. The @app.get("/") decorator registers the read_root function to handle GET requests to the root path.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.