r/FastAPI • • Sep 08 '26

Tutorial FastAPI Interactive Tutorials: the browser-only course now runs real WebSockets in WebAssembly, has a VS Code-style workspace, syncs your progress, and issues a certificate when you finish a track (61 lessons, no install)

97 Upvotes

A year ago I launched fastapiinteractive.com - an interactive FastAPI course where you write and run real Python in the browser. No installs, no backend, it's Pyodide plus a small ASGI server running FastAPI in WebAssembly. I've posted about it here a couple of times, last one ~6 months ago.

I'll be honest, I didn't expect it to get this much use. I got busy and didn't touch it for a few months, and when I came back people were still going through the lessons every day and sending me bug reports. That got me back into it. A lot has changed since, so here's the update.

What's new:

  • WebSockets truly work now. There's no network socket in WASM, so the connection goes over the worker's message channel, but past the ASGI layer it's the real Starlette WebSocket running your handler. Embarrassing detail: previously, the two websocket lessons used to be graded by a GET /health check, so the code they taught had never once run as a websocket. Now they're graded on a real exchange of messages, including a broadcast between two connections, and there's a socket console to try your endpoints manually.
  • Streaming responses, file uploads and form bodies work.
  • Infinite loops don't kill the tab anymore. Your code gets compiled through a guard with a time budget per request, so while True: raises inside your own code with your line number instead of hanging everything.
  • New UI, VS Code style: lesson list with progress in the sidebar, editor in the middle, console/tests/theory as output tabs, status bar showing what the runtime is doing.
  • Accounts. Sign in with GitHub and your progress and code sync between devices. Without an account it works exactly like before, everything stays in your browser.
  • Certificates. When you finish a track you can get a certificate of completion - PDF, an image for LinkedIn, and a verification page with a serial anyone can check. Optional, the lessons themselves are free.
  • 61 lessons now: 45 basics following the FastAPI tutorial, the 6-lesson blog+auth project as a proper multi-file package, 10 advanced patterns.

Try it: https://www.fastapiinteractive.com/

Bug reports, feedback and ideas for lessons are very welcome, here or via the contact form on the site.

Thank you!

r/FastAPI • • Jul 21 '26

Tutorial Finished my first FastAPI project. Where do I go from here?

17 Upvotes

Hey everyone,

I recently finished my first FastAPI project and wanted to get some feedback from people with more experience.

It's just a simple Movie Watchlist API that I built to learn FastAPI and backend fundamentals, so I'm not really looking for feedback on the idea itself. I'm more interested in hearing what you think about the code, the structure, and the way I approached building it.

Repo: https://github.com/BensefiaAbdessamed/MoviesWatchlist

My goal is to become a backend engineer who can build production-ready applications, so I'd really appreciate an honest review. If you were reviewing this as a junior's project, what would you point out? What beginner mistakes do you notice? What would you refactor or do differently? Are there any bad practices that I should stop early?

I'm also a bit unsure about what to learn next. Should I keep improving this project by adding more concepts, or is it better to start a new one? What backend topics do you think are important after getting comfortable with FastAPI? Things like testing, caching, message queues, Docker, CI/CD, design patterns, system design, or anything else?

A couple of friends also suggested that I should learn Django next. Do you think it's worth learning at this stage, or should I keep going deeper with FastAPI and backend fundamentals before jumping to another framework?

Lately I've also been getting interested in RAG systems and MCP integration because AI applications seem to be everywhere now. Do you think it's a good idea to start learning those, or would that just distract me from building a strong backend foundation first?

Feel free to be as critical as you want. I'm posting this because I genuinely want to improve and avoid building bad habits early on.

Thanks to anyone who takes the time to review it or share their advice. I really appreciate it.

r/FastAPI • • 24d ago

Tutorial fastapi-multiauth: accept cookies, bearer tokens and API keys on the same route, with correct OpenAPI docs

32 Upvotes

Hey everyone,

I wanted to share a library I've been working on over the past 3 months: fastapi-multiauth.

My FastAPI apps usually need more than one way to log in: a session cookie for the frontend, a bearer token for scripts, an API key for automation. Getting one route to accept all of them, with Swagger showing it right, takes a lot of boilerplate. The libraries I tried either handled one scheme at a time or pushed their own user model, so I built my own.

You bring the validator: one function (sync or async) that takes a credential and returns your user. Use SQLAlchemy, Redis, an identity provider or a plain dict. No ORM, no database and no user model are imposed.

The library pulls the credential from the request, tries each scheme, and documents them all in OpenAPI.

from fastapi import FastAPI, Security
from fastapi_multiauth import APIKeyCookieAuth, HTTPBearerAuth, MultiAuth, UnauthorizedError


async def validate_token(token: str) -> dict:
    user = await find_user_by_token(token)  # your logic
    if user is None:
        raise UnauthorizedError()
    return user


async def validate_session(user_id: str) -> dict:
    user = await get_user(user_id)  # your logic
    if user is None:
        raise UnauthorizedError()
    return user


bearer = HTTPBearerAuth(validator=validate_token, prefix="user_")
session = APIKeyCookieAuth(name="__Host-session", validator=validate_session, secret_key=SECRET_KEY)
auth = MultiAuth(bearer, session)

app = FastAPI()


@app.get("/me")
async def me(user: dict = Security(auth)):
    return user

That's it. /me accepts a valid bearer token or a valid session cookie, and Swagger lists both.

Some of the more advanced stuff:

  • Signed cookie sessions with key rotation and optional revocation
  • Opaque tokens with prefixes (user_...), hash-only storage and checksums
  • Fail-closed scope checks and step-up auth (fresh(), stepped_up()) for sensitive routes
  • OAuth2/OIDC login helpers: discovery, PKCE, state, code exchange
  • auth_surface(app) to audit which guard protects each route

More examples and recipes: https://fastapi-multiauth.d3vyce.fr/recipes

  • Docs: https://fastapi-multiauth.d3vyce.fr
  • Repo: https://github.com/d3vyce/fastapi-multiauth

Feedback welcome, especially if you've handled multi-scheme auth in FastAPI another way.

r/FastAPI • • Oct 10 '26

Tutorial I built a self-hosted proxy, and the most interesting part turned out to be the FastAPI permissions

0 Upvotes

Coming from Django, the thing I missed most in FastAPI wasn't the ORM or the admin. It was user.has_perm("app.add_thing"): users, groups, per-action permissions, superuser. FastAPI gives you Depends and leaves the rest to you. The libraries I found were either JWT-only or full policy engines like Casbin.

So for my project's admin API I rebuilt Django's model in plain FastAPI + SQLAlchemy, and changed a few things on the way.

What I kept from Django

  • Permissions named resource.action: traffic.view, certificates.add
  • Groups of permissions, plus permissions given to a user directly
  • An is_superuser flag that has everything

The tables are basically Django's auth_group_permissions, auth_user_groups and auth_user_user_permissions.

What I changed

1. Permissions are an enum in code, not rows in a table

Django generates permission rows through migrations. Here the code is what checks them, so the list lives in code and the DB only stores who has what:

class Permission(StrEnum):
    TRAFFIC_VIEW = "traffic.view"
    CERTIFICATES_ADD = "certificates.add"
    ...

2. Each use case declares what it needs, like permission_required

class CreateTrustedNetworkService(BaseUserAuthenticatedService[CreateTrustedNetworkResponse]):
    required_permissions: ClassVar[frozenset[Permission]] = frozenset({Permission.TRUSTED_NETWORKS_ADD})

The base class decodes the JWT, loads the user and their permissions in one UNION query, and returns 403 with what's missing. The route only passes the token and the body.

3. Why not Depends(require(...))

On purpose. Permissions belong to the use case, not to the URL:

  • The escalation check below needs the user's permissions inside the logic anyway. A dependency would just be a second place for the same thing.
  • A service is tested without HTTP, and the check can't be lost by forgetting a dependency on a new route.
  • OpenAPI still knows: every route documents its 403 with the exact permission, e.g. "The user lacks trusted_networks.add."

4. No privilege escalation

This is the part Django warns about in its own docs: if a user can edit users, they can give themselves superuser. Here you can only give what you have:

missing = self.data.permissions - self.permissions
if missing:
    raise HTTPException(403, f"You can't give permissions you don't have: {', '.join(sorted(missing))}.")

This applies to groups, users, adding someone to a group, and even changing another user's password, since otherwise you could just log in as them. (create_group, update_group, create_user)

5. Revoking access takes effect on the next request

Permissions aren't stored in the JWT. They're read on every request, so if you remove someone from a group, their next call fails.

Where it lives

This is the admin API of Proxium, a self-hosted HTTP/SOCKS5 proxy with accounts, quotas and speed limits. Support gets "revoke accounts", accounting gets "view traffic", and neither can touch certificates. One Docker image runs everything, so you can try to break the permissions yourself:

docker run -d --name proxium -p 80:80 -p 8080:8080 -v proxium:/var/lib/proxium \
  -e SUPERUSER_CREATE=true -e SUPERUSER_EMAIL=admin@example.com -e SUPERUSER_PASSWORD=change-me \
  ikoldakov/proxium

If you'd still put it in Depends, change my mind in the comments.

Next on the API side: SSO for the admin over OIDC and an API for merchants. If either sounds fun, the roadmap has the rest, and the code is MIT: https://github.com/koldakov/proxium

r/FastAPI • • Jan 05 '26

Tutorial techniques to make your fastapi backend super fast

42 Upvotes

hey guys, i've compiled some of the most important learnings i've gained up to this point about building a better and faster backend service into an article.

please review it and provide feedback. also, suggest any techniques i have missed, and you've found interesting.x

https://blog.coffeeinc.in/why-your-backend-is-slow-and-what-to-do-about-it-d008d7ae9566

r/FastAPI • • Apr 29 '26

Tutorial A Practical Guide to OpenTelemetry and FastAPI

Thumbnail
signoz.io
24 Upvotes

Hey folks, I recently revamped our article on Implementing OpenTelemetry in FastAPI Projects in a practical manner, which was originally written in 2024 and needed a fresh coat of paint.

The article covers auto-instrumentation, manual spans, visualizing metrics and how observability lets you understand how your web apps behave.
I've also included some advanced tips, such as, selective error tracking, and wrapping dependency functions to capture any operations within the `yield` scope.

If you are on the fence about observability, or have integrated it but don't really how it works, I believe this guide can help you out.

I personally would have benefitted from this writeup in my previous day job, where I worked with FastAPI microservices and learnt how OpenTelemetry worked the hard way.

Any feedback would be much appreciated, did I miss anything, is there scope for improvement? Please let me know. I'm also curious to understand what problems you face with monitoring your FastAPI web apps.

r/FastAPI • • Apr 30 '26

Tutorial What “production-ready FastAPI” actually means beyond making the route work

15 Upvotes

A lot of beginner FastAPI projects stop at:

u/app.post("/login")
def login():
    ...

But in real apps, “it works” is not the same as “it’s safe to ship.”

Some things I think every FastAPI route should be checked for:

  • Does the route verify the current user owns the resource?
  • Does it return only safe response fields?
  • Are expired / invalid tokens tested?
  • Are duplicate emails handled properly?
  • Are async DB sessions used correctly?
  • Are errors consistent and not leaking internals?
  • Are tests covering failure cases, not only happy paths?

The biggest jump for me was realizing that backend quality is mostly about edge cases.

Curious what other FastAPI devs here check before shipping a route?