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

# app.py
import uvicorn
from fastapi import FastAPI
from fastapi_better_di.patcher.auto import is_pathed
# functions were patched immediately after import

assert is_pathed(), "Something went wrong"


class MyType:
    def __init__(self, value):
        self.value = value


app = FastAPI()
app.dependency_overrides[MyType] = lambda: MyType(123)


@app.get("/")
def handler(my_type: MyType):  # <- DI without `Depends()`
    assert my_type.value == 123
    return my_type


if __name__ == "__main__":
    uvicorn.run(app)

See all examples

Usage

You have 2 use cases:

  1. Use patching (preferably):
    • 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(FastAPI) 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.2.1.tar.gz (4.2 kB view details)

Uploaded Source

File details

Details for the file fastapi-better-di-0.2.1.tar.gz.

File metadata

  • Download URL: fastapi-better-di-0.2.1.tar.gz
  • Upload date:
  • Size: 4.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.10.2

File hashes

Hashes for fastapi-better-di-0.2.1.tar.gz
Algorithm Hash digest
SHA256 1ae8e181d968f8e506f1ec177dabf6f39f2bb2b1f553491d5c86fe8b8e53cf8f
MD5 e7b4175c8bf08aaef3e14d505f41ca2f
BLAKE2b-256 2d9fdb3232f59143d44349e691a69fa140a01a1e34109381e658cfe194cc6eaa

See more details on using hashes here.

Supported by

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