Getting Started with the FastAPI Class
In this tutorial, you will build a fully configured FastAPI application instance. You will learn how to initialize the FastAPI class, customize its metadata for automatic documentation, and manage its lifecycle using the modern lifespan pattern.
By the end of this guide, you will have a production-ready application entry point that serves as the central hub for your routes, dependencies, and middleware.
Prerequisites
To follow this tutorial, you need the fastapi package installed in your environment. You will also need an ASGI server like uvicorn to run the application.
Step 1: Create the Minimal Application
The FastAPI class (found in fastapi/applications.py) is the main entry point for your project. It inherits from Starlette and provides the core functionality for your API.
Create a file named main.py and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
In this step, you instantiated the FastAPI class and assigned it to the variable app. This object is what the ASGI server (like Uvicorn) will use to communicate with your code. The @app.get("/") decorator uses the application instance to register a "path operation" that responds to HTTP GET requests at the root URL.
Step 2: Configure API Metadata
The FastAPI constructor accepts several parameters that define how your API is presented in the automatically generated OpenAPI schema and interactive documentation (Swagger UI).
Update your app instantiation with metadata:
from fastapi import FastAPI
app = FastAPI(
title="Inventory Manager",
summary="A simple API to manage warehouse stock.",
description="""
Inventory Manager API helps you track items and shipments. 🚀
## Items
You can **read items** and **update stock levels**.
""",
version="1.0.0",
contact={
"name": "Support Team",
"url": "http://example.com/contact/",
"email": "support@example.com",
},
license_info={
"name": "Apache 2.0",
"url": "https://www.apache.org/licenses/LICENSE-2.0.html",
},
)
By providing these arguments, you are configuring the title, summary, description, and version attributes of the FastAPI instance. These values are used by the openapi() method to generate the JSON schema that powers the /docs endpoint.
Step 3: Manage the Application Lifecycle
For tasks like connecting to a database on startup or cleaning up resources on shutdown, you should use the lifespan parameter. While FastAPI supports on_startup and on_shutdown parameters, they are deprecated in favor of the lifespan context manager.
Add a lifespan handler to your application:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Logic to run on startup
print("Connecting to database...")
yield
# Logic to run on shutdown
print("Disconnecting from database...")
app = FastAPI(lifespan=lifespan)
The lifespan function is an asynchronous context manager. Everything before the yield runs before the application starts receiving requests, and everything after the yield runs after the application finished handling requests.
Step 4: Customize Documentation Endpoints
By default, FastAPI serves the OpenAPI schema at /openapi.json, Swagger UI at /docs, and ReDoc at /redoc. You can change these paths or disable them entirely using the docs_url, redoc_url, and openapi_url parameters.
from fastapi import FastAPI
app = FastAPI(
openapi_url="/api/v1/openapi.json",
docs_url="/documentation",
redoc_url=None # This disables ReDoc
)
Setting openapi_url to None will automatically disable both /docs and /redoc, as they both depend on the OpenAPI schema to function.
Complete Working Result
Combining these steps, your main.py should look like this:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: Load resources
print("Application is starting up")
yield
# Shutdown: Clean up resources
print("Application is shutting down")
app = FastAPI(
title="Inventory Manager",
description="Manage your warehouse stock efficiently.",
version="1.0.0",
lifespan=lifespan,
docs_url="/api/docs",
redoc_url=None
)
@app.get("/")
async def root():
return {"status": "active"}
To run this application, use the following command in your terminal:
uvicorn main:app --reload
You can now visit http://127.0.0.1:8000/api/docs to see your customized documentation.
Next Steps
- Learn how to organize larger applications using
APIRouter. - Explore adding global
dependenciesto theFastAPIconstructor to apply logic to every route in your app. - Use
app.add_middleware()to handle cross-cutting concerns like CORS or GZip compression.