0
0
FastAPIframework~30 mins

Folder structure patterns in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Folder Structure Patterns in FastAPI
📖 Scenario: You are building a simple FastAPI web application to manage books in a library. To keep your project clean and easy to maintain, you want to organize your code using a common folder structure pattern.
🎯 Goal: Build a basic FastAPI project with a clear folder structure that separates the main app, routers, and models.
📋 What You'll Learn
Create a main application file main.py inside the app folder
Create a routers folder inside app with a books.py router file
Create a models.py file inside app for data models
Include a simple route in books.py that returns a list of book titles
💡 Why This Matters
🌍 Real World
Organizing code in folders is essential for real FastAPI projects to keep code manageable and scalable.
💼 Career
Understanding folder structure patterns is a key skill for backend developers working with FastAPI or similar frameworks.
Progress0 / 4 steps
1
Create the initial folder structure and main app file
Create a folder called app. Inside app, create a file named main.py with the following code: import FastAPI from fastapi and create an instance called app.
FastAPI
Need a hint?

Use from fastapi import FastAPI and then create app = FastAPI().

2
Add a routers folder and create books router
Inside the app folder, create a folder named routers. Inside routers, create a file called books.py. In books.py, import APIRouter from fastapi, create a router instance called router, and add a GET route /books that returns a list of book titles: ["Book A", "Book B"].
FastAPI
Need a hint?

Create router = APIRouter() and add a GET route @router.get("/books") that returns the list.

3
Create a models.py file for data models
Inside the app folder, create a file named models.py. In this file, import BaseModel from pydantic and create a class Book that inherits from BaseModel with two fields: title (string) and author (string).
FastAPI
Need a hint?

Use class Book(BaseModel): with title: str and author: str fields.

4
Connect the books router in main.py
In main.py, import router from app.routers.books and include it in the app using app.include_router(router).
FastAPI
Need a hint?

Use app.include_router(router) to add the books routes to the main app.