π Starting Authentication & Authorization
In this section, we begin implementing:
Authentication β Who are you?
Authorization β What are you allowed to do?
As our application grows, we must now think about structure and scalability, not just writing more endpoints.
π§ The Architectural Problem
When starting authentication, your first instinct might be:
βLetβs just add more endpoints inside
main.py.β
For example:
/register/login/verify-token/users/me
But mixing:
Todo logic
Authentication logic
Authorization logic
inside a single file quickly becomes:
β Hard to maintain
β Difficult to scale
β Messy and tightly coupled
As backend engineers, we separate concerns.
ποΈ Step 1 β Create a Separate File for Auth
Inside your Todo project directory:
Create a new file: Inside TodoApp folder
auth.pyThis file will eventually contain:
User registration
Login
JWT logic
Password hashing
Role validation
π§© Step 2 β Basic FastAPI Setup in auth.py
Inside auth.py, we may be tempted to write:
from fastapi import FastAPI
app = FastAPI()Then create a demo endpoint:
from fastapi import FastAPI
app = FastAPI()
@app.get("/auth/")
async def get_user():
return {"user": "authenticated"}π¨ What Just Happened Internally?
When you write:
app = FastAPI()You are creating:
π§ A completely new FastAPI application instance
This means:
main.pyhas its ownappauth.pynow has a differentapp
They are two completely separate ASGI applications.
π₯οΈ Step 3 β Running the Server
In the terminal, we still run:
uvicorn main:app --reloadFastAPI only loads:
main.py β appIt does NOT load:
auth.py β appBecause we never told FastAPI to include it.
π What You Will Notice in the Browser
When you open:
/docsYou will see:
All Todo endpoints from
main.py
But you will NOT see:
GET /auth/Why?
Because auth.py is running its own separate FastAPI application that is never started.
β Why Not Just Run auth.py Separately?
You could run:
uvicorn auth:app --reload
But then:
You lose access to your Todo endpoints
You now have two separate applications
They cannot share dependencies or database sessions cleanly
This is NOT how scalable backend systems are built.
π§ Backend Concept β One Application, Multiple Routers
A production backend typically has:
One FastAPI application instance
Multiple modules
Organized routing
Instead of:
Multiple FastAPI apps βWe want:
One FastAPI app
Multiple routers β
This allows:
Clean separation of concerns
Shared database sessions
Shared authentication logic
Scalable architecture
ποΈ auth.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/auth/")
async def get_user():
return {"user": "authenticated"}