Skip to content

FastAPI integration

Benefits

  • Use Wirio's dependency injection in FastAPI.
  • Use FastAPI with a framework-agnostic dependency injection.
  • Easily testable services.
  • Transparent integration instead of referencing module-based singletons.

Installation

To use the FastAPI integration, add the fastapi extra to automatically install the required compatible dependencies.

uv add wirio[fastapi]

Quickstart

from typing import Annotated

from fastapi import FastAPI

from wirio import ServiceCollection
from wirio.annotations import FromServices


class EmailService:
    pass


class UserService:
    def __init__(self, email_service: EmailService) -> None:
        self.email_service = email_service

    async def create_user(self) -> None:
        pass


app = FastAPI()


@app.post("/users")
async def create_user(
    user_service: Annotated[UserService, FromServices()],  # (1)!
) -> None:
    pass


services = ServiceCollection()
services.configure_fastapi(app)  # (2)!
services.add_transient(EmailService)
services.add_transient(UserService)
  1. Annotate the parameter with the type to resolve
  2. This will configure FastAPI to use Wirio's dependency injection

Testing

Information available here.