r/FastAPI • • Apr 03 '22

Question Manage background activity

3 Upvotes

Hey guys.

I am creating an FastAPI application that is collecting user data in the background 24/7 and saving it to the DB.

I was wondering:

How would I go about implementing something like this in a multi-worker environemnt? Because I don't want the data collection task to run in every process, but I also need to access the data throughout the API.


r/FastAPI • • Sep 18 '21

Question [HELP] FastAPI Error Handling : Need to handle Primary Key and Unique Key Violations but the Code never runs the Exception Handling part

Thumbnail
stackoverflow.com
3 Upvotes

r/FastAPI • • Sep 28 '21

Tutorial Build a Blockchain with Python + FastAPI

Thumbnail
youtu.be
3 Upvotes

r/FastAPI • • Dec 14 '20

Question Starting with FastAPI and vanilla Bootstrap CRUD

3 Upvotes

Good day all. I have been playing around with FastAPI this past week and a half. So I am able to make the normal API backend component work. However I now want to plug in the normal bootstrap front end using Javascript for instance..and just make a normal crud using bootstrap form and posting to backend. For instance normal - create/update/delete/read....."students/employees" models or examples you get on web. Does anyone have a working example of posting HTML forms to FastAPI backend....would really appreciate it....thanks in advance


r/FastAPI • • Mar 01 '26

Question Cerchi qualcuno con cui sviluppare?

0 Upvotes

Ciao ragazzi, per risolvere un problema concreto, cioè noi programmatori che magari molte volte non riusciamo a trovare persone interessate a collaborare con noi, ho sviluppato da zero una piattaforma concreta che risolve questo problema.

www.codekhub.it

È un social per programmare, dove puoi creare progetti, invitare persone, recensioni, matchmaking con programmatori etc.

La piattaforma è già online mi farebbe un sacco piacere sapere cosa ne pensate. Si sono già iscritte una decina di persone.


r/FastAPI • • Apr 08 '22

Question Generic OIDC providers with FastAPI

3 Upvotes

Hi guys, is there a package in FastAPI that supports all generic OpenID connect providers? i've been trying to use AuthenticationX but the tutorial isn't explanatory enough. can i get recommendations?


r/FastAPI • • Jul 11 '26

Question Where to start?

3 Upvotes

Hi there! I'm an incoming 2nd year computer engineering student who wants to learn web development for microcontroller UI. However, I don't know where to start. I already know how to program in Python and some basic web requirements like HTML and CSS, but I am stuck whether I should learn JavaScript next or go straight to FastAPI. Thank you for reading this post. Any input would be appreciated.


r/FastAPI • • Feb 23 '25

Tutorial Alternative to FastAPI for serving AI workflows? No infra, just API?

16 Upvotes

I’ve been using FastAPI to serve AI models and workflows, but I’ve been wondering....is there a way to skip the whole API server setup entirely?

Like, what if I just define my AI function, and it instantly behaves like an API without writing a FastAPI app, handling requests, or deploying anything?

I developed an approach where you can run an AI pipeline inside a Jupyter Notebook, and instead of setting up FastAPI, it auto-generates an OpenAI-style API. No need to deal with CORS, async handling, or managing infra....just write your function, and it’s callable remotely.

Has anyone tried something similar? Curious if anyone has seen a different way to serve AI workflows without manually building an API layer.

https://github.com/epuerta9/whisk

Tutorial:
https://www.youtube.com/watch?v=lNa-w114Ujo


r/FastAPI • • May 08 '25

Question I'm a beginner

7 Upvotes

i dont have any experience with backend can anyone tell me resources to learn from scratch to advanced(to understand the logic behind that as i dont have any backend knowledge)


r/FastAPI • • Jul 29 '24

Question App with large user base

7 Upvotes

Hi, has anybody here build an app with a large user base? And how is it going? Are your servers expensive?

Thanks for the insights.


r/FastAPI • • Jun 17 '23

Announcement Reddit Blackout: Should we continue to participate?

17 Upvotes

Hey y'all! We've been locked for the better part of the week after running a poll and finding that the community believed this was a worthwhile cause.

Figured this would be a good time to repoll and gauge how the community felt moving forward things should be handled. Happy to abide by whatever we decide!

Upvote one of the three comments I made below to either:

Also happy to hear other ideas on this thread in the meantime if any others exist!

EDIT: Gonna close this poll come Tuesday evening so we catch all the weekend browsers and then the weekday reddit-at-work-ers for a good chunk of time each.


r/FastAPI • • Jul 10 '21

Tutorial FastAPI - Modern web framework for building APIs with Python in minutes

Thumbnail
youtube.com
12 Upvotes

r/FastAPI • • Apr 11 '25

Question I am making an api project and i want some help

8 Upvotes

As the title says i am making an api project and it is showing no errors in VS code but i cannot seem to run my api. I have been stuck on this for 3-4 days and cannot seem to make it right hence, the reason for this post. I think it has something to do with a database if someone is willing to help a newbie drop a text and i can show you my code and files. Thank you.


r/FastAPI • • Jun 01 '23

pip package FastKafka 0.7.0 adds Windows support

8 Upvotes

FastKafka is a powerful and easy-to-use Python library for building asynchronous web services that interact with Kafka topics. Built on top of Pydantic, AIOKafka and AsyncAPI, FastKafka simplifies the process of writing producers and consumers for Kafka topics and automatically generates documentation for such microservices.
This release brings Windows support, multiple cluster configurations and more, all done as per your feedback :D Take a look, join us on Discord, check out FastKafka on GitHub and let us know how to make it better.


r/FastAPI • • May 03 '22

feedback request FastyAPI.. a fastapi stack boilerplate for scaling.

13 Upvotes

Hello reddit! im currently working on FastyAPI a stack boilerplate for FastAPI.

stack boilerplate?

Exactly!, the idea is to provide boilerplate code and a backend stack architecture that scales!

the stack :

  • Nginx

  • Gunicorn with uvicorn workers

  • FastAPI

  • Motor

  • MongoDB with sharding

  • Redis

  • Celery (optional.)

  • Flower (optional.)

  • Docker

the boilerplate (no subfolders. a naming convention to organise folders.) :

crud

  • dependencies

  • helpers

  • models

  • routers

aswell as a CLI to configure the boilerplate with premade repetitive code.

FastyAPI should be Clone to go with absolutely no bloat.

the project still needs to mature but your feedback is very much appreciated

if you find this somewhat interesting, please consider giving us a star on github


r/FastAPI • • Apr 15 '26

feedback request Alternative API for all music streaming platforms

Thumbnail
reddit.com
0 Upvotes

r/FastAPI • • Oct 29 '25

Hosting and deployment Deployed FastAPI + MongoDB to Vercel. Facing some MongoDB connection issues

0 Upvotes

Hi everyone. This is my first time working with FastAPI + MongoDB and deploying it to Vercel. From the time I first deployed, I got some errors, like loop even errors, and connection errors. I sometimes get this error:

```

❌ Unhandled exception: Cannot use MongoClient after close

```

I get this error sometimes in some APIs. Reloading the page usually fixes it.

Now, here's the main issue I'm facing. The Frontend (built with NextJS) is calling a lot of APIs. Some of them are working and displaying content from the DB. While some APIs aren't working at all. I checked the deployment logs, and I can't seem to find calls to those APIs.

I did some research, asked AI. My intuition says I messed something up big time in my code, especially in the database setup part I guess. Vercel's serverless environment is causing issues with my async await calls and mongoDB setup.

What's weird is that those API calls were working even a few hours ago. But now it's not working at all. The APIs are working themselves because I can test from Swagger. Not sure what to do about this.

This is my session.py file

```

from motor.motor_asyncio import AsyncIOMotorClient
from beanie import init_beanie
from app.core.config import settings
import asyncio


mongodb_client = None
_beanie_initialized = False
_client_loop = None  # Track which loop the client belongs to

async def init_db():
    """Initialize MongoDB connection safely for serverless."""
    global mongodb_client, _beanie_initialized, _client_loop

    loop = asyncio.get_running_loop()

    # If the loop has changed or the client is None, re-init
    if mongodb_client is None or _client_loop != loop:
        if mongodb_client:
            try:
                mongodb_client.close()
            except Exception:
                pass

        mongodb_client = AsyncIOMotorClient(
            settings.MONGODB_URI,
            maxPoolSize=5,
            minPoolSize=1,
            serverSelectionTimeoutMS=5000,
            connect=False,  # ✅ don't force connection here
        )
        _client_loop = loop
        _beanie_initialized = False

    if not _beanie_initialized:
      # Model imports

      await init_beanie(
            database=mongodb_client.get_default_database(),
            document_models=[ # Models]
      )

      _beanie_initialized = True
        print("✅ MongoDB connected and Beanie initialized")

async def get_db():
    """Ensure DB is ready for each request."""
    await init_db()

```

In the route files, I used this in all aync functions as a parameter: _: None = Depends(get_db)

async def do_work(
    _: None = Depends(get_db))

Any help is appreciated.


r/FastAPI • • May 08 '26

Other Skopx - AI analytics API connecting 50+ data sources

Thumbnail
skopx.com
0 Upvotes

r/FastAPI • • Nov 12 '21

Question How to distinguish the parameters between the subdependencies of the same type?

0 Upvotes

I have defined the following dependencies:

class RelativeDeltaParams(BaseModel):
    years: int = 0
    months: int = 0
    weeks: int = 0
    days: int = 0

class DateBuffer(BaseModel):
    backward: RelativeDeltaParams = Depends(RelativeDeltaParams)
    forward: RelativeDeltaParams = Depends(RelativeDeltaParams)

Is it possible to distinguish between backward.years and forward.years?


r/FastAPI • • Dec 07 '21

Tutorial Why we choose FastAPI over Flask for building ML applications

Thumbnail
milvus.io
4 Upvotes

r/FastAPI • • Sep 24 '23

Question Send a List of JSON strings and a list of images to fastapi using aiohttp multipart writer.

0 Upvotes

The endpoint works correctly in the swagger UI, I just cant seem to get the aiohttp part right.

I had it set up to process a list of JSON strings and a single image but wanted to expand it to a list of images.

Here is the exception:

Traceback (most recent call last):
  File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/aiohttp/multipart.py", line 798, in append
    payload = get_payload(obj, headers=headers)
  File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/aiohttp/payload.py", line 71, in get_payload
    return PAYLOAD_REGISTRY.get(data, *args, **kwargs)
  File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/aiohttp/payload.py", line 118, in get
    raise LookupError()
aiohttp.payload.LookupError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/zmml_eventproc", line 178, in <module>
    detections = loop.run_until_complete(main())
  File "uvloop/loop.pyx", line 1517, in uvloop.loop.Loop.run_until_complete
  File "/usr/local/bin/zmml_eventproc", line 158, in main
    return await zm_client.detect(eid=eid, mid=g.mid)
  File "/opt/zm_ml/src/zm_ml/Client/main.py", line 1000, in detect
    part = mpwriter.append(
  File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/aiohttp/multipart.py", line 800, in append
    raise TypeError("Cannot create payload from %r" % obj)
TypeError: Cannot create payload from [b'\xff\xd8\xff\xfe\x00\x11Lavc58.134.100\x00\xff\xdb\x00C\x00\x08\x14\x14\x17\x14\x17\x1b\x1b\x1b\x1b\x1b\x1b \x1e !!!    !!!$$$***$$$!!$$((**./.++*+//222<<99FFHVVg\xff\xc4\x00\xb6\x00\x00\x02\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x03\x06\x02\x05\x01\x00\x07\x08\x01\x00\x03\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x10\x00\x01\x03\x02\x03\x05\x04\x07\x05\x05\x05\x07\x04\x00\x04\x07\x01\x00\x02\x11\x03!\x12A1Qaq"\x042\x81\x91\x13\xb1R\xa1\x05B\xd1\xc1\xe1#\x14rb\x82\xf03\xf1\x92\xb2\xa2SC\x15\xd2\x93T4$\x06...........']

writer

Here is the writer code:

            with aiohttp.MultipartWriter("form-data") as mpwriter:
                part = mpwriter.append_json(
                    models_json,
                    {"Content-Type": "application/json"},
                )
                part.set_content_disposition("form-data", name="hints_model")


                images = []
                #image = ('file', image)
                images.append(image)
                part = mpwriter.append(
                    images,
                    {"Content-Type": "image/jpeg"},
                )
                part.set_content_disposition(
                    "form-data", name="images", filename=image_name
                )
                _perf = perf_counter()
                r: aiohttp.ClientResponse
                session: aiohttp.ClientSession = g.api.async_session
                async with session.post(
                    url,
                    data=mpwriter,
                    timeout=aiohttp.ClientTimeout(total=30.0),
                    headers={
                        "Authorization": f"Bearer {ml_token}",
                    },
                ) as r:
                    status = r.status
                    if status == 200:
                        if r.content_type == "application/json":
                            reply = await r.json()
                        else:
                            logger.error(
                                f"{lp} Route '{route.name}' returned a non-json response! \n{r}"
                            )
                    else:
                        logger.error(
                            f"{lp}route '{route.name}' returned ERROR status {status} \n{r}"

Receiver

How the endpoint is defined:

@app.post(
    "/detect/group",
    summary="Detect objects in images using a set of threaded models referenced by name/UUID",
)
async def group_detect(
    user_obj = Depends(verify_token),
    hints_model: List[str] = Body(
        ...,
        description="Model names/UUIDs",
        example="yolov4, 97acd7d4-270c-4667-9d56-910e1510e8e8, yolov7 tiny",

    ),
    images: List[UploadFile] = File(..., description="Images to run the ML models on"),

):

r/FastAPI • • Nov 10 '22

Tutorial What is CI/CD? DIY With FastAPI, AWS, and Semaphore

Thumbnail
semaphoreci.com
4 Upvotes

r/FastAPI • • Dec 09 '22

Question Not showing list?

0 Upvotes

@.get("/") async def read_root():

# houses = json.load(open("data.json"))["houses"]["house"]

# return houses[0]["id"]

houses = json.load(open("data.json"))["houses"]["house"]

for house in houses:

return house["id"]

When I run the commented code, I receive "3070", which is working as intended, however when I try to loop it in the non-commented code, I also receive "3070" instead of a list of ids.

Can't figure this one out, thanks for the help :)


r/FastAPI • • Jan 28 '23

pip package FastAPI common response wrappers

4 Upvotes

Hello everyone! I built a new library to give a standard solution on "generic response wrapper" and "response wrapper in api docs".

https://github.com/acwazz/fastapi-responseschema

This package extends the FastAPI response model schema allowing you to have a common response wrapper via a fastapi.routing.APIRoute.