Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
A tour of the FastAPI blog an AI agent built: two main.py files, app/main.py with SessionMiddleware and three routers, database, models, schemas no route uses, bcrypt in auth.py, JWT code nobody calls, templates, the seed script and a Swagger page that says little for an HTML app.
What you will learn
- Say what each file in a monolithic FastAPI blog does, from the root main.py to the templates
- Read app/main.py and find the session middleware, the static mount and the routers
- Tell which code in an AI-built project is actually used (schemas, JWT helpers) and which is left over
- List the review points a folder tour turns up before you change anything
Before you start
- FastAPI routes and Depends
- SQLAlchemy models and a session per request
- Jinja2 templates
An AI agent built our FastAPI blog. It runs, it has a design, and the admin can write posts. Before you change anything in it, though, you should know where each piece sits. When a page breaks or you want a new feature, you need to know which file to open.
So in this article we open every folder and file of the project, one at a time. On the way we'll note a few things the agent got wrong. The blog comes from building it with an AI agent and giving it a design. It runs on FastAPI 0.136.1 with SQLite.
The office building
Picture an office building. uvicorn is the front door, and the FastAPI app is the help desk behind it. The root main.py is the switch that opens the front door in the morning. app/main.py is the reception: it sets the house rules and sends each visitor to the right desk. The routes folder holds the desks, one file for accounts, one for posts and one for comments. models.py and database.py are the records room. templates and static are the rooms the visitor actually sees.
Two main.py files
The root main.py is five lines:
from app.main import app
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=8000, reload=True)
The first line imports app from app.main, so the app itself is built inside the package. Run this file with python main.py and it starts uvicorn with reload on.
Now open app/main.py and scroll to the bottom. Lines 43 to 45 hold the same if __name__ == "__main__" block again. Two entry points that do the same job is one too many, so keep one and delete the other. In the run we started the server with uvicorn app.main:app, and both GET / and GET /openapi.json answered 200.
app/main.py: the reception
This file is 45 lines. Here it is, with the fallback secret replaced by a placeholder and the contact block shortened:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.middleware.sessions import SessionMiddleware
from app.database import engine, Base
from app.routes import auth, posts, comments
import os
from dotenv import load_dotenv
load_dotenv()
# Create database tables
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Blog Application",
description="A monolithic FastAPI blog application with user authentication, post management, and commenting system",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
license_info={
"name": "MIT",
}
)
# Add session middleware for authentication
SECRET_KEY = os.getenv("SECRET_KEY", "<placeholder>")
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
# Mount static files
app.mount("/static", StaticFiles(directory="app/static"), name="static")
# Include routers
app.include_router(auth.router, tags=["auth"])
app.include_router(posts.router, tags=["posts"])
app.include_router(comments.router, tags=["comments"])
- Line 13,
Base.metadata.create_all, creates any missing tables when the app starts. SessionMiddlewareis the only middleware in the app. It keeps a user logged in from page to page with a signed cookie. The key comes from.env, and if it's missing the code falls back to a fixed string written in the source. Always set it.app.mount("/static", ...)serves the static folder, so the browser can fetch the CSS.- The three
include_routerlines plug in the routes. Each router gets a tag, and you'll see those tags on the docs page.
.env and requirements.txt
.env holds three names: ADMIN_EMAIL, SECRET_KEY and DATABASE_URL. load_dotenv() reads them when the app starts. This file holds a secret, so it must never go into git, and the project has no .gitignore. Ask the agent to add one before you push.
requirements.txt pins eleven packages to exact versions:
fastapi==0.136.1
uvicorn[standard]==0.46.0
python-multipart==0.0.27
jinja2==3.1.6
sqlalchemy==2.0.36
python-dotenv==1.2.2
passlib[bcrypt]==1.7.4
bcrypt==4.0.1
python-jose[cryptography]==3.3.0
email-validator==2.3.0
itsdangerous==2.2.0
Keep an eye on python-jose, the JWT package. We'll come back to it.
database.py and models.py: the records room
database.py is 25 lines. DATABASE_URL defaults to sqlite:///./blog.db, one file next to main.py. create_engine sets up the connection, and check_same_thread=False lets FastAPI use it from more than one thread. SessionLocal makes sessions, Base is the parent of every model, and get_db opens a session, yields it to a route and closes it afterwards. That pattern is explained in SQLAlchemy models and migrations.
models.py has three classes, and each becomes a table: User (email, username, hashed_password, is_admin, created_at), Post (title, content, author_id and two dates) and Comment, which links to a post and an author through foreign keys. The relationship lines let you write post.author or post.comments and SQLAlchemy runs the query.
There's no migrations folder. create_all only adds tables that are missing, so if you change a model later, the existing table stays as it was. That's the job Alembic does.
schemas.py: written, never used
These are Pydantic models for the shape of the data:
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import Optional, List
class UserCreate(BaseModel):
email: EmailStr
username: str
password: str
class UserLogin(BaseModel):
email: EmailStr
password: str
class UserResponse(BaseModel):
id: int
email: str
username: str
is_admin: bool
created_at: datetime
class Config:
from_attributes = True
UserCreate and UserLogin are for data coming in. UserResponse, PostResponse and CommentResponse are for data going out. But a search of the code finds response_model zero times, and routes/auth.py imports UserCreate and UserLogin on line 7 and then never uses them.
The reason is simple. These routes read form fields and send back HTML pages, not JSON. In a JSON API, schemas do real work (see path, query, body and response_model). Here they're leftovers, so ask the agent to use them or remove them.
auth.py: passwords and guards
The helper file in the app package is 100 lines. The top of it:
SECRET_KEY = os.getenv("SECRET_KEY", "<placeholder>")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
def verify_password(plain_password: str, hashed_password: str) -> bool:
# Truncate password to 72 bytes (bcrypt limit)
truncated_password = plain_password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
return pwd_context.verify(truncated_password, hashed_password)
def get_password_hash(password: str) -> str:
# Truncate password to 72 bytes (bcrypt limit)
truncated_password = password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
return pwd_context.hash(truncated_password)
Passwords are hashed with bcrypt through passlib. They are hashed, not encrypted: there's no decrypt function and no way back from a hash. verify_password hashes what you typed and compares. The full story of the hash, the 72-byte cut and the login is in how a request and a login flow through the blog.
At the bottom are two guards. require_auth answers 401 when nobody is logged in. require_admin calls it first and answers 403 when the user isn't an admin.
Token code nobody calls
The same file has create_access_token on line 34, which builds a JWT with python-jose, and get_current_user_from_token on line 54. The search found exactly one hit for each: the line that defines it. Nothing calls them. The app logs users in with the session cookie instead. That's unused code plus an extra package in requirements.txt, so ask the agent to remove it or explain why it's there.
The routes package
Listing the app's routes gives thirteen:
GET /register auth.register_page
POST /register auth.register
GET /login auth.login_page
POST /login auth.login
GET /logout auth.logout
GET / posts.index
GET /post/{post_id} posts.post_detail
GET /admin/create posts.create_post_page
POST /admin/create posts.create_post
GET /admin/edit/{post_id} posts.edit_post_page
POST /admin/edit/{post_id} posts.edit_post
POST /admin/delete/{post_id} posts.delete_post
POST /post/{post_id}/comment comments.create_comment
Register and login each have a GET that shows the page and a POST that takes the form. Every function is async def, and every page comes back as HTML. The guards are attached with Depends: the five admin routes have user=Depends(require_admin), and the comment route has user=Depends(require_auth):
@router.get("/admin/create", response_class=HTMLResponse)
async def create_post_page(request: Request, db: Session = Depends(get_db), user=Depends(require_admin)):
Those async def functions sit on a blocking SQLAlchemy session. Whether that matters gets measured in the request flow article.
Templates and static
The templates folder has seven HTML files. base.html is the frame with the menu and footer, and line 7 links /static/css/style.css. The menu changes with the user: if user.is_admin is true it shows New Post, and with nobody logged in it shows Login and Register.
index.html extends base.html and fills the content block:
{% extends "base.html" %}
{% block title %}Home - Blog{% endblock %}
{% block content %}
<div class="posts-container">
{% if posts %}
{% for post in posts %}
<article class="post-card">
<h2><a href="/post/{{ post.id }}">{{ post.title }}</a></h2>
<div class="post-meta">
<span class="author">{{ post.author.username }}</span>
<span class="date">{{ post.created_at.strftime('%B %d, %Y') }}</span>
</div>
(shortened from the real file). static holds one stylesheet, 611 lines. The js folder is empty, because the Quill editor on the create page loads from a CDN. Each route file points Jinja2Templates at app/templates, so a route only names the file it wants.
seed_data.py
Back at the root, the seed script fills a fresh database. It creates the tables, and if there are already users it prints "Database already has data. Skipping seed." and stops. Otherwise it adds two test users, an admin (the ADMIN_EMAIL value from .env) and a regular user, both with hashed passwords, then five sample posts and three comments. The run ended like this:
Created post: Welcome to My Blog!
Created post: Getting Started with FastAPI
Created post: Building a Monolithic Application
Created post: Using Quill.js for Rich Text Editing
Created post: Database Design for Blog Applications
Created 3 sample comments
Database seeded successfully!
The Swagger page for an HTML app
Because it's FastAPI, /docs is free. The routes are grouped under the three tags auth, posts and comments, and the page lists nine paths for thirteen routes, because a GET and a POST often share a path like /login.
The schemas there have names like Body_login_login_post. FastAPI made them from the form fields, and the classes in schemas.py don't appear at all. The POST routes claim to return JSON with an empty schema, but they really send a redirect. So for an HTML app this page tells you little. It matters much more when a separate front end talks to the back end over JSON, because then it becomes the agreement between the two.
The review list from one tour
| Where | What we found | Ask the agent to |
|---|---|---|
main.py and app/main.py | two entry points that do the same thing | keep one |
.env | a secret, and no .gitignore | add a .gitignore |
schemas.py | no route uses it, response_model appears 0 times | use it or remove it |
auth.py lines 34 and 54 | JWT helpers nobody calls, plus python-jose | remove them |
routes/auth.py line 62 | is_admin = email == ADMIN_EMAIL | set the admin from a trusted place (details) |
models.py, auth.py | datetime.utcnow on six lines, deprecated | use datetime.now(timezone.utc) |
Older AI tools often put everything into one main.py. This agent split the app well, but it still left unused code and a duplicate entry point behind. So read the tree and keep asking questions. The same tour for the other two frameworks: the Django blog and the Flask blog.
Quick recap
| File or folder | Job |
|---|---|
main.py (root) | starts uvicorn on app.main:app |
app/main.py | create_all, SessionMiddleware, static mount, three routers |
.env | ADMIN_EMAIL, SECRET_KEY, DATABASE_URL |
database.py, models.py | engine, sessions, get_db; User, Post, Comment tables |
schemas.py | Pydantic shapes, unused in this HTML app |
auth.py | bcrypt hashing, require_auth (401), require_admin (403) |
routes/ | 13 async def routes returning HTML |
templates/, static/ | pages built on base.html, one style.css |
seed_data.py | two test users, five posts, three comments |
Try it yourself
Prompt an AI tool to remove the unused token code. Review the diff, check that python-jose left requirements.txt too, and open /docs to make sure the page still loads.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
