Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Research Dependency Injection in FastAPI #777

Closed
6 tasks done
lasryariel opened this issue Aug 30, 2024 · 4 comments
Closed
6 tasks done

Research Dependency Injection in FastAPI #777

lasryariel opened this issue Aug 30, 2024 · 4 comments
Assignees
Labels
Complexity: Large Issue requires some research and solution is only loosely defined. Feature: Infrastructure Changes to site technical Architecture points: 1 Can be done in 4-6 hours Role: Back End

Comments

@lasryariel
Copy link
Member

lasryariel commented Aug 30, 2024

Overview

As part of our ongoing effort to improve code readability and accessibility for junior developers, we are exploring the use of Dependency Injection (DI) in FastAPI. The goal is to leverage FastAPI’s DI capabilities to create a more modular, testable, and maintainable codebase.

Action Items

  1. Understand FastAPI's Dependency Injection System

    • Research how Dependency Injection works in FastAPI.
    • Identify best practices for implementing DI in FastAPI, with a focus on readability and simplicity.
  2. Evaluate Current Codebase for DI Opportunities

    • Review the current FastAPI codebase to identify areas where Dependency Injection could simplify or improve the architecture.
    • Document the parts of the code that could benefit from DI, such as services, database connections, or third-party integrations.
  3. Decision Record

Resources/Instructions

A well-researched assessment of Dependency Injection system in FastAPI and documentation of areas to implement.

@lasryariel lasryariel added Role: Back End points: 1 Can be done in 4-6 hours Feature: Infrastructure Changes to site technical Architecture Complexity: Large Issue requires some research and solution is only loosely defined. labels Aug 30, 2024
@github-project-automation github-project-automation bot moved this to New Issue Approval in P: HUU: Project Board Aug 30, 2024
@lasryariel lasryariel moved this from New Issue Approval to In Progress in P: HUU: Project Board Aug 30, 2024
@tylerthome
Copy link
Member

So far from a brief look at the docs, it looks like the Depends() mechanism available in FastAPI will be handy for abstracting some common processes (along with middlewares), but a bit different than DI within OOP frameworks as the top-level injected Callable's only passed arguments will be parameters equivalent to the Path operations within FastAPI.

Thinking about database, logging, etc dependencies we might consider using global singletons, and allow the ContextManager to handle any open and close operations on e.g. connections.

Overall so far it looks like existing code will port without too much headache, but @paulespinosa may catch something I missed on this read through.

@paulespinosa
Copy link
Member

@tylerthome got the basics down. I also second the assertion that porting the existing code base can be done.

The Dependency Injection system in FastAPI is easy to use and capable of doing lots for us. The tutorial is extensive https://fastapi.tiangolo.com/tutorial/dependencies/ with details that provide guidance on injecting database dependencies, security related dependencies, and more. In addition, the Advanced provides another way to make an instance of a class callable and use it as a dependency.

The tutorial tells us FastAPI will create a Context Manager for any dependency with yield and also provides guidance on how to create custom Context Managers. https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#what-are-context-managers.

The tutorial on writing bigger applications guides us to put dependencies into its own module. https://fastapi.tiangolo.com/tutorial/bigger-applications/#dependencies. This can aid us in maintaining easy to understand code structure.

For logging, it appears the standard is to use Python's logging facility for all logging. The logger can be customized at startup and removes the need for associating DI and logging. https://docs.python.org/3/library/logging.html

import logging
import mylib
logger = logging.getLogger(__name__)

The FastAPI project template also uses this technique for logging. For example: https://github.com/fastapi/full-stack-fastapi-template/blob/master/backend/app/backend_pre_start.py

Regarding, best practices. I think it's too early to know what they are until we have designed the API's architecture(s).

Below is a just a brainstorm for how DI could be used to inject the current user as a guest and case manager.

@router.post("/intake_profile")
def submit_intake_profile(intake_profile: IntakeProfile, guest: Annotated[Guest, Depends(get_current_user_as_guest)], case_manager: Annotated[CaseManager, Depends(get_case_manager)]):
    case = case_manager.caseFor(guest)
    case.submit_intake_profile(intake_profile)

@lasryariel
Copy link
Member Author

Conversation between Ariel and Paul 9/4

As a follow up we need to design for both infrastructure and business objects

Infrastructure

  • FastAPI - look at existing objects in HUU software to determine what needs to be added to FastAPI dependency injection
  • SQLAlchemy/SQLModel - we currently use SQLAlchemy should we add on the layer of SQLModel? integration with fastapi documentation noted that fastapi will be moving more towards supporting SQLModel, but is that too bleeding edge for HUU context?)
    • SQL Model is just a layer on top of SQLAlchemy
    • discuss in engineering call
  • Security

Business objects

  • Users/roles, intake profiles, events, tasks, documents, etc.
    • ask Tyler if we will have unmatched case/matched case (case management) type objects
  • behaviors and how it updates states of objects
  • this can also help us organize the files in the project

Current state of dependency injection in HUU code

  • some objects already require dependencies to work (repositories- middleman for when we make db queries and changes)
    • discuss improvements to using repositories, could be an issue for jr developers that it is maybe not being used in the intended way

@lasryariel
Copy link
Member Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Complexity: Large Issue requires some research and solution is only loosely defined. Feature: Infrastructure Changes to site technical Architecture points: 1 Can be done in 4-6 hours Role: Back End
Projects
Status: Done
Development

No branches or pull requests

3 participants