Skip to main content

No project description provided

Project description

fastapi-better-di

What is this ?

fastapi-better-di is a utility that allows you to use DI in fastapi without Depends()

Installation

pip install fastapi_better_di

Examples

# routes.py
from fastapi import APIRouter

from custom_types import MyType

api = APIRouter()


@api.get("/")
def handler(my_type: MyType):  # <- DI without Depends()
    return {"my_type": my_type.value}
# app.py
from fastapi import FastAPI
from fastapi_better_di.patcher.auto import is_pathed

from custom_types import MyType

assert is_pathed(), "Something went wrong"

app = FastAPI()

# Register types for DI
app.dependency_overrides[MyType] = lambda: MyType(123)


def register_routers():
    # Importing routers after initializing main app
    from routes import api

    app.include_router(router=api)


register_routers()
  1. See full examples

Usage

You have 2 use cases:

  1. Use patching:
    • Auto patching: patches classes when importing:

      from fastapi_better_di.patcher.auto import is_pathed # The classes were patched immediately after import
      
      # To check if everything is OK, use assert
      assert is_pathed(), "Something went wrong"
      
    • Manual patching: you need to call patch() by yourself:

      from fastapi_better_di.patcher.manual import patch, is_pathed
      
      patch()
      
      # To check if everything is OK, use assert
      assert is_pathed(), "Something went wrong"
      
    • Patching example

  2. Use DI Classes: FastAPIDI, APIRouterDI, APIRouteDI
    • Use FastAPIDI instead of FastAPI
    • Use APIRouterDI instead of APIRouter
    • Use APIRouteDI instead of APIRoute
    • DI Classes example
  • IMPORTANT: You can still use = Depends() without a function as an argument, and it won't add unnecessary arguments to the swagger.

  • IMPORTANT: The main app(FastAPIDI) and dependency_overrides must be initialized before importing routers!

How it works

fastapi-better-di simply patch the handler function and add = Depends(func) as the default argument

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi-better-di-0.1.1.tar.gz (3.8 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page