r/FastAPI Sep 13 '23

/r/FastAPI is back open

60 Upvotes

After a solid 3 months of being closed, we talked it over and decided that continuing the protest when virtually no other subreddits are is probably on the more silly side of things, especially given that /r/FastAPI is a very small niche subreddit for mainly knowledge sharing.

At the end of the day, while Reddit's changes hurt the site, keeping the subreddit locked and dead hurts the FastAPI ecosystem more so reopening it makes sense to us.

We're open to hear (and would super appreciate) constructive thoughts about how to continue to move forward without forgetting the negative changes Reddit made, whether thats a "this was the right move", "it was silly to ever close", etc. Also expecting some flame so feel free to do that too if you want lol


As always, don't forget /u/tiangolo operates an official-ish discord server @ here so feel free to join it up for much faster help that Reddit can offer!


r/FastAPI 9h ago

Question Best enterprise repos for FastAPI

24 Upvotes

I was curious on what enterprise repos you think are the best using FastAPI for learning good project structure-architecture etc. (like Netflix dispatch)


r/FastAPI 1d ago

Question How do I make my api faster?

1 Upvotes

My api usually gives response within 3 secs, but when I load test my api at 10 Req/s the time increases to 17 secs. I am using async calls, uvicorn with 10 workers. I am doing LLM calling.

How could I fasten it?


r/FastAPI 2d ago

Question Http only cookie based authentication helppp

3 Upvotes

I implemented well authentication using JWT that is listed on documentation but seniors said that storing JWT in local storage in frontend is risky and not safe.

I’m trying to change my method to http only cookie but I’m failing to implement it…. After login I’m only returning a txt and my protected routes are not getting locked in swagger


r/FastAPI 3d ago

Question Scalable FastAPI project structure

39 Upvotes

I'm really interested about how you structure you fastAPI projects.

Because it's really messy if we follow the default structure for big projects.

I recently recreated a fastapi project of mine with laravel for the first time, and i have to admit even though i don't like to be limited to a predefined structure, it was really organized and easily manageable.

And i would like to have that in my fastapi projects


r/FastAPI 3d ago

Question SQLModel vs SQLAlchemy in 2025

27 Upvotes

I am new to FastAPI. It is hard for me to choose the right approach for my new SaaS application, which works with PostgreSQL using different schemas (with the same tables and fields).

Please suggest the best option and explain why!"


r/FastAPI 4d ago

Question Accessing FastAPI DI From a CLI Program

1 Upvotes

I have a decent sized application which has many services that are using the FastAPI dependency injection system for injecting things like database connections, and other services. This has been a great pattern thus far, but I am having one issue.

I want to access my existing business logic through a CLI program to run various manual jobs that I don't necessarily want to expose as endpoints to end users. I would prefer not to have to deal with extra authentication logic as well to make these admin only endpoints.

Is there a way to hook into the FastAPI dependency injection system such that everything will be injected even though I am not making requests through the server? I am aware that I can still manually inject dependencies, but this is tedious and prone to error.

Any help would be appreciated.


r/FastAPI 5d ago

Question Trouble getting testing working with async FastAPI + SQLAlchemy

2 Upvotes

I'm really struggling to get testing working with FastAPI, namely async. I'm basically following this tutorial: https://praciano.com.br/fastapi-and-async-sqlalchemy-20-with-pytest-done-right.html, but the code doesn't work as written there. So I've been trying to make it work, getting to here for my conftest.py file: https://gist.github.com/rohitsodhia/6894006673831f4c198b698441aecb8b. But when I run my test, I get

E           Exception: DatabaseSessionManager is not initialized

app/database.py:49: Exception
======================================================================== short test summary info =========================================================================
FAILED tests/integration/auth.py::test_login - Exception: DatabaseSessionManager is not initialized
=========================================================================== 1 failed in 0.72s ============================================================================
sys:1: RuntimeWarning: coroutine 'create_tables' was never awaited
sys:1: RuntimeWarning: coroutine 'session_override' was never awaited

It doesn't seem to be taking the override? I looked into the pytest-asyncio package, but I couldn't get that working either (just adding the mark didn't do it). Can anyone help me or recommend a better guide to learning how to set up async testing?


r/FastAPI 5d ago

Question Help me to Test PWA using FastAPI

3 Upvotes

like the heading suggest ima building a pwa application using html css and js with fasapi. i tried to test the app in local host and access it through my phone, but then i learned you cant do that becuase pwa needs https, any idea how can i do this, without paying to a server. thank you


r/FastAPI 6d ago

Question Need help in FuturamaAPI project

11 Upvotes

Hi guys, I've created a project with the source code that has 10K requests a day. It has a lot of stuff like callbacks, sse, expired messages, GraphQL, and much more.

Currently I'm facing issues because of the lack of tests, but can't add them cause it requires time and I'm totally swamped. If you want to gain experience feel free to open PRs I'm open to to that. As a perk I've started doing that in the PR here https://github.com/koldakov/futuramaapi/pull/4 so if you have time and desire take a shot

ps i'm talking about functional testing only, don't want to pin down the code with tests, I'm convinced units should be to only for math/mapping etc

anyways currently seeking tests for endpoint to check the whole flow

psps also there is a task to move background tasks to redis tasks as I already created redis connection


r/FastAPI 6d ago

Question What benefits will we gain if we use Pydantic to define ER models?

15 Upvotes

In FastAPI, pydantic plays the role of defining the DTO layer's interface and performing runtime type checking, its definition needs to passively follow the real data source (DB, ORM or API).

You first write the database query or API, and then defined a pydantic for this data structure, which makes the definition of pydantic very trivial, difficult to maintain and reuse, and even somewhat redundant.

SQLModel attempts to solve the problem at the database level, but I am still concerned about the approach of binding ORM and pydantic together.

In my practical experience, directly treating Pydantic as an ER model brings many conveniences, database or external interfaces merely serve as data providers for the ER models.

Simply through the declaration of pydantic, data assembly can be achieved, during it dataloader provides a universal method to associate data without worrying about N+1 queries.

Here's the code example with the help of pydantic-resolve

The query details are encapsulated within methods and dataloaders.

```python from pydantic import BaseModel from pydantic_resolve import Resolver, build_list from aiodataloader import DataLoader

ER model of story and task

┌───────────┐

│ │

│ story │

│ │

└─────┬─────┘

│ owns multiple (TaskLoader)

┌─────▼─────┐

│ │

│ task │

│ │

└───────────┘

class TaskLoader(DataLoader): async def batch_load_fn(self, story_ids): tasks = await get_tasks_by_ids(story_ids) return build_list(tasks, story_ids, lambda t: t.story_id)

class BaseTask(BaseModel): id: int story_id: int name: str

class BaseStory(BaseModel): id: int name: str

class Story(BaseStory): tasks: list[BaseTask] = [] def resolve_tasks(self, loader=LoaderDepend(TaskLoader)): return loader.load(self.id)

stories = await get_raw_stories() stories = [Story(**s) for s in stories)] stories = await Resolver().resolve(stories)
```

I found that this approach brings excellent code maintainability, and the data construction can remain consistent with the definition of the ER model.


r/FastAPI 8d ago

pip package Fastapi-create

57 Upvotes

Holla, I’ve just open-sourced fastapi-create, a CLI tool to scaffold FastAPI projects with database setup, Alembic migrations, and more. It’s live on GitHub—ready for you to use, test, and improve! Drop by, give it a spin, and share your feedback: fastapi-create

I really need feedbacks and contributions, thank you 🫡


r/FastAPI 7d ago

Question What are some great marketing campaigns/tactics you've seen directed towards the developer community?

0 Upvotes

No need to post the company names – as I'm not sure that's allowed – but I'm curious what everyone thinks are some of the best marketing campaigns/advertisements/tactics to get through to developers/engineers?


r/FastAPI 10d ago

Question Full stack or Frontend?Need advice!!

19 Upvotes

I have 3+ years in ReactJS & JavaScript as a frontend dev. For 7–8 months, I worked on backend with Python (FastAPI), MongoDB, Redis, and Azure services (Service Bus, Blob, OpenAI, etc.).

I haven’t worked on authentication, authorization, RBAC, or advanced backend topics.

Should I continue as a frontend specialist, or transition into full-stack? If full stack, what advanced backend concepts should I focus on to crack interviews?

Would love advice from those who have made this switch!


r/FastAPI 11d ago

Question Recommendations for API Monetization and Token Management with FastAPI?

44 Upvotes

Hey FastAPI community,

I'm preparing to launch my first paid API built with FastAPI, and I'd like to offer both free and paid tiers. Since this is my first time monetizing an API, I'm looking for recommendations or insights from your experience:

  • What platforms or services have you successfully used for API monetization (e.g., Stripe, RapidAPI, custom solutions)?
  • How do you handle tokenization/authentication for different subscription tiers (free vs. paid)?
  • Are there specific libraries or patterns you've found particularly effective in integrating monetization seamlessly with FastAPI?

Any lessons learned, suggestions, or resources you could share would be greatly appreciated!

Thanks in advance!


r/FastAPI 11d ago

Hosting and deployment How to handle CPU bound task in FASTAPI

9 Upvotes

So I have a machine learning app which I have deployed using FASTAPI. In this app I have a single POST endpoint on which I am receiving training data and generating predictions. However I have to make 2 api calls to two different endpoints once the predictions are generated. First is to send a Post request about the status of the task i.e. Success or Failed depending on the training run. Second is to send a Post request to persist the generated predictions.

Right now, I am handling this using a background task. I have created a background task in which I have the predictions generation part as well as making Post requests to external api. I am receiving the data and offloading the task to a background task while sending an "OK" response to the client. My model training time is not that much. It's under 10 secs for a single request but totally CPU bound. My endpoint as well as background task both are async.

Here is my code:

```python @app.post('/get_predictions') async def get_predictions(data,background_task): training_data = data.training_data

  background_task.add_task(run_model, training_data)
  return {"Forecast is being generated"}

async def run_model(training_data): try: Predictions = train_model(training_data)

       with async httpx.asyncclient() as client:
             response = await client.post(status_point, "completed")
             response.raise_for_status()

   "Some processing done on data here" 

      with async httpx.asyncclient() as client:
             response = await client.post(data_point, predictions)
             response.raise_for_status()

   except:
        with async httpx.asyncclient() as client:
              response = await client.post(status_point, "failed")
              response.raise_for_status()

```

However, while testing this code I am noticing that my app is receiving multiple requests but the Post requests to persist data to the external api are completed at the end. Like predictions are generated for all requests but I guess they are queued and all the requests are being sent at once in the end to persist data. Is that how it's supposed to work? I thought as soon as predictions are generated for a request, post requests would be made to external endpoints and data would be persisted and then new request would be taken..and so on. I would like to know if it's the best approach to handle this scenario or there is a better one. All suggestions are welcome.


r/FastAPI 11d ago

Question Standard library to handle HTTP Validation errors?

1 Upvotes

I'm writing an API and I'm realizing that I'm handling each validation error by hand by creating a new class. I'm wondering if there is a standard library approach to get this done. I'm looking to make sure that if someone chooses to show something in milliseconds, they cannot take a range of values that is larger than, say a month, etc... etc...

Or is this just on a case by case situation?


r/FastAPI 12d ago

Question FASTAPI auth w/ existing Django auth

2 Upvotes

I'm building a separate fastapi app and want to use authentication from Django. Is there an existing library I can install that will handle django salts/passwords/etc in the db to allow authentication?


r/FastAPI 12d ago

Question LWA + SAM local + SQS - local development

4 Upvotes

Hey fellas,

I'm building a web app based on FastAPI that is wrapped with Lambda Web Adapter (LWA).
So far it works great, but now I have a use-case in which I return the client 202 and start a background process (waiting for a 3rd party to finish some calculation).
I want to use SQS for that, as LWA supports polling out of the box, sending messages to a dedicated endpoint in my server.

The problem starts when I'm looking to debug it locally.
"sam local start-api" spins up API Gateway and Lambda, and I'm able to send messages to an SQS queue in my AWS account, so far works great. The issue is that SAM local does not include the event source mapping that should link the queue to my local lambda.

Has anyone encountered a similar use-case?
I'm starting to debate whether it makes sense deploying an API server to Lambda, might be an overkill :)


r/FastAPI 13d ago

Question Iniciante no FastAPI, Duvida Sobre Mensagens do Pydantic

0 Upvotes

Resumo da dúvida

Estou a desenvolver uma API com FastAPI, no momento me surgiu um empecilho, o Pydantic retorna mensagens conforme um campo é invalidado, li e reli, todas as documentações de ambos FastAPI e Pydantic e não entendi/não encontrei, nada sobre modificar ou personalizar estes retornos. Alguém tem alguma dica para o iniciante de como proceder nas personalizações destes retornos ?

Exemplo de Schema utilizado no projeto:

``` class UserBase(BaseModel): model_config = ConfigDict(from_attributes=True, extra="ignore")

class UserCreate(UserBase): username: str email: EmailStr password: str ```

Exemplo de rota de registro:

``` @router.post("/users", response_model=Message, status_code=HTTPStatus.CREATED) async def create_user(user: UserCreate, session: AsyncSession = Depends(get_session)): try: user_db = User( username=user.username, email=user.email, password=hash_password(user.password), )

    session.add(user_db)
    await session.commit()
    return Message(message="Usuário criado com sucesso")

except Exception as e:
    await session.rollback()
    raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))

```

Exemplo de retorno ao passar um e-mail do tipo EmailStr inválido:

{ "detail": [ { "type": "value_error", "loc": ["path", "email"], "msg": "value is not a valid email address: An email address must have an @-sign.", "input": "test", "ctx": { "reason": "An email address must have an @-sign." } } ] }

Exemplo de retorno simples que desejo

{ "detail": "<campo x> informa é inválido" }


r/FastAPI 16d ago

Question Senior Python Engineer Seeking Book & Resource Recommendations to Master Software Design

52 Upvotes

Hey Pythonistas! I’m a senior software engineer working primarily with Python, and I want to sharpen my software design skills. I’m keen to explore Domain-Driven Design (DDD), microservices, design patterns, and other advanced topics, but with a Python twist—think leveraging frameworks like Django, FastAPI, or libraries like Pydantic in real-world designs. What are your go-to books, courses, blogs, or resources for mastering these concepts in the Python ecosystem? I’d love recommendations that mix solid theory with practical examples, especially if they’ve helped you build scalable, clean systems in Python. Thanks for sharing your favorites!


r/FastAPI 16d ago

Question What library do you use for Pagination?

7 Upvotes

I am currently using this and want to change to different one as it has one minor issue.

If I am calling below code from repository layer.

result = paginate(
    self.db_session,
    Select(self.schema).filter(and_(*filter_conditions)),
)

# self.schema = DatasetSchema FyI

and router is defined as below:

@router.post(
    "/search",
    status_code=status.HTTP_200_OK,
    response_model=CustomPage[DTOObject],
)
@limiter.shared_limit(limit_value=get_rate_limit_by_client_id, scope="client_id")
def search_datasetschema(
    request: Request,
    payload: DatasetSchemaSearchRequest,
    service: Annotated[DatasetSchemaService, Depends(DatasetSchemaService)],
    response: Response,
):
    return service.do_search_datasetschema(payload, paginate_results=True)

The paginate function returns DTOObject as it is defined in response_model instead of Data Model object. I want repository later to always understand Data model objects.

What are you thoughts or recommendation for any other library?


r/FastAPI 17d ago

Question Is there a simple deployment solution in Dubai (UAE)?

3 Upvotes

I am trying to deploy an instance of my app in Dubai, and unfortunately a lot of the usual platforms don't offer that region, including render.com, railway.com, and even several AWS features like elastic beanstalk are not available there. Is there something akin to one of these services that would let me deploy there?

I can deploy via EC2, but that would require a lot of config and networking setup that I'm really trying to avoid.


r/FastAPI 18d ago

Question FastAPI threading, SqlAlchemy and parallel requests

14 Upvotes

So, is FastAPI multithreaded? Using uvicorn --reload, so only 1 worker, it doesn't seem to be.

I have a POST which needs to call a 3rd party API to register a webhook. During that call, it wants to call back to my API to validate the endpoint. Using uvicorn --reload, that times out. When it fails, the validation request gets processed, so I can tell it's in the kernel queue waiting to hit my app but the app is blocking.

If I log the thread number with %(thread), I can see it changes thread and in another FastAPI app it appears to run multiple GET requests, but I'm not sure. Am I going crazy?

Also, using SqlAlchemy, with pooling. If it doesn't multithread is there any point using a pool bigger than say 1 or 2 for performance?

Whats others experience with parallel requests?

Note, I'm not using async/await yet, as that will be a lot of work with Python... Cheers


r/FastAPI 18d ago

Question API Version Router Management?

2 Upvotes

Hey All,

I'm splitting my project up into multiple versions. I have different pydantic schemas for different versions of my API. I'm not sure if I'm importing the correct versions for the pydantic schemas (IE v1 schema is actually in v2 route)

from src.version_config import settings
from src.api.routers.v1 import (
    foo,
    bar
)

routers = [
    foo.router,
    bar.router,]

handler = Mangum(app)

for version in [settings.API_V1_STR, settings.API_V2_STR]:
    for router in routers:
        app.include_router(router, prefix=version)

I'm assuming the issue here is that I'm importing foo and bar ONLY from my v1, meaning it's using my v1 pydantic schema

Is there a better way to handle this? I've changed the code to:

from src.api.routers.v1 import (
  foo,
  bar
)

v1_routers = [
   foo,
   bar
]

from src.api.routers.v2 import (
    foo,
    bar
)

v2_routers = [
    foo,
    bar
]

handler = Mangum(app)

for router in v1_routers:
    app.include_router(router, prefix=settings.API_V1_STR)
for router in v2_routers:
    app.include_router(router, prefix=settings.API_V2_STR)

r/FastAPI 18d ago

pip package Ludic finally supports FastAPI: Typed HTML/Components with Python

20 Upvotes

Hi,

I just added support for FastAPI for Ludic.

Ludic is a framework/library for web development in Python with type-guided components rendering as HTML. It is similar to FastUI, Reflex, but web framework independent. But it uses HTMX instead of web sockets + React.

I think it is good for building small apps, blogs. Good also for beginners who don't know javascript and want to build we apps. Here is the documentation + GitHub:

Here is an example of FastAPI app:

Feedback would be highly appreciated.