Introduction to FastAPI

🧠 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).

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.

LibraryPurposeWorks Independently?
SQLAlchemyHandles database interaction via ORM (Object Relational Mapper).✅ Yes — works with any Python framework (Flask, Django, etc.)
PydanticValidates and serializes data (input/output models).✅ Yes — can be used in any Python script or framework.
pydantic-settingsLoads configuration (like environment variables) safely.✅ Yes — standalone library for any Python app.
FastAPIWeb 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

ResponsibilityDescription
1️⃣ Routing & EndpointsDefines URLs like /todos, /todos/{id} and what functions handle them.
2️⃣ Request HandlingAccepts HTTP requests (GET, POST, etc.) and parses input (JSON, form, etc.).
3️⃣ Dependency InjectionAutomatically provides resources like db: Session = Depends(get_db).
4️⃣ Validation IntegrationUses Pydantic models to validate request bodies automatically.
5️⃣ Response SerializationConverts ORM objects → Pydantic → JSON responses.
6️⃣ Async I/O SupportHandles thousands of concurrent requests using async/await.
7️⃣ DocumentationAutomatically 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
StepLibrary Doing the WorkDescription
1️⃣ Client sends JSON →FastAPIParses JSON request body
2️⃣ Validate data →PydanticEnsures it matches TodoCreate schema
3️⃣ Store data →SQLAlchemySaves Todo in database
4️⃣ Convert result →PydanticFormats ORM model as JSON response
5️⃣ Send back response →FastAPIReturns 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.

LibraryExample of Use Without FastAPI
SQLAlchemyUsed in Flask, Django ORM alternatives, or scripts.
PydanticUsed in data pipelines, microservices, or CLI tools for validation.
pydantic-settingsUsed 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.

✅ 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

ConceptFastAPI’s Role
SQLAlchemy ORMManages the database layer
PydanticValidates and structures data
pydantic-settingsLoads configuration
FastAPICoordinates everything — handles requests, validation, routing, and responses

Scroll to Top