📖 Scenario: You are building a simple FastAPI application to manage a small library of books. As the app grows, organizing your code well will help keep it easy to understand and maintain.
🎯 Goal: Build a FastAPI app with a clear project structure by creating a data list, a configuration variable, a route to get books, and finally include the router in the main app.
📋 What You'll Learn
Create a list of books with exact titles and authors
Add a configuration variable for the API prefix
Create a FastAPI router with a GET endpoint to return the books list
Include the router in the main FastAPI app with the prefix
💡 Why This Matters
🌍 Real World
Organizing FastAPI projects clearly helps teams work together and makes adding features easier.
💼 Career
Understanding project structure is key for backend developers building scalable APIs with FastAPI.
Progress0 / 4 steps
1
Create the initial data list
Create a list called books with these exact dictionaries: {'title': '1984', 'author': 'George Orwell'}, {'title': 'Brave New World', 'author': 'Aldous Huxley'}, and {'title': 'Fahrenheit 451', 'author': 'Ray Bradbury'}.
FastAPI
Hint
Use a list of dictionaries with the exact keys and values given.
2
Add API prefix configuration
Create a string variable called API_PREFIX and set it to "/library".
FastAPI
Hint
Just assign the string "/library" to API_PREFIX.
3
Create a FastAPI router with GET endpoint
Import APIRouter from fastapi. Create a router called router. Add a GET endpoint /books to router that returns the books list.
FastAPI
Hint
Use @router.get("/books") decorator and an async function returning books.
4
Include the router in the main FastAPI app
Import FastAPI from fastapi. Create an app called app. Include the router in app using API_PREFIX as the prefix.
FastAPI
Hint
Use app.include_router(router, prefix=API_PREFIX) to add the router.
Practice
(1/5)
1. Why is having a clear project structure important when building a FastAPI app that will grow over time?
easy
A. It keeps the code organized and easier to maintain as the app grows.
B. It makes the app run faster by optimizing imports.
C. It automatically fixes bugs in the code.
D. It reduces the size of the app's files on disk.
Solution
Step 1: Understand the role of project structure
A clear project structure organizes code logically, making it easier to find and update parts as the app grows.
Step 2: Consider the impact on maintenance
Without good structure, code becomes messy and hard to maintain, especially with many files and developers.
Final Answer:
It keeps the code organized and easier to maintain as the app grows. -> Option A