🧠 What is FastAPI?
FastAPI is a modern, high-performance web framework for building APIs with Python.
It’s based on:
- Starlette (for the web parts)
- Pydantic (for data validation)
- async I/O support (for high speed)
💡 Why it’s popular:
- Automatically generates documentation (Swagger UI).
- Performs automatic data validation using Python type hints.
- Super-fast (built on ASGI — Asynchronous Server Gateway Interface).
Table of Contents
FastAPI orchestrates web-level logic, routing, validation, dependency management, and HTTP response building.
Creating our first FastAPI project
Before driving into the FastAPI coding let create root page with hello world, famous message. To create the project, we need to follow these steps.
#step 1 : Create project folder
mkdir first-app
cd first-app
code .
Step 2: Create requirements.tx
Inside the project lets create requirements.txt file containing minimum libraries need to run our first fastapi.
#requirements libraries
fastapi
uvicorn
pydantic
Step 3: Create a Virtual Environment
A virtual environment isolates your project’s dependencies from your system’s global Python packages, preventing conflicts. Use the built-in venv module to create an environment (we’ll call it venv):
python3 -m venv venv
source venv/bin/activate
Step 4: Install the fastapi
In our virtual enviroment cli, let used the requiremets.tx to install the minimum libraries to run the FastAPI.
pip install -r requirements.txt
Step 5: Run FastAPI
Let first create main.py inside the root folder and add following code.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
Now inside the virtual enviroment terminal let run the main.py and open browser to check hello world message at root url http://localhost:8000/
1. How FastAPI Fits In — and What Its Real Job Is
The Role of Each Major Library used in FastAPI, and other popular Python web framwork.
| Library | Purpose | Works Independently? |
|---|---|---|
| SQLAlchemy | Handles database interaction via ORM (Object Relational Mapper). | ✅ Yes — works with any Python framework (Flask, Django, etc.) |
| Pydantic | Validates and serializes data (input/output models). | ✅ Yes — can be used in any Python script or framework. |
| pydantic-settings | Loads configuration (like environment variables) safely. | ✅ Yes — standalone library for any Python app. |
| FastAPI | Web framework for building APIs. Handles requests, routing, dependency injection, validation, responses, etc. | ❌ No — this is the “glue” that ties all others together for APIs. |
2. So What Exactly Does FastAPI Do?
Think of FastAPI as the “Director” — it doesn’t store data, validate it, or query the database itself —
but it tells when and how each helper (Pydantic, SQLAlchemy, etc.) should do their job.
🧩 FastAPI’s Main Responsibilities
| Responsibility | Description |
|---|---|
| 1️⃣ Routing & Endpoints | Defines URLs like /todos, /todos/{id} and what functions handle them. |
| 2️⃣ Request Handling | Accepts HTTP requests (GET, POST, etc.) and parses input (JSON, form, etc.). |
| 3️⃣ Dependency Injection | Automatically provides resources like db: Session = Depends(get_db). |
| 4️⃣ Validation Integration | Uses Pydantic models to validate request bodies automatically. |
| 5️⃣ Response Serialization | Converts ORM objects → Pydantic → JSON responses. |
| 6️⃣ Async I/O Support | Handles thousands of concurrent requests using async/await. |
| 7️⃣ Documentation | Automatically generates Swagger & Redoc API docs. |
3. How They Work Together (with Example)
Here’s the flow of a typical FastAPI request using SQLAlchemy & Pydantic:
Client → FastAPI Endpoint → Pydantic Validation → SQLAlchemy Query → Response
Example
@app.post("/todos", response_model=schemas.Todo)
def create(todo: schemas.TodoCreate, db: Session = Depends(get_db)):
db_todo = models.Todo(**todo.model_dump())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
| Step | Library Doing the Work | Description |
|---|---|---|
| 1️⃣ Client sends JSON → | FastAPI | Parses JSON request body |
| 2️⃣ Validate data → | Pydantic | Ensures it matches TodoCreate schema |
| 3️⃣ Store data → | SQLAlchemy | Saves Todo in database |
| 4️⃣ Convert result → | Pydantic | Formats ORM model as JSON response |
| 5️⃣ Send back response → | FastAPI | Returns validated JSON to client |
4. Using These Libraries Without FastAPI
Yes — each library (SQLAlchemy, Pydantic, pydantic-settings) can work independently with other Python frameworks or even standalone scripts.
✅ This is exactly why Clean Architecture is possible — because each responsibility (database access, validation, configuration, etc.) is separated and can operate at different layers.
Clean Architecture is not specific to FastAPI; it can be applied to any backend framework (Flask, Django, etc.) or even non-web Python applications.
| Library | Example of Use Without FastAPI |
|---|---|
| SQLAlchemy | Used in Flask, Django ORM alternatives, or scripts. |
| Pydantic | Used in data pipelines, microservices, or CLI tools for validation. |
| pydantic-settings | Used in any project needing environment configuration. |
Example (without FastAPI):
from sqlalchemy import create_engine
from pydantic import BaseModel
engine = create_engine("sqlite:///test.db")
class User(BaseModel):
name: str
age: int
data = {"name": "Alice", "age": 25}
user = User(**data) # ✅ validated even without FastAPI
So yes — all of these are independent libraries, but FastAPI brings them together seamlessly for web development.
Why FastAPI Became Popular
✅ Uses Pydantic for auto-validation → less manual error handling.
✅ Integrates SQLAlchemy cleanly for database ORM.
✅ Built on ASGI (async) → faster and modern than older frameworks.
✅ Generates interactive documentation automatically.
✅ Supports dependency injection, making large projects easier to scale.
🧠 6. In Short
| Concept | FastAPI’s Role |
|---|---|
| SQLAlchemy ORM | Manages the database layer |
| Pydantic | Validates and structures data |
| pydantic-settings | Loads configuration |
| FastAPI | Coordinates everything — handles requests, validation, routing, and responses |