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 need | Version / notes |
|---|---|
| Python | A supported 3.x release (3.11 or newer recommended) – check with python3 --version |
| pip + venv | Included with Python |
| Basics | Python type hints and async/await |
3. Local setup
1Create the folder and venv
Activate it before installing.
BASHmkdir fastapi-app && cd fastapi-app python3 -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate2Install FastAPI
fastapi[standard]includes Uvicorn and thefastapiCLI.BASHpip install "fastapi[standard]" pip freeze > requirements.txt
4. Create & run a project
1Create the API
Pydantic models describe request and response bodies; FastAPI validates them automatically.
main.pyfrom 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]2Run in development
Auto-reload is on. Open http://127.0.0.1:8000/docs to try every endpoint in the browser.
BASHfastapi dev main.py3Send a request
Invalid data (e.g. a text price) returns a clear 422 error.
BASHcurl -X POST http://127.0.0.1:8000/items -H "Content-Type: application/json" -d '{"name":"Pen","price":25}'4Load settings from .env
Install
pip install pydantic-settings; it reads environment variables with types.config.pyfrom 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.
SECRET_KEY=generate-a-long-random-value
DATABASE_URL=postgresql://api:pass@localhost:5432/api
CORS_ORIGINS=http://localhost:5173Key dependencies
| Package / tool | Used for |
|---|---|
fastapi | Framework (Starlette + Pydantic) |
uvicorn | ASGI server (included in fastapi[standard]) |
pydantic / pydantic-settings | Validation and typed settings |
sqlalchemy or sqlmodel | Database access |
httpx | Async HTTP client and test client |
pytest | Tests with TestClient |
Folder structure
fastapi-app/
├── app/
│ ├── main.py # app = FastAPI()
│ ├── routers/ # APIRouter per resource
│ ├── models.py # Pydantic / DB models
│ └── config.py # Settings
├── tests/
├── .env
└── requirements.txtEssential commands
| Command | What it does |
|---|---|
fastapi dev main.py | Development server with reload + /docs |
fastapi run main.py | Production-style server (no reload) |
uvicorn main:app --workers 4 | Several worker processes |
pytest | Run tests |
curl localhost:8000/openapi.json | Download the OpenAPI schema |
6. Production deployment
Server & hosting requirements
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu VPS, 1–2 GB RAM |
| App server | Uvicorn with several workers (or Gunicorn + Uvicorn workers) |
| Web server | Nginx reverse proxy |
| Domain + SSL | DNS + Let’s Encrypt |
Deployment steps
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.
BASHssh 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_IP2Install Python on the server
Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.
BASHsudo apt install -y python3 python3-venv python3-pip sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app3Install the app
Create the venv on the server.
BASHgit 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 .env4Run 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.target5Start and enable the service
Reload systemd, start the service now and on every boot, and check that it is active (running).
BASHsudo systemctl daemon-reload sudo systemctl enable --now fastapi-app sudo systemctl status fastapi-app journalctl -u fastapi-app -f6Install Nginx as a reverse proxy
Nginx receives requests on ports 80/443 and forwards them to your app on
127.0.0.1:8000. Replaceexample.comwith your domain. TheUpgradeheaders in this config also make WebSocket endpoints work./etc/nginx/sites-available/example.comserver { 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"; } }7Enable the site and reload Nginx
Link the config into
sites-enabled, test it and reload.nginx -tmust say syntax is ok before you reload.BASHsudo apt install -y nginx sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx8Open 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.
BASHsudo ufw allow OpenSSH sudo ufw allow 'Nginx Full' # ports 80 and 443 (after installing Nginx) sudo ufw enable sudo ufw status9Point your domain to the server
In your domain registrar's DNS panel add an A record for
@(andwww) with the server's public IP address. DNS changes usually appear within minutes but can take up to 24–48 hours. Check withdigor 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.com10Add 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.BASHsudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com sudo certbot renew --dry-run11Optional: hide the docs in production
Disable the public docs if the API is private.
PYTHONapp = 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.
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.
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_modelto control exactly what is returned. - Split routes with
APIRouterand dependencies (Depends) for auth and DB sessions. - Never block the event loop inside
async def. - Test with
TestClient/httpx in CI. - Never commit
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store.