Skip to content

02 Installation Setup

DodaTech 4 min read

title: FastAPI Installation and Project Setup weight: 12 date: 2026-06-28 lastmod: 2026-06-28 description: Install FastAPI, uvicorn, and Pydantic with virtual environment setup, project structure, and configuration for REST API development in Python. tags: [api-development, fastapi]


FastAPI installation uses pip with a virtual environment, installing FastAPI, uvicorn (ASGI server), and optional dependencies like SQLAlchemy, databases, and Jinja2 for a complete REST API development setup.

```mermaid
flowchart TD
  A[Installation] --> B[python -m venv venv]
  B --> C[pip install fastapi uvicorn]
  C --> D[Project Structure]
  D --> E[main.py]
  D --> F[routes/]
  D --> G[schemas/]
  D --> H[models/]
  A --> I[Optional Deps]
  I --> J[sqlalchemy, databases]
  I --> K[pytest, httpx]
  style A fill:#e1f5fe
  style B fill:#f3e5f5
  style D fill:#c8e6c9

Create a virtual environment, install FastAPI and uvicorn, then set up a project structure with main.py, routes, schemas (Pydantic), models (SQLAlchemy), and configuration. Use the --reload flag during development for automatic restarts.

Think of the setup like preparing a workshop. The virtual environment is your clean workspace (isolated from other projects). FastAPI is your workbench (framework). Uvicorn is the power switch (server). The project structure is your tool organization system.

Example: Installation Commands

# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install FastAPI with all optional dependencies
pip install "fastapi[all]"

# Or install minimal
pip install fastapi uvicorn pydantic

# Optional dependencies
pip install sqlalchemy databases asyncpg
pip install pytest httpx
pip install python-multipart  # For file uploads
pip install redis aioredis     # For caching

# Verify installation
python -c "import fastapi; print(fastapi.__version__)"

Expected output:

0.115.0

Example: Recommended Project Structure

fastapi-api/
├── app/
│   ├── __init__.py
│   ├── main.py              # FastAPI app creation
│   ├── config.py            # Settings class
│   ├── database.py          # Database connection
│   ├── dependencies.py      # Dependency injection
│   ├── routes/
│   │   ├── __init__.py
│   │   ├── users.py
│   │   └── items.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   ├── user.py          # Pydantic models
│   │   └── item.py
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py          # SQLAlchemy models
│   ├── services/
│   │   ├── __init__.py
│   │   └── user_service.py
│   └── utils/
│       ├── __init__.py
│       └── security.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py
│   └── test_users.py
├── .env
├── .gitignore
└── requirements.txt

Example: Main Application Setup

# app/main.py
from fastapi import FastAPI
from app.config import settings
from app.routes import users, items
from app.database import engine, Base

# Create database tables
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title=settings.APP_NAME,
    description="REST API built with FastAPI",
    version="1.0.0",
    docs_url="/docs" if settings.DEBUG else None,
    redoc_url="/redoc" if settings.DEBUG else None
)

# Include routers
app.include_router(users.router, prefix="/api/users", tags=["Users"])
app.include_router(items.router, prefix="/api/items", tags=["Items"])

@app.get("/api/health")
def health_check():
    return {"status": "ok", "version": "1.0.0"}

Example: Configuration Management

# app/config.py
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    APP_NAME: str = "FastAPI API"
    DEBUG: bool = True
    DATABASE_URL: str = "sqlite:///./test.db"
    SECRET_KEY: str = "change-this-in-production"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    CORS_ORIGINS: list = ["http://localhost:3000"]

    class Config:
        env_file = ".env"

settings = Settings()

# Run with: uvicorn app.main:app --reload

Expected output:

$ uvicorn app.main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000
INFO:     Started reloader process [12345] using StatReload
INFO:     Started server process [12346]
INFO:     Waiting for application startup.

Common Mistakes

  1. Installing without a virtual environment — Installing FastAPI globally pollutes the system Python and causes version conflicts between projects.
  2. Running main.py directly — FastAPI requires an ASGI server. Run with uvicorn, not python main.py.
  3. Forgetting to activate the virtual environment — Running uvicorn without activating the venv uses the system Python, which may not have FastAPI installed.
  4. Putting all code in main.py — A single file becomes unmanageable. Use the recommended structure with separate modules for routes, schemas, and models.
  5. Not using a .env file — Hard-coding configuration makes the app insecure and non-portable. Use Pydantic Settings to load from .env.

Practice Questions

  1. What ASGI server is required to run FastAPI applications?
  2. What is the purpose of a virtual environment?
  3. How do you organize routes in a FastAPI project?
  4. What is the Pydantic Settings class used for?
  5. Challenge: Set up a complete FastAPI project with the recommended structure. Include a configuration module using Pydantic Settings, two route modules (users and products), and a health check endpoint. Run with uvicorn --reload.

FAQ

What is the difference between pip install fastapi and fastapi[all]?

fastapi[all] installs optional dependencies like uvicorn, pydantic, python-multipart, and jinja2. Install minimal dependencies for production and add only what you need.

Should I use SQLite or PostgreSQL with FastAPI?

Use SQLite for development and testing. Use PostgreSQL for production. FastAPI supports both through SQLAlchemy and async drivers.

How do I structure a large FastAPI application?

Use APIRouter for modular routes, separate schemas (Pydantic) from models (SQLAlchemy), use dependency injection for shared logic, and organize by feature not by layer.

Do I need uvicorn or can I use gunicorn?

Use uvicorn directly for development. For production, run uvicorn workers under gunicorn: gunicorn -k uvicorn.workers.UvicornWorker app.main:app.

How do I reload on file changes?

Use the --reload flag: uvicorn app.main:app --reload. This watches for file changes and restarts automatically.

Mini Project

Set up a complete FastAPI project from scratch with virtual environment, project structure (routes, schemas, config), Pydantic Settings with .env file, a health check endpoint, and two additional route modules (users and items). Run with uvicorn and verify at /docs.

What's Next

Now learn about path operations in Building REST APIs with FastAPI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro