FastAPI - Beginner to Pro / Authentication & Authorization

Starting Authentication & Authorization

πŸ” 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.py

This 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.py has its own app

  • auth.py now has a different app

They are two completely separate ASGI applications.


πŸ–₯️ Step 3 β€” Running the Server

In the terminal, we still run:

uvicorn main:app --reload

FastAPI only loads:

main.py β†’ app

It does NOT load:

auth.py β†’ app

Because we never told FastAPI to include it.

🌐 What You Will Notice in the Browser

When you open:

/docs

You 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"}