[Python] In FastAPI, should I directly call the database again or reuse an existing API...

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I’m building a simple FastAPI project where I have both API endpoints and HTML page rendering. (I’m mainly a mobile developer, but I’m learning web development alongside.)

    Here’s my situation:

    I have an API endpoint that fetches all books:

    @router.get("/get_all_books", status_code=status.HTTP_200_OK)
    async def get_all_books(user: user_dependency, db: Db_Dependency):
    if user is None:
    raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
    return db.query(Book).all()


    And I have an HTML render function that displays all books:

    @router.get("", status_code=status.HTTP_200_OK, response_class=HTMLResponse)
    async def all_books_render(request: Request, db: Db_Dependency):
    try:
    user = await validate_current_user(request.cookies.get('access_token'))
    if user is None:
    return redirect_to_login()

    books = db.query(Book).all()
    return templates.TemplateResponse("books.html", {'request': request, 'books': books, 'user': user})
    except:
    return redirect_to_login()


    In the HTML render function, instead of using the /get_all_books endpoint, the data is directly fetched from the database again.

    My question is: Would it be a better practice to reuse the API endpoint (for example, call get_all_books inside all_books_render) instead of querying the database again?

    I tried this:

    books = await get_all_books(user, db)


    But I’m unsure if this is a good design or not. • Is it better to call the endpoint function (get_all_books) inside my HTML rendering function? • Or is it better to keep them separate and query the database directly in both places?

    I want to understand the best practice here, especially considering that my project needs to serve both API clients (like mobile apps) and a small web frontend.

    Thanks in advance for any advice!

    Continue reading...

Compartilhe esta Página