Basics
FastAPI is a modern Python web framework for building APIs quickly and efficiently. It’s built on top of Starlette (for web handling) and Pydantic (for data validation). FastAPI is known for its speed, ease of use, and automatic generation of interactive documentation using OpenAPI (Swagger).
1. 🔍 What is FastAPI?
Section titled “1. 🔍 What is FastAPI?”FastAPI is a web framework designed to create RESTful APIs with minimal code and maximum performance.
1.1 Key Features:
Section titled “1.1 Key Features:”- Asynchronous support (async/await): Great for high-performance apps (like real-time APIs).
- Data validation: Built-in using Pydantic.
- Type hints: Used for input/output validation and automatic docs.
- Automatic docs: Swagger UI and ReDoc generated out of the box.
- Fast: Very close to Node.js and Go in performance benchmarks.
- Easy to use: Minimal boilerplate code.
1.2 FastAPI vs Django
Section titled “1.2 FastAPI vs Django”| Feature | FastAPI | Django |
|---|---|---|
| API First | Designed for APIs | Web framework with API via Django REST |
| Async support | First-class async support | Limited (added later, not native) |
| Performance | Very fast (near Node.js/Go speed) | Slower due to sync model |
| Automatic docs | Yes (Swagger & ReDoc) | Not out of the box |
| Type validation | Yes (via Pydantic & Python types) | Manual or via Django REST serializers |
| Boilerplate | Minimal | More boilerplate |
| Learning curve | Easier for API-only devs | Steeper for REST APIs |
1.3 When to Use What?
Section titled “1.3 When to Use What?”-
Use FastAPI if:
- You are building a microservice or API-only backend.
- You want modern Python type hints and async support.
- You care about speed and automatic docs.
-
Use Django if:
- You need an all-in-one solution with admin panel, ORM, templating.
- You are building a full-stack site or CMS.
- You have complex relational database needs with Django ORM.
2. Hello World
Section titled “2. Hello World”To create a project using FastAPI for the backend and a frontend (like React, Vue, plain HTML, etc.), follow these high-level steps:
2.1 Step 1: Set Up the FastAPI Backend
Section titled “2.1 Step 1: Set Up the FastAPI Backend”1. Create a Python virtual environment:
Section titled “1. Create a Python virtual environment:”python -m venv venvsource venv/bin/activate # On Windows: venv\Scripts\activate2. Install FastAPI and a server (e.g., Uvicorn):
Section titled “2. Install FastAPI and a server (e.g., Uvicorn):”pip install fastapi uvicorn3. Create your FastAPI app (main.py):
Section titled “3. Create your FastAPI app (main.py):”from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# Allow requests from frontendapp.add_middleware( CORSMiddleware, allow_origins=["*"], # Change to your frontend URL in production allow_methods=["*"], allow_headers=["*"],)
@app.get("/api/hello")def hello(): return {"message": "Hello from FastAPI!"}4. Run the backend server:
Section titled “4. Run the backend server:”uvicorn main:app --reload2.2 Step 2: Set Up the Frontend
Section titled “2.2 Step 2: Set Up the Frontend”Choose a frontend stack like:
- React (with Vite or Create React App)
- Vue
- Plain HTML/JS
Example with React (Vite):
Section titled “Example with React (Vite):”npm create vite@latest my-frontend --template reactcd my-frontendnpm installnpm run devCall the FastAPI API:
Section titled “Call the FastAPI API:”In your React component (e.g., App.jsx):
import { useEffect, useState } from 'react';
function App() { const [message, setMessage] = useState("");
useEffect(() => { fetch('http://localhost:8000/api/hello') .then(res => res.json()) .then(data => setMessage(data.message)); }, []);
return <h1>{message}</h1>;}
export default App;2.3 Step 3: Connect and Run
Section titled “2.3 Step 3: Connect and Run”- Make sure the backend (FastAPI) is running on
localhost:8000 - Make sure the frontend (React) is running on
localhost:5173(or similar)
2.4 Deployment Options
Section titled “2.4 Deployment Options”- Backend: Deploy with Render, Railway, or a VPS (e.g., using Gunicorn + Nginx).
- Frontend: Deploy with Vercel, Netlify, or Firebase Hosting.
FastAPI does not have its own web server built-in, but it is designed to run on ASGI servers (Asynchronous Server Gateway Interface), primarily:
✅ Common ASGI Servers for FastAPI
Section titled “✅ Common ASGI Servers for FastAPI”| Server | Description |
|---|---|
| Uvicorn | Most commonly used. Lightweight and fast. |
| Hypercorn | Alternative ASGI server. Supports HTTP/2, QUIC. |
| Daphne | Part of Django Channels (less common for FastAPI). |
🔧 Typical Usage
Section titled “🔧 Typical Usage”You install and run Uvicorn like this:
pip install uvicornuvicorn main:app --reloadmain→ your Python file (i.e.,main.py)app→ the FastAPI instance (app = FastAPI())--reload→ auto-reload when code changes (for dev only)
🔍 Under the Hood
Section titled “🔍 Under the Hood”FastAPI is:
- Just a Python framework to define routes and logic.
- ASGI-compatible (similar to how Flask is WSGI-compatible).
- Dependent on an external ASGI server like Uvicorn to actually serve HTTP requests.
🧠 Summary
Section titled “🧠 Summary”- ❌ FastAPI doesn’t include a server.
- ✅ You use Uvicorn (or another ASGI server) to run it.
- ✅ This separation allows FastAPI to be asynchronous, high-performance, and flexible.
Let me know if you want help setting up Uvicorn in production (with Gunicorn or Nginx).