Application Architecture

Loading concept...

πŸ—οΈ 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:

  1. APIRouter Basics β†’ Like building separate rooms
  2. Router Configuration β†’ Like connecting rooms with doors
  3. 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/
  • /profile becomes /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 message
  • GET /users/ β†’ List of users
  • GET /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!

  1. APIRouter = Mini-app for related routes
  2. include_router() = Connects router to main app
  3. prefix = Adds path prefix to all routes
  4. tags = Groups routes in API docs
  5. 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! 🏠✨

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.