Skip to content

Add lifespan support to FastAPI app creation #27

@Mohammadreza-kh94

Description

@Mohammadreza-kh94

Feature Request: Add Lifespan Support to FastAPI App Creation

Feature Description

Add support for optional lifespan context managers when creating FastAPI applications through the create_fastapi_app utility function.

Problem Statement

Currently, the create_fastapi_app function in AppUtils doesn't support passing a lifespan parameter to the FastAPI application. This makes it difficult to properly initialize and clean up resources that need to exist for the lifetime of the application, such as database connections, external APIs, or background tasks.

Proposed Solution

Enhance the create_fastapi_app function to accept an optional lifespan parameter, which would be an async context manager that gets passed directly to the FastAPI constructor. This would allow developers to define setup and teardown operations that run at application startup and shutdown.

Use Cases

  1. When a developer needs to initialize database connections at startup and properly close them on shutdown
  2. In situations where background tasks need to be started when the app starts and gracefully terminated when it stops
  3. For integrations with external services that require authentication or session management throughout the application's lifecycle
  4. When resources need to be properly cleaned up to prevent memory leaks or hanging connections

Alternative Solutions

One alternative would be to manually handle lifecycle events outside the app creation function, but this leads to fragmented code and potential resource leaks. Another option would be to use middleware, but middleware runs for each request rather than once during app lifecycle events, making it less suitable for this purpose.

Implementation Ideas

The implementation is straightforward - add a new optional parameter to the create_fastapi_app function and pass it to the FastAPI constructor:

@classmethod
def create_fastapi_app(
    cls,
    config: BaseConfig | None = None,
    *,
    configure_exception_handlers: bool = True,
    lifespan: Callable[..., AsyncContextManager] | None = None,
) -> FastAPI:
    # existing code...
    app = FastAPI(
        # existing parameters...
        lifespan=lifespan,
    )
    # rest of the existing code...

Additional Context

FastAPI's lifespan parameter was introduced to replace the older startup/shutdown event handlers and provides a cleaner, more Pythonic way to manage application lifecycle. Libraries like SQLAlchemy, Redis, and other connection-based services benefit greatly from proper lifecycle management.

Example usage would be:

from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Setup: initialize connections, etc.
    db = initialize_db()
    app.state.db = db
    
    yield  # Server is running and handling requests
    
    # Cleanup: close connections, etc.
    await db.close()

app = AppUtils.create_fastapi_app(config, lifespan=lifespan)

Would you be willing to help implement this feature?

  • Yes, I'd be interested in contributing code
  • Yes, I'd be interested in testing
  • Yes, I'd be interested in documenting
  • No, I'm just suggesting the feature

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions