Backend & Languages

FastAPI Setup & Deployment Guide

Modern, fast Python API framework with automatic validation and OpenAPI docs – develop with fastapi dev, deploy with Uvicorn workers.

Updated Official documentation ↗

1. Introduction & use cases

FastAPI is a Python framework for building APIs with standard type hints. It validates request data with Pydantic, converts it to Python objects and generates interactive OpenAPI documentation (Swagger UI at /docs) automatically.

It is built on Starlette and the ASGI standard, so async endpoints can handle many concurrent requests – among the fastest Python frameworks. It runs on Uvicorn in development and production.

Where it is used

  • High-performance REST APIs and microservices
  • Serving machine-learning models
  • Back-ends for React/Next.js and mobile apps
  • Async integrations with other APIs and WebSockets

2. Prerequisites

You needVersion / notes
PythonA supported 3.x release (3.11 or newer recommended) – check with python3 --version
pip + venvIncluded with Python
BasicsPython type hints and async/await

3. Local setup

  1. 1Create the folder and venv

    Activate it before installing.

    BASH
    mkdir fastapi-app && cd fastapi-app
    python3 -m venv .venv
    source .venv/bin/activate   # Windows: .venv\Scripts\activate
  2. 2Install FastAPI

    fastapi[standard] includes Uvicorn and the fastapi CLI.

    BASH
    pip install "fastapi[standard]"
    pip freeze > requirements.txt

4. Create & run a project

  1. 1Create the API

    Pydantic models describe request and response bodies; FastAPI validates them automatically.

    main.py
    from fastapi import FastAPI, HTTPException
    from pydantic import BaseModel
    
    app = FastAPI(title="Items API")
    
    class ItemIn(BaseModel):
        name: str
        price: float
    
    class Item(ItemIn):
        id: int
    
    items: dict[int, Item] = {}
    
    @app.get("/health")
    async def health():
        return {"status": "ok"}
    
    @app.post("/items", response_model=Item, status_code=201)
    async def create_item(data: ItemIn):
        item = Item(id=len(items) + 1, **data.model_dump())
        items[item.id] = item
        return item
    
    @app.get("/items/{item_id}", response_model=Item)
    async def get_item(item_id: int):
        if item_id not in items:
            raise HTTPException(status_code=404, detail="Item not found")
        return items[item_id]
  2. 2Run in development

    Auto-reload is on. Open http://127.0.0.1:8000/docs to try every endpoint in the browser.

    BASH
    fastapi dev main.py
  3. 3Send a request

    Invalid data (e.g. a text price) returns a clear 422 error.

    BASH
    curl -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name":"Pen","price":25}'
  4. 4Load settings from .env

    Install pip install pydantic-settings; it reads environment variables with types.

    config.py
    from pydantic_settings import BaseSettings, SettingsConfigDict
    
    class Settings(BaseSettings):
        model_config = SettingsConfigDict(env_file=".env")
        database_url: str = "sqlite:///./app.db"
        secret_key: str
    
    settings = Settings()

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

With pydantic-settings, field names map to environment variables case-insensitively (secret_key ← SECRET_KEY). Missing required values stop the app at startup with a clear error.

.env
SECRET_KEY=generate-a-long-random-value
DATABASE_URL=postgresql://api:pass@localhost:5432/api
CORS_ORIGINS=http://localhost:5173

Key dependencies

Package / toolUsed for
fastapiFramework (Starlette + Pydantic)
uvicornASGI server (included in fastapi[standard])
pydantic / pydantic-settingsValidation and typed settings
sqlalchemy or sqlmodelDatabase access
httpxAsync HTTP client and test client
pytestTests with TestClient

Folder structure

project structure
fastapi-app/
├── app/
│   ├── main.py        # app = FastAPI()
│   ├── routers/       # APIRouter per resource
│   ├── models.py      # Pydantic / DB models
│   └── config.py      # Settings
├── tests/
├── .env
└── requirements.txt

Essential commands

CommandWhat it does
fastapi dev main.pyDevelopment server with reload + /docs
fastapi run main.pyProduction-style server (no reload)
uvicorn main:app --workers 4Several worker processes
pytestRun tests
curl localhost:8000/openapi.jsonDownload the OpenAPI schema

6. Production deployment

Server & hosting requirements

RequirementRecommendation
ServerUbuntu VPS, 1–2 GB RAM
App serverUvicorn with several workers (or Gunicorn + Uvicorn workers)
Web serverNginx reverse proxy
Domain + SSLDNS + Let’s Encrypt

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Python on the server

    Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.

    BASH
    sudo apt install -y python3 python3-venv python3-pip
    sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app
  3. 3Install the app

    Create the venv on the server.

    BASH
    git clone https://github.com/you/fastapi-app.git /srv/app && cd /srv/app
    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt
    nano .env
  4. 4Run it as a systemd service

    systemd starts the app on boot and restarts it on failure. Save the unit file, then enable it. Logs: journalctl -u fastapi-app -f.

    /etc/systemd/system/fastapi-app.service
    [Unit]
    Description=fastapi-app
    After=network.target
    
    [Service]
    User=deploy
    WorkingDirectory=/srv/app
    EnvironmentFile=/srv/app/.env
    ExecStart=/srv/app/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4 --proxy-headers
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
  5. 5Start and enable the service

    Reload systemd, start the service now and on every boot, and check that it is active (running).

    BASH
    sudo systemctl daemon-reload
    sudo systemctl enable --now fastapi-app
    sudo systemctl status fastapi-app
    journalctl -u fastapi-app -f
  6. 6Install Nginx as a reverse proxy

    Nginx receives requests on ports 80/443 and forwards them to your app on 127.0.0.1:8000. Replace example.com with your domain. The Upgrade headers in this config also make WebSocket endpoints work.

    /etc/nginx/sites-available/example.com
    server {
        listen 80;
        server_name example.com www.example.com;
    
        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_http_version 1.1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
    }
  7. 7Enable the site and reload Nginx

    Link the config into sites-enabled, test it and reload. nginx -t must say syntax is ok before you reload.

    BASH
    sudo apt install -y nginx
    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
  8. 8Open only the ports you need

    Allow SSH, HTTP and HTTPS through the firewall. Application ports (3000, 8000 …) stay closed to the internet – Nginx forwards traffic to them.

    BASH
    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'   # ports 80 and 443 (after installing Nginx)
    sudo ufw enable
    sudo ufw status
  9. 9Point your domain to the server

    In your domain registrar's DNS panel add an A record for @ (and www) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check with dig or an online DNS checker.

    OUTPUT
    # Type  Name  Value              TTL
    # A     @     203.0.113.10       3600
    # A     www   203.0.113.10       3600
    dig +short example.com
  10. 10Add free HTTPS with Let’s Encrypt

    Certbot gets a free SSL certificate, adds it to the Nginx config and redirects HTTP to HTTPS. Certificates renew automatically (a systemd timer runs twice a day); test renewal once with --dry-run.

    BASH
    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d example.com -d www.example.com
    sudo certbot renew --dry-run
  11. 11Optional: hide the docs in production

    Disable the public docs if the API is private.

    PYTHON
    app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ fastapi dev main.py FastAPI Starting development server 🚀 server Server started at http://127.0.0.1:8000 server Documentation at http://127.0.0.1:8000/docs tip Running in development mode, for production use: fastapi runINFO: Will watch for changes in these directories: ['/home/you/fastapi-app']INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO: Application startup complete.
Figure 1: terminal output of the sample FastAPI project (section 4).
1Endpoints +Pydantic2pip install onserver3Uvicorn workers:80004Nginx proxy5HTTPS API + /docs
Figure 2: production deployment flow (section 6).
fastapi-app/├── app/│ ├── main.py # app = FastAPI()│ ├── routers/ # APIRouter per resource│ ├── models.py # Pydantic / DB models│ └── config.py # Settings├── tests/├── .env└── requirements.txt
Figure 3: project folder structure (section 5).

8. Common errors & solutions

422 Unprocessable Entity

The request body or parameters do not match the Pydantic model. The response detail lists the exact field and problem.

Error loading ASGI app. Could not import module "main"

Run the command from the folder containing main.py, or use the dotted path (app.main:app).

CORS errors from the browser

Add CORSMiddleware with your front-end origins.

PYTHON
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(CORSMiddleware, allow_origins=["https://example.com"], allow_methods=["*"], allow_headers=["*"])
Server is slow under load

A blocking call (sync DB driver, requests, time.sleep) inside an async def blocks the event loop. Use async libraries or declare the endpoint with plain def so it runs in a thread pool.

Redirect URLs use http behind Nginx

Start Uvicorn with --proxy-headers (and --forwarded-allow-ips if Nginx is on another host).

Best practices

  • Use response_model to control exactly what is returned.
  • Split routes with APIRouter and dependencies (Depends) for auth and DB sessions.
  • Never block the event loop inside async def.
  • Test with TestClient/httpx in CI.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.