r/FastAPI • • Mar 29 '25

Question "Python + MongoDB Challenge: Optimize This Cache Manager for a Twitter-Like Timeline – Who’s Up for It?"

9 Upvotes

Hey r/FastAPI folks! I’m building a FastAPI app with MongoDB as the backend (no Redis, all NoSQL vibes) for a Twitter-like platform—think users, posts, follows, and timelines. I’ve got a MongoDBCacheManager to handle caching and a solid MongoDB setup with indexes, but I’m curious: how would you optimize it for complex reads like a user’s timeline (posts from followed users with profiles)? Here’s a snippet of my MongoDBCacheManager (singleton, async, TTL indexes):

from motor.motor_asyncio import AsyncIOMotorClient
from datetime import datetime

class MongoDBCacheManager:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.client = AsyncIOMotorClient("mongodb://localhost:27017")
        self.db = self.client["my_app"]
        self.post_cache = self.db["post_cache"]

    async def get_post(self, post_id: int):
        result = await self.post_cache.find_one({"post_id": post_id})
        return result["data"] if result else None

    async def set_post(self, post_id: int, post_data: dict):
        await self.post_cache.update_one(
            {"post_id": post_id},
            {"$set": {"post_id": post_id, "data": post_data, "created_at": datetime.utcnow()}},
            upsert=True
        )

And my MongoDB indexes setup (from app/db/mongodb.py):

async def _create_posts_indexes(db):
    posts = db["posts"]
    await posts.create_index([("author_id", 1), ("created_at", -1)], background=True)
    await posts.create_index([("content", "text")], background=True)

The Challenge: Say a user follows 500 people, and I need their timeline—latest 20 posts from those they follow, with author usernames and avatars. Right now, I’d: Fetch following IDs from a follows collection.

Query posts with {"author_id": {"$in": following}}.

Maybe use $lookup to grab user data, or hit user_cache.

This works, but complex reads like this are MongoDB’s weak spot (no joins!). I’ve heard about denormalization, precomputed timelines, and WiredTiger caching. My cache manager helps, but it’s post-by-post, not timeline-ready. Your Task:
How would you tweak this code to make timeline reads blazing fast?

Bonus: Suggest a Python + MongoDB trick to handle 1M+ follows without choking.

Show off your Python and MongoDB chops—best ideas get my upvote! Bonus points if you’ve used FastAPI or tackled social app scaling before.


r/FastAPI • • Feb 11 '25

Question Having troubles of doing stream responses using the OPENAI api

3 Upvotes
from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from data_models.Messages import Messages
from completion_providers.completion_instances import (
    client_anthropic,
    client_openai,
    client_google,
    client_cohere,
    client_mistral,
)
from data_models.Messages import Messages


completion_router = APIRouter(prefix="/get_completion")


@completion_router.post("/openai")
async def get_completion(
    request: Messages, model: str = "default", stream: bool = False
):
    try:
        if stream:
            return StreamingResponse(
                 client_openai.get_completion_stream(
                    messages=request.messages, model=model
                ),
                media_type="application/json", 
            )
        else:
            return client_openai.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}


@completion_router.post("/anthropic")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_anthropic.get_completion(
                messages=request.messages
            )
        else:
            return client_anthropic.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}


@completion_router.post("/google")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_google.get_completion(messages=request.messages)
        else:
            return client_google.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}


@completion_router.post("/cohere")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_cohere.get_completion(messages=request.messages)
        else:
            return client_cohere.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}


@completion_router.post("/mistral")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_mistral.get_completion(
                messages=request.messages
            )
        else:
            return client_mistral.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}


from fastapi import APIRouter
from fastapi.responses import StreamingResponse
from data_models.Messages import Messages
from completion_providers.completion_instances import (
    client_anthropic,
    client_openai,
    client_google,
    client_cohere,
    client_mistral,
)
from data_models.Messages import Messages



completion_router = APIRouter(prefix="/get_completion")



@completion_router.post("/openai")
async def get_completion(
    request: Messages, model: str = "default", stream: bool = False
):
    try:
        if stream:
            return StreamingResponse(
                 client_openai.get_completion_stream(
                    messages=request.messages, model=model
                ),
                media_type="application/json", 
            )
        else:
            return client_openai.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}



@completion_router.post("/anthropic")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_anthropic.get_completion(
                messages=request.messages
            )
        else:
            return client_anthropic.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}



@completion_router.post("/google")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_google.get_completion(messages=request.messages)
        else:
            return client_google.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}



@completion_router.post("/cohere")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_cohere.get_completion(messages=request.messages)
        else:
            return client_cohere.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}



@completion_router.post("/mistral")
def get_completion(request: Messages, model: str = "default"):
    print(list(request.messages))
    try:
        if model != "default":
            return client_mistral.get_completion(
                messages=request.messages
            )
        else:
            return client_mistral.get_completion(
                messages=request.messages, model=model
            )
    except Exception as e:
        return {"error": str(e)}





import json
from openai import OpenAI
from data_models.Messages import Messages, Message
import logging


class OpenAIClient:
    client = None
    system_message = Message(
        role="developer", content="You are a helpful assistant"
    )

    def __init__(self, api_key):
        self.client = OpenAI(api_key=api_key)

    def get_completion(
        self, messages: Messages, model: str, temperature: int = 0
    ):
        if len(messages) == 0:
            return "Error: Empty messages"
        print([self.system_message, *messages])
        try:
            selected_model = (
                model if model != "default" else "gpt-3.5-turbo-16k"
            )
            response = self.client.chat.completions.create(
                model=selected_model,
                temperature=temperature,
                messages=[self.system_message, *messages],
            )
            return {
                "role": "assistant",
                "content": response.choices[0].message.content,
            }
        except Exception as e:
            logging.error(f"Error: {e}")
            return "Error: Unable to connect to OpenAI API"

    async def get_completion_stream(self, messages: Messages, model: str, temperature: int = 0):
        if len(messages) == 0:
            yield json.dumps({"error": "Empty messages"})
            return
        try:
            selected_model = model if model != "default" else "gpt-3.5-turbo-16k"
            stream = self.client.chat.completions.create(
                model=selected_model,
                temperature=temperature,
                messages=[self.system_message, *messages],
                stream=True,
            )
            async for chunk in stream:
                choices = chunk.get("choices")
                if choices and len(choices) > 0:
                    delta = choices[0].get("delta", {})
                    content = delta.get("content")
                    if content:
                        yield json.dumps({"role": "assistant", "content": content})
        except Exception as e:
            logging.error(f"Error: {e}")
            yield json.dumps({"error": "Unable to connect to OpenAI API"})


import json
from openai import OpenAI
from data_models.Messages import Messages, Message
import logging



class OpenAIClient:
    client = None
    system_message = Message(
        role="developer", content="You are a helpful assistant"
    )


    def __init__(self, api_key):
        self.client = OpenAI(api_key=api_key)


    def get_completion(
        self, messages: Messages, model: str, temperature: int = 0
    ):
        if len(messages) == 0:
            return "Error: Empty messages"
        print([self.system_message, *messages])
        try:
            selected_model = (
                model if model != "default" else "gpt-3.5-turbo-16k"
            )
            response = self.client.chat.completions.create(
                model=selected_model,
                temperature=temperature,
                messages=[self.system_message, *messages],
            )
            return {
                "role": "assistant",
                "content": response.choices[0].message.content,
            }
        except Exception as e:
            logging.error(f"Error: {e}")
            return "Error: Unable to connect to OpenAI API"


    async def get_completion_stream(self, messages: Messages, model: str, temperature: int = 0):
        if len(messages) == 0:
            yield json.dumps({"error": "Empty messages"})
            return
        try:
            selected_model = model if model != "default" else "gpt-3.5-turbo-16k"
            stream = self.client.chat.completions.create(
                model=selected_model,
                temperature=temperature,
                messages=[self.system_message, *messages],
                stream=True,
            )
            async for chunk in stream:
                choices = chunk.get("choices")
                if choices and len(choices) > 0:
                    delta = choices[0].get("delta", {})
                    content = delta.get("content")
                    if content:
                        yield json.dumps({"role": "assistant", "content": content})
        except Exception as e:
            logging.error(f"Error: {e}")
            yield json.dumps({"error": "Unable to connect to OpenAI API"})

This returns INFO: Application startup complete.

INFO: 127.0.0.1:49622 - "POST /get_completion/openai?model=default&stream=true HTTP/1.1" 200 OK

ERROR:root:Error: 'async for' requires an object with __aiter__ method, got Stream

WARNING: StatReload detected changes in 'completion_providers/openai_completion.py'. Reloading...

INFO: Shutting down

and is driving me insane


r/FastAPI • • Sep 07 '24

Tutorial How to Add JWT Authentication in FastAPI (Python) | Easy Tutorial

Thumbnail
youtube.com
3 Upvotes

r/FastAPI • • Oct 29 '25

Tutorial 18.Python | FastAPI | Clean Architecture | Dependency Injection.

Thumbnail
youtu.be
3 Upvotes

🚀 Master FastAPI with Clean Architecture! In this introductory video, we'll kickstart your journey into building robust and scalable APIs using FastAPI and the principles of Clean Architecture. If you're looking to create maintainable, testable, and future-proof web services, this tutorial is for you!


r/FastAPI • • Jan 25 '26

Other [side project] fastapi + chromadb + openrouter: local journal chat app for more prespectives

Post image
3 Upvotes

[why]

- needed perspective on my state of mind
- exploring alternate paths and ideas to my journal entires

[how]

- little time on weekend
- opencode + glm
- some time designing workflow

GitHub: https://github.com/gamedevCloudy/reorlike


r/FastAPI • • May 26 '26

Hosting and deployment I got tired of formatting enterprise invoices by hand, so I built a Python API to automate it.

0 Upvotes

Disclosure: I am the founder of this API.

I’ve been working on a project to solve a problem I kept hitting: generating professional, calculated PDF invoices without the headache of manual formatting. I wanted to share the process of building and monetizing this as a SaaS tool using Python, Render, and RapidAPI.

The Technical Challenge: Getting complex tables, tax calculations, and dynamic line items to look enterprise-grade while keeping the API stateless was the biggest hurdle. I had to ensure the HTML-to-PDF rendering was fast enough to be usable as a real-time service.

The Monetization Pipeline: I wanted to see if I could build a complete end-to-end monetization flow. I integrated tiered pricing and overage limits to ensure the API stays sustainable as it scales.

I’m looking for feedback from the SaaS community on the integration experience—specifically, if the JSON payload structure is intuitive enough for a billing flow. You can test the endpoint and documentation here: https://rapidapi.com/frenzersteven1/api/enterprise-pdf-invoice-generator

I'm curious to hear: for those of you who have built billing-related tools, what is the #1 feature you wish you had implemented in your MVP?


r/FastAPI • • Apr 15 '25

Question Transitioning from NestJS to Python (FastAPI, ML, Data Engineering): Is My Decision Right for the Long Run?

12 Upvotes

Hi everyone, I’m currently working with NestJS, but I’ve been seriously considering transitioning into Python with FastAPI, SQL, microservices, Docker, Kubernetes, GCP, data engineering, and machine learning. I want to know—am I making the right choice?

Here’s some context:

The Node.js ecosystem is extremely saturated. I feel like just being good at Node.js alone won’t get me a high-paying job at a great company—especially not at the level of a FANG or top-tier product-based company—even with 2 years of experience. I don’t want to end up being forced into full-stack development either, which often happens with Node.js roles.

I want to learn something that makes me stand out—something unique that very few people in my hometown know. My dream is to eventually work in Japan or Europe, where the demand is high and talent is scarce. Whether it’s in a startup or a big product-based company in domains like banking, fintech, or healthcare—I want to move beyond just backend and become someone who builds powerful systems using cutting-edge tools.

I believe Python is a quicker path for me than Java/Spring Boot, which could take years to master. Python feels more practical and within reach for areas like data engineering, ML, backend with FastAPI, etc.

Today is April 15, 2025. I want to know the reality—am I likely to succeed in this path in the coming years, or am I chasing something unrealistic? Based on your experience, is this vision practical and achievable?

I want to build something big in life—something meaningful. And ideally, I want to work in a field where I can also freelance, so that both big and small companies could be potential clients/employers.

Please share honest and realistic insights. Thanks in advance.


r/FastAPI • • Mar 20 '26

pip package There's no good library for managing individual route-level lifecycle in ASGI frameworks — so I built one

8 Upvotes

A few weeks ago I ran into a frustrating situation — I needed to take down one route in a live FastAPI app for maintenance without redeploying the whole service. There was no clean way to do it. I ended up hacking together a flag in the database and checking it manually in the route handler, which felt wrong.

Rate limiting came up as a need around the same time. Since the goal was a single library that manages the full route lifecycle, it made more sense to build it in than to delegate it elsewhere.

The bigger picture is to build a full-fledged library for managing the full lifecycle of your routes or APIs — from the moment they go live to the moment they go down and everything in between.

api-shield is the start of that.

What it does right now

Route Maintenance — Put any route into maintenance mode from a dashboard or CLI without redeploying. You can schedule windows, restrict access to specific environments, or disable a route entirely.

Rate Limiting — Per-route policies with fixed window, sliding window, and token bucket support. Exempt IPs or roles, set burst limits, and resolve tiers dynamically per request. No extra library or external service needed.

Dashboard — A live HTMX dashboard showing route states, audit logs, and rate limit hits. No frontend build step.

CLI — A thin client that talks directly to your running app. Toggle routes, check status, view rate limit hits, and reset limits from the terminal.

Problems it is meant to solve

  • You need a route down right now and a redeploy takes 5 minutes you don't have

  • You want per-route rate limiting without standing up a gateway

  • You have no visibility into what is happening across your routes at runtime

  • You keep writing one-off middleware for things that should be reusable

It is built for ASGI Python frameworks. FastAPI is fully supported today and adapters for other ASGI frameworks are coming.

We just shipped the first real production Python app running on it and it has been stable so far.

pip install api-shield

GitHub: https://github.com/Attakay78/api-shield

Happy to answer questions and very open to feedback on the direction. Bug reports and PRs are welcome — there is a lot more to build here.


r/FastAPI • • Jan 09 '26

Other Production-ready FastAPI starter I wish I had earlier (auth, Stripe, Celery)

0 Upvotes

Hey everyone,

After building multiple FastAPI projects, I realized I was spending the same 1–3 weeks every time on the exact same stuff:

  • JWT auth & user management

  • Stripe subscriptions + webhooks

  • Email flows

  • Background tasks (Celery)

  • Database setup & migrations

  • Deployment boilerplate

So I end up building a production ready FastAPI template that I now reuse for all my projects.

It includes:

  • FastAPI + SQLAlchemy + Alembic

  • JWT auth (email + social-ready)

  • Stripe billling (subscriptions, webhooks)

  • Background jobs with Celery

  • Email infrastructure

  • Docker + deployment setup

The goal isn’t to “teach FastAPI” - it’s for people who already know it and just want to ship faster.

I’ve been using it in real projects and recently cleaned it up into something reusable.
here you can find it: https://fastlaunchapi.dev

what’s the part of fastapi you hate rebuilding the most?


r/FastAPI • • May 05 '26

Hosting and deployment Open-source local-first multi-agent mesh built with FastAPI, React, LM Studio, and SQLite

2 Upvotes

Product name:

Octopus Agents V2.2

Tagline:

A 34-agent local-first AI mesh running on one workstation

Description:

Octopus is an open-source AI agent mesh for local-first software work. It routes tasks across 34 specialized roles, uses LM Studio for local inference, keeps state in SQLite, supports Obsidian memory, and ships with a React operator UI for chat, coworking, code, email, calendar, memory, and system status.

Topics:

Artificial Intelligence, Developer Tools, Open Source, Productivity, GitHub

Website:

https://github.com/tjbmoose09/octopus-v2

Maker comment:

Hey Product Hunt - Tyler here.

I built Octopus because I wanted to test a different shape of agent system: not one model wearing 34 hats, but a local mesh where specialized agents have different roles, model assignments, memory access, and routing boundaries.

V2.2 runs locally by default through LM Studio. The backend is FastAPI, state is SQLite, memory can go to Obsidian, and the UI is a React/Vite operator console with live pipeline logs.

The part I am most interested in is the architecture: 34 roles, 101 wired skills, 37 MCP server registrations, and a quarantined hacker-zone mesh with explicit bridge logging. It is early, weird, and very much for builders who like local AI systems they can inspect.

I would love feedback on the architecture, security boundaries, README clarity, and what would make this easier for another developer to run.


r/FastAPI • • Jul 23 '24

Question S3 server simulation in Python

2 Upvotes

I want to implement S3 server using FastAPI and Python. This is my code for signature validation:

async def verify_signature(request: Request):
    try:
        authorization_header = request.headers.get("Authorization")
        amz_date = request.headers.get("x-amz-date")
        if not authorization_header or not amz_date:
            logging.error("Missing authorization or x-amz-date header")
            return False

        logging.debug(f"\n\n=======================================================\n")
        logging.debug(f"Request URL:\n{request.url}")
        logging.debug(f"Authorization Header:\n{authorization_header}")
        logging.debug(f"x-amz-date:\n{amz_date}")

        auth_parts = authorization_header.split(", ")
        credential_part = auth_parts[0]
        signed_headers_part = auth_parts[1]
        signature_part = auth_parts[2]

        credential_scope = (
            credential_part.split(" ")[1].split("Credential=")[1].split("/")[1:]
        )
        credential_scope = "/".join(credential_scope)

        signed_headers = signed_headers_part.split("SignedHeaders=")[-1].split(";")
        provided_signature = signature_part.split("Signature=")[-1]

        logging.debug(f"Signed Headers:\n{signed_headers}")
        logging.debug(f"Credential Scope:\n{credential_scope}")

        headers_dict = {k.lower(): v for k, v in request.headers.items()}
        sorted_headers = {
            k: headers_dict[k] for k in sorted(headers_dict) if k in signed_headers
        }

        logging.debug(f"Headers Dict:\n{headers_dict}")
        logging.debug(f"Sorted Headers:\n{sorted_headers}")

        canonical_uri = request.url.path
        canonical_querystring = request.url.query
        if False and headers_dict.get("x-amz-content-sha256") == "UNSIGNED-PAYLOAD":
            payload_hash = (
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
            )
        else:
            payload_hash = hashlib.sha256(await request.body()).hexdigest()

        sorted_headers["x-amz-content-sha256"] = payload_hash
        canonical_headers = "".join([f"{k}:{v}\n" for k, v in sorted_headers.items()])

        canonical_request = "\n".join(
            [
                request.method,
                canonical_uri,
                canonical_querystring,
                canonical_headers,
                ";".join(signed_headers),
                payload_hash,
            ]
        )

        logging.debug(f"Canonical Request:\n{canonical_request}")

        string_to_sign = "\n".join(
            [
                ALGORITHM,
                amz_date,
                credential_scope,
                hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
            ]
        )

        logging.debug(f"String to Sign:\n{string_to_sign}")

        date_stamp = credential_scope.split("/")[0]
        signing_key = get_signature_key(
            AWS_SECRET_ACCESS_KEY,
            date_stamp,
            AWS_REGION,
            SERVICE,
        )

        signature = hmac.new(
            signing_key, string_to_sign.encode("utf-8"), hashlib.sha256
        ).hexdigest()

        logging.debug(f"Calculated Signature: {signature}")
        logging.debug(f"Provided Signature: {provided_signature}")

        is_valid = provided_signature == signature
        if not is_valid:
            logging.error("Signatures do not match")
        return is_valid

    except Exception as e:
        logging.error(f"Verification failed: {e}")
        return False

I test with this way:

def test():
    from io import BytesIO

    import boto3

    session = boto3.Session(
        AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION
    )
    client = session.client(
        "s3", endpoint_url=ENDPOINT
    )
    f = BytesIO(b"salam2")
    f.seek(0)
    put_res = client.put_object(Bucket="mybucket", Key="myfile2.txt", Body=f)
    print(put_res)
    get_res = client.get_object(Bucket="mybucket", Key="myfile2.txt")
    print(get_res["Body"].read())
    del_res = client.delete_object(Bucket="mybucket", Key="myfile2.txt")
    print(del_res)

The code works correctly for `GET` and `DELETE` requests. But the calculated signature for `PUT` is not matched.
Any help?


r/FastAPI • • Jan 16 '23

Question Project template without ORM

2 Upvotes

I don't want to use SQLAlchemy or any other ORM, but every project example use it. Can you recommend me a template to use with async postgres database?


r/FastAPI • • May 03 '23

Question I am a beginner who has recently started with fastapi, and I have some questions. Please let me know if you can help. Thank you.

2 Upvotes

I'm studying fastapi with ChatGPT. I am currently studying one-to-many foreign key relationships and would like some advice.

class Post: 
    ...     
    comments = relationship("Comment", back_populates="post")  

class Comment:     
    ...     
    post_id = Column(ForeignKey("post.id"), nullable=False)     
    post = relationsihp("Post", back_populates="comments") 

When there are two existing classes like above

comment = Comment(content=content, post_id=post_id)
session.add(comment)
session.commit()

post = session.query(Post).filter_by(id=post_id).first()
post.comments.append(comment) 

do I need to use every time I register a comment?

ChatGPT says that if I don't do it that way, I won't be able to read

post = session.query(Post).filter_by(id=post_id).first() 
post.comments 

However, even without using

post.comments.append(comment)

I can still read it from the docs. So I'm wondering if ChatGPT is giving me the wrong information or if it's only visible in the docs


r/FastAPI • • Mar 05 '22

Question Job

2 Upvotes

Where to find remote jobs for FasAPI? I have 2 years experience in software development using FastAPI as our backend. But I consider it 1 year experience since because of the selfstudy while using it in work. I'm from Philippines btw.


r/FastAPI • • Sep 18 '21

Question [HELP] FastAPI returning JSON Array, need to convert it into tables but unable to do so because I started web dev 5 days ago it is probably most basic thing yet I can't figure it out yet, maybe someone experienced can help me out?

Thumbnail
stackoverflow.com
0 Upvotes

r/FastAPI • • Mar 29 '21

Question How to handle many-to-many relationships?

2 Upvotes

Hello peps,

I'm building a simple service with fastapi. I'll try to present my problem in the easiest way I can :)

Let's say I have two entities: Person and Animal. The relationship is like "likes", so my dude Mark is a cat person but also loves horses, while Katia is a huge dog fan.

I'm talking about the generic animal, not a particular one, so the "Animals" are reusable... and thank god, since each of them also has a huge photo that weights several megabytes, to show the fluff

I would have something like this

association_table = Table(
'association', Base.metadata,
Column('person_id', String, ForeignKey('people.id')),
Column('animal_id', String, ForeignKey('animals.id'))
)

class Person(Base):
id = Column(String, primary_key = True)
name = Column(String)
animals = relationship("Animal", secondary=association_table, backref="people")

class Animal(Base):
id = Column(String, primary_key = True)
photo = Column(String) # base 64

Don't consider the names or the fact that the primary key is a string, in the real app it all makes sense.

Now, I want an endpoint to GET and POST/PUT a Person. Problem is, how do I handle the relationship?

I would like to allow a List of primary keys (strings in this case) as the input (and then the post function will take care of linking that to the actual animal), and also to get a list of primary keys instead of the whole animal entity, so that I can get something like

{

"id": "...",

"name": "Mark",

"animals": ["cat", "horse"]

}

This way, on my frontend I would download all the animals (or keep a cache, whatever), and then link them to each person as need be, instead of downloading the same cat 100 times because everybody loves cats

I tried something like this

def get(self, db: Session, id: str):
person = db.query(Person).filter(Person.id == id).first()
person.animals = [animal.id for animal in person.animals]

return person

But that fails because of

AttributeError: 'str' object has no attribute '_sa_instance_state'

Because I guess it's doing a type-checking against the sqlalchemy model (not the pydantic one)

def get(self, db: Session, id: str):
person = db.query(Person).filter(Person.id == id).first()
person.likedAnimals = [animal.id for animal in person.animals]

return person

This one "works" in the sense that it actually adds the field, and with pydantic models I can "hide" the original animals... but my understanding is that it's still being downloaded in full, it's just not showing it.

This seems like and extremely basic thing to do and clearly I'm missing something, because I find it hard to implement. Any suggestion will be very welcome!


r/FastAPI • • Jan 18 '26

pip package fastapi-fullstack v0.1.15 released – now with DeepAgents (LangChain's multi-agent framework) + HITL support!

Thumbnail reddit.com
0 Upvotes

r/FastAPI • • Sep 27 '25

feedback request I took a try at Microservices with FastAPI

2 Upvotes

Hello Everyone,

I am a frontend developer hoping for the switch to a backend role, would love to see opinions on this simple project

The project is based the following Video Tutorial Python Microservices, however, for my learning purposes I simply took the requirements and attempted to do it on my own.

The objective

A user uploads a video, and the system will convert the video to MP3 format, and notify the user by email and provide a download link for the file as an MP3 file

You can find my implementation in this Github Repo.

A few things to note about this project:

  • It is simply a uv workspaces to facilitate microservices as packages.

  • Given the first point, I wonder if this is a legit microservices setup. In my experience, usually each service gets its own repository.

  • This also may indicate that teams will probably not be very effective in this workspaces setup.

  • However, for a solo developer, it seems to work pretty well.

I would love to know your thoughts:

  • Genuinely curious, what are your thoughts of this setup? How do you do microservices?

  • I wish to convince my manager or future employers that I could work as backend engineer, is this worthy of demonstration? I realize that I may have more to learn and things to catch up with, and I am willing to put in the work.

Thanks in advanced


r/FastAPI • • Apr 28 '26

Other Benchmarking API agents vs vision agents on the same task - 40x fewer tokens, 44x faster

Post image
2 Upvotes

Hey r/FastAPI! I'm the creator of Reflex, an open-source Python web framework. We just released v0.9 and wanted to share something relevant with this community.

We ran a benchmark comparing two approaches to letting AI agents interact with a web app:

  1. A vision agent (browser/computer use) that screenshots the UI and clicks around

  2. An API agent that calls HTTP endpoints directly

The task for both agents was to find a "Smith" customer with the most orders, accept their pending reviews, and mark their most recent order as delivered. We chose this task since it's similar to automation work a typical tool sees.

The vision agent took 550k tokens and 17 minutes on average, the API agent took 12k tokens and 19.7 seconds. Of course, API agents are faster and more token efficient since they don't need to take screenshots and directly interface with the UI. The problem is many apps don't have APIs for every action, since it takes engineering overhead to build and maintain each separate API codebase.

We built a plugin for Reflex that auto-generates FastAPI-compatible HTTP endpoints from your app's existing event handlers. For example, your app has a button with an on_click handler, the plugin exposes that handler as an endpoint. An agent can call the same function a human click triggers. No separate API to build or maintain.

Reflex compiles to React on the frontend and Python on the backend, with full FastAPI compatibility.

benchmark link: Vision Agents vs API Calls
our repo: reflex-dev/reflex: 🕸️ Web apps in pure Python 🐍


r/FastAPI • • Dec 27 '25

pip package fastapi-fullstack v0.1.10 released – optional SQLModel ORM + Nginx reverse proxy as Traefik alternative!

4 Upvotes

Hey r/FastAPI,

A few days ago I shared the v0.1.6 update here – thanks for the great feedback and stars! For those catching up or new: fastapi-fullstack is an open-source CLI generator (pip install fastapi-fullstack) that creates production-ready full-stack AI/LLM apps with FastAPI backend + optional Next.js 15 frontend. It handles async APIs, auth, databases, AI agents (PydanticAI/LangChain with multi-provider support), 20+ integrations, and now even more flexible production setups.

Key highlight in recent updates (v0.1.9): Optional SQLModel ORM!
SQLModel simplifies SQLAlchemy with built-in Pydantic – perfect for FastAPI, as models are defined once and used everywhere (in DB, API, validation). Less boilerplate, full type-safety, and seamless integration with FastAPI's deps and async sessions.
Still works with Alembic migrations and SQLAdmin panels.
Switch via CLI: --orm sqlmodel (or interactive prompt). A great option for cleaner FastAPI code!

Example from generated code:

from sqlmodel import SQLModel, Field

class User(SQLModel, table=True):

id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)

email: str = Field(max_length=255, unique=True)

is_active: bool = Field(default=True)

Other new stuff in v0.1.10 (and quick recap of 0.1.7-0.1.9):

  • Nginx reverse proxy support as Traefik alternative (modes: included/external/none, with secure configs, WebSocket, TLS, Let's Encrypt)

  • Production .env.prod with validation + no insecure defaults

  • From 0.1.7: Traefik proxy, progressive docs, refactored CLAUDE.md

Full changelog: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template/blob/main/docs/CHANGELOG.md
Repo: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template

FastAPI folks – how does SQLModel fit your workflows? And the Nginx deploy? Any suggestions? Contributions welcome! 🚀

Python


r/FastAPI • • Apr 29 '24

Question Building a Food Ordering System with OpenAI and FastAPI

4 Upvotes

Hey everyone!

I'm currently working on building a food ordering system using OpenAI's AI and FastAPI. In my setup, I use OpenAI to assist with taking orders by passing some context to initiate a chat, like this:

message = [
    {
        "role": "system",
        "content": "You are Elle, a WhatsApp bot for an Indian food restaurant called foodcourt. Your job is to take orders from clients."
    },
    {"role": "system", "content": "Here's a list of our available food items:"},
    {
        "role": "system",
        "content": "1. Butter Chicken - $25 2. Chicken Tikka Masala - $20 3. Tandoori Chicken - $15 4. Chicken Biryani - $30 5. Chicken Korma - $25 6. Chicken Vindaloo - $20 7. Chicken Saag - $20 8. Chicken Jalfrezi - $25 9. Chicken Madras - $20 10. Chicken Tandoori - $15"
    }
]

The AI takes orders pretty well with this context, but I'm struggling to figure out how to store the order details in a database after the AI successfully takes the order.

Has anyone done something similar, or do you have any suggestions on best practices for integrating OpenAI with FastAPI to store order details in a database? I'd love to hear about any tech stack recommendations, specific database solutions, or general tips on implementing this.

Thanks in advance for your insights!


r/FastAPI • • Jun 12 '24

Question Django/DRF and FastApi Open source contribution and adding them to Resume

4 Upvotes

Hello I want to contribute to Django, Django RestFramework OR FastApi projects, But the thing is projects with stars 500 plus are really hard to contribute to and difficult to understand as a beginner, even if I do understand them, I cant think of contributing of new features, I have found projects with less stars like 5,10 or over all small projects they are more beginner friendly, If I Contribute to them will it be a valid pr Also If I make a Pr To project and it gets rejected or nothing happens, should I still add it to me cv under ope n source contributions heading as I Cant find internship in current job market


r/FastAPI • • Oct 13 '25

Hosting and deployment Can I deploy a FastAPI app using Dokploy?

4 Upvotes

Hi everyone

I’m following a course where they deploy a FastAPI app using Render, and in Render they can easily define things like:

  • The build command (for example pip install -r requirements.txt),

  • The start command (for example uvicorn main:app --host 0.0.0.0 --port 8000), and

  • The branch to deploy from.

I’m using Dokploy instead, and I really like it — but I’m not sure how to do the same setup there.
I see options for Dockerfiles, manual deployments, and environments, but what’s the best way to replicate Render’s workflow in Dokploy for a simple FastAPI app?

Should I create a Dockerfile manually, or is there a way to specify build/start commands directly in the web UI?

Any tips, examples, or best practices would be awesome


r/FastAPI • • Jan 04 '26

feedback request Can someone help me to make my resume. It seems my experience is apparently worthless..

Post image
0 Upvotes

I got comments saying my experience don't match and not really good advices. Any guidance please?