FastAPI Core Architecture and Implementation
FastAPI Project Architecture
The Application Entry Point
Every FastAPI project begins with an instance of the FastAPI class. This object is the central point of your entire application. You'll use it to define routes, add middleware, and configure settings. The standard convention is to create this instance in a file named main.py and call the variable app.
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
This simple setup creates an application with a single endpoint that responds to GET requests at the root URL (/). While this works for basic examples, production applications almost always need to manage resources, like database connections or machine learning models, that must be initialized before the app starts accepting requests and cleaned up when it shuts down.
Managing Lifespan Events
To handle setup and teardown tasks, FastAPI provides a modern and robust mechanism called the lifespan protocol. This is the recommended way to manage resources that have a lifetime tied to the application itself. It replaces older, legacy event handlers (@app.on_event("startup")) because it offers better support for asynchronous code, improved type safety, and more explicit error handling.
The lifespan argument accepts an that handles both startup and shutdown logic in a single, clean function. Everything before the yield statement runs on startup. The application then runs and handles requests. Once the application is shutting down, the code after the yield statement is executed for cleanup.
Let's see how to implement this. We'll create a dummy 'database' (a simple dictionary) that gets initialized on startup and 'cleared' on shutdown.
# main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
# A dummy "database" dictionary
fake_items_db = {"items": []}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Code to run on startup
print("Application startup...")
fake_items_db["items"].append("Initial item")
yield
# Code to run on shutdown
print("Application shutdown...")
fake_items_db.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/items/")
async def read_items():
return fake_items_db
In this example, when the application starts, it prints a message and adds an item to our fake_items_db. The yield keyword then passes control to the application, which is now ready to serve requests. When the server is stopped (e.g., with Ctrl+C), the code after yield executes, printing a shutdown message and clearing the dictionary. This ensures resources are never left dangling.
Running Your Application
FastAPI itself is a web framework, not a web server. To run your application, you need an ASGI server like Uvicorn. ASGI (Asynchronous Server Gateway Interface) is the standard interface between async-capable Python web servers, frameworks, and applications.
# In your terminal
uvicorn main:app --reload
This command tells to run the application.
main: The Python file where your FastAPI instance lives (main.py).app: The variable name of your FastAPI instance insidemain.py.--reload: A development flag that automatically restarts the server whenever you save changes to your code.
When you run the server, you'll see the "Application startup..." message in your terminal. If you access http://127.0.0.1:8000/items/ in your browser, you'll see the initial item. When you stop the server, the "Application shutdown..." message will appear as the cleanup logic executes.
What is the recommended mechanism in modern FastAPI for managing application startup and shutdown events, such as initializing a database connection?
In a lifespan function like the one below, which part of the code is executed when the application shuts down?
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
# Code block 1
print("Startup logic runs here")
db_connection = connect_to_db()
yield
# Code block 2
print("Shutdown logic runs here")
db_connection.close()
This structured approach to application lifespan management is fundamental for building robust, production-ready services with FastAPI.