Home > Net >  FastAPI structure - where to store large database queries
FastAPI structure - where to store large database queries

Time:06-20

I've been working on FastAPI backend, I've mainly been following the project structure as used here because this project was created by the FastAPI creator and seems a good reference.

So far my project has been scaling well, but I've only had to deal with simple CRUD database operations. Now I need to use more complex database queries, and I'm not sure where these would fit in the current project structure. Is there a standard folder structure I should follow, or should I just make a "queries" folder and be done with it?

CodePudding user response:

It's common to separate that functionality out into distinct services, where each service has its own responsibility. A ProductService would have methods to retrieve products according to business rules (and needs), and would be where the queries related to those requirements would be (and other functionality as well).

You'll also see this mentioned as a Repository-based layout, where the Repository is an abstraction over "how to save and retrieve given data". I prefer to structure this as services instead, since having a service that uses a repository in many cases is overkill (how often do you really change your underlying repository implementation during an application's life time?).

foo/
    schemas/
    services/
        user.py
        product.py
        posts.py

A service could be something like:

class ProductService:
    def __init__(self, db):
        self.db = db

    def get_products_for_user(user_id: int, pagination: Pagination):
        return self.db.query(Product).filter(Product.user_id == user_id)[pagination.offset:pagination.offset   pagination.hits]

.. etc.

  • Related