Getting Started
FastAPI is a modern, high-performance web framework for building APIs with Python, based on standard Python type hints. It is designed to be easy to use, fast to code, and ready for production.
Prerequisites
- Python: Version 3.10 or higher is required.
- Virtual Environment: It is highly recommended to use a virtual environment (e.g.,
venv,uv, orpdm) to manage your dependencies.
Installation
The recommended way to install FastAPI is with the standard group of optional dependencies, which includes a high-performance ASGI server (uvicorn) and the FastAPI CLI.
pip install "fastapi[standard]"
If you prefer a minimal installation without the CLI and extra dependencies, you can use:
pip install fastapi
Quick Start
1. Create your application
Create a file named main.py and add the following code:
from fastapi import FastAPI
# Initialize the FastAPI application
app = FastAPI()
@app.get("/")
async def read_root():
"""
A simple GET endpoint that returns a JSON response.
"""
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
"""
An endpoint with path and query parameters.
FastAPI automatically validates that item_id is an integer.
"""
return {"item_id": item_id, "q": q}
2. Run the development server
Use the fastapi dev command to start the server with auto-reload enabled:
fastapi dev main.py
The server will start at http://127.0.0.1:8000.
3. Interactive API Documentation
FastAPI automatically generates interactive documentation for your API. Once the server is running, you can access:
- Swagger UI: http://127.0.0.1:8000/docs — allows you to test your API directly from the browser.
- ReDoc: http://127.0.0.1:8000/redoc — provides a clean, alternative documentation view.
Usage with Pydantic
FastAPI uses Data Schemas and Validation for data validation and serialization. You can define complex request bodies using Python classes:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
Verify Installation
To confirm that FastAPI and its CLI are correctly installed, run:
fastapi --version
Other Install Options
Using uv (Recommended)
If you use the uv package manager, you can install FastAPI and run it immediately:
uv add "fastapi[standard]"
uv run fastapi dev main.py
Production Deployment
For production, use the fastapi run command, which optimizes the server configuration:
fastapi run main.py
Next Steps
- Explore the tutorial to learn about dependency injection, security, and more.
- Learn how to structure Bigger Applications using
APIRouter. - Check out the deployment guide for hosting your API on various platforms.