ποΈ Building Your FastAPI House: Application Architecture
The Big Picture: What Are We Building?
Imagine youβre building a house. You wouldnβt just throw all your furniture, pipes, and wires into one big pile, right? That would be chaos!
Instead, you organize:
- ποΈ Living room stuff goes in the living room
- π³ Kitchen stuff goes in the kitchen
- π Bathroom stuff goes in the bathroom
FastAPI Application Architecture works the same way!
When your app grows big, you need to organize your code into neat βroomsβ (folders and files) so you can find things easily.
π§ Our Journey Today
Weβll learn three super important things:
- APIRouter Basics β Like building separate rooms
- Router Configuration β Like connecting rooms with doors
- Project File Organization β Like having a floor plan
π¦ Part 1: APIRouter Basics
What is APIRouter?
Think of APIRouter like a mini-app inside your main app.
Without APIRouter (messy room):
# main.py - Everything in ONE file!
from fastapi import FastAPI
app = FastAPI()
@app.get("/users")
def get_users():
return ["Alice", "Bob"]
@app.get("/products")
def get_products():
return ["Apple", "Banana"]
# 100 more routes... CHAOS!
With APIRouter (organized rooms):
# routers/users.py - Just user stuff!
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def get_users():
return ["Alice", "Bob"]
How to Create a Router
Itβs like creating a new room:
from fastapi import APIRouter
# Create a new "room"
router = APIRouter()
# Add "furniture" (routes) to this room
@router.get("/hello")
def say_hello():
return {"message": "Hello!"}
Why Use APIRouter?
| Without Router | With Router |
|---|---|
| π° All code in one file | π Code split into files |
| π° Hard to find things | π Easy to navigate |
| π° Team conflicts | π Teams work separately |
π Part 2: Router Configuration
Connecting Your Rooms
Now you have separate rooms (routers), but how do you connect them to your main house (app)?
Itβs like installing doors between rooms!
graph TD A[π Main App] --> B[πͺ Include Router] B --> C[π€ Users Router] B --> D[π¦ Products Router] B --> E[π Orders Router]
The Magic Include
# main.py
from fastapi import FastAPI
from routers import users, products
app = FastAPI()
# Connect the rooms!
app.include_router(users.router)
app.include_router(products.router)
Adding Prefixes (Room Labels)
Want all user routes to start with /users? Use a prefix!
app.include_router(
users.router,
prefix="/users"
)
Now:
/in users.py becomes/users//profilebecomes/users/profile
Adding Tags (Room Signs)
Tags help organize your API docs:
app.include_router(
users.router,
prefix="/users",
tags=["Users"]
)
Complete Configuration Example
# main.py
from fastapi import FastAPI
from routers import users, products
app = FastAPI(title="My Shop")
app.include_router(
users.router,
prefix="/users",
tags=["Users"]
)
app.include_router(
products.router,
prefix="/products",
tags=["Products"]
)
π Part 3: Project File Organization
The Floor Plan
Just like a house has a floor plan, your project needs a structure!
Simple Project:
my_app/
βββ main.py # π Front door
βββ routers/ # π All rooms
β βββ __init__.py
β βββ users.py # π€ User room
β βββ products.py # π¦ Product room
βββ requirements.txt # π Shopping list
Bigger Project:
my_app/
βββ main.py # π Entry point
βββ routers/ # πͺ API routes
β βββ __init__.py
β βββ users.py
β βββ products.py
βββ models/ # π Data shapes
β βββ __init__.py
β βββ user.py
βββ services/ # βοΈ Business logic
β βββ __init__.py
β βββ auth.py
βββ config.py # βοΈ Settings
What Goes Where?
| Folder | Whatβs Inside | Example |
|---|---|---|
routers/ |
API endpoints | GET /users |
models/ |
Data structures | User class |
services/ |
Business logic | Send email |
config.py |
Settings | Database URL |
The init.py File
This little file says βIβm a folder Python can use!β
# routers/__init__.py
# Can be empty, or export routers:
from .users import router as users_router
π― Putting It All Together
Step 1: Create Your Router
# routers/users.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def list_users():
return [{"name": "Alice"}]
@router.get("/{user_id}")
def get_user(user_id: int):
return {"id": user_id}
Step 2: Connect to Main App
# main.py
from fastapi import FastAPI
from routers import users
app = FastAPI()
app.include_router(
users.router,
prefix="/users",
tags=["Users"]
)
@app.get("/")
def home():
return {"message": "Welcome!"}
Step 3: Your Routes Now Work!
GET /β Welcome messageGET /users/β List of usersGET /users/123β User with ID 123
π Quick Summary
graph LR A[π― Application Architecture] --> B[APIRouter] A --> C[Router Config] A --> D[File Organization] B --> B1[Create mini-apps] B --> B2[Separate concerns] C --> C1[include_router] C --> C2[prefix & tags] D --> D1[routers/ folder] D --> D2[models/ folder] D --> D3[services/ folder]
π‘ Remember This!
- APIRouter = Mini-app for related routes
- include_router() = Connects router to main app
- prefix = Adds path prefix to all routes
- tags = Groups routes in API docs
- Organize files = Happy developers!
π You Did It!
You now know how to:
- β Create routers for different features
- β Configure and connect them
- β Organize your project like a pro
Your FastAPI house is ready for visitors! π β¨