Skip to main content

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.
  • Tools: It is recommended to use uv or pip for package management.

Installation

The recommended way to install FastAPI is with the standard extra, which includes a production-ready server (Uvicorn) and the fastapi CLI.

Using uv (recommended):

uv add "fastapi[standard]"

Using pip:

pip install "fastapi[standard]"

Hello World / Quick Start

Create a file named main.py:

from fastapi import FastAPI

# Create the FastAPI application instance
app = FastAPI()

# Define a path operation for the root URL
@app.get("/")
async def read_root():
"""
A simple GET endpoint that returns a JSON response.
"""
return {"Hello": "World"}

# Define a path operation with a path parameter
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
"""
An endpoint that takes a path parameter 'item_id' and an optional query parameter 'q'.
"""
return {"item_id": item_id, "q": q}

Run the server

Start the development server using the fastapi CLI:

fastapi dev main.py

The server will start at http://127.0.0.1:8000.

Verify Installation

  1. Open your browser at http://127.0.0.1:8000. You should see:
    {"Hello": "World"}
  2. Interactive API Docs: Go to http://127.0.0.1:8000/docs. You will see the automatic interactive API documentation provided by Swagger UI.
  3. Alternative API Docs: Go to http://127.0.0.1:8000/redoc. You will see the automatic documentation provided by ReDoc.

Usage Patterns

Modularity with APIRouter

For larger applications, use APIRouter to organize your code into multiple files:

from fastapi import APIRouter

router = APIRouter()

@router.get("/users/", tags=["users"])
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]

Then include it in your main app:

from fastapi import FastAPI
from .routers import users

app = FastAPI()
app.include_router(users.router)

Dependency Injection

FastAPI has a powerful Dependency Injection system using Depends:

from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons

Next Steps

  • Getting Started for a comprehensive walkthrough of all features.
  • Deployment for instructions on how to deploy your FastAPI application to production.
  • Advanced User Guide for complex use cases like custom middleware and security.