Module 3 Exercises: Building the Skeleton

Module 3 Exercises: Building the Skeleton

Practical exercises to master project structure, environment management, and secure configuration.

Module 3 Exercises: Building the Skeleton

You've learned how to move from a single script to a production-grade architecture. These exercises will test your ability to organize and secure a project.


Exercise 1: The Router Inclusion

You are building a Social Media API. You have created a file called api/v1/posts.py with the following content:

from fastapi import APIRouter

router = APIRouter()

@router.get("/feed")
def get_feed():
    return {"posts": []}

Write the code needed in your main.py to include this router so that the feed is accessible at the URL /api/v1/posts/feed.


Exercise 2: The .gitignore Audit

Which of the following files should NEVER be committed to a public Git repository? (Select all that apply)

  1. main.py
  2. .env
  3. requirements.txt
  4. .venv/
  5. pyproject.toml
  6. secrets.json

Exercise 3: Pydantic Settings Design

Design a Settings class using pydantic-settings for an Email Marketing App. The class should handle three variables:

  • SERVICE_NAME (String, default: "MailFast")
  • MAX_EMAILS_PER_DAY (Integer, no default)
  • USE_SANDBOX_MODE (Boolean, default: True)

How would your .env file look if you wanted to set the max emails to 5000 and turn off sandbox mode?


Self-Correction / Discussion

Exercise 1 Answer:

from fastapi import FastAPI
from app.api.v1 import posts

app = FastAPI()

app.include_router(
    posts.router, 
    prefix="/api/v1/posts", 
    tags=["posts"]
)

Exercise 2 Answer:

2, 4, and 6.

  • .env contains secrets.
  • .venv/ is environment-specific and massive.
  • secrets.json contains... well, secrets! Note: requirements.txt and pyproject.toml SHOULD be committed so others can recreate your environment.

Exercise 3 Answer:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    service_name: str = "MailFast"
    max_emails_per_day: int
    use_sandbox_mode: bool = True

settings = Settings()

.env file:

MAX_EMAILS_PER_DAY=5000
USE_SANDBOX_MODE=False

Summary of Module 3

You now know how to build the "House" for your code.

  • Structure: You can modularize with APIRouter.
  • Isolation: You can protect your environment with Venv/Poetry.
  • Security: You can manage secrets via Environment Variables.

In Module 4: Routing and Request Handling, we will dive back into the code to master how FastAPI processes incoming path and query parameters.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn