[Python] FastAPI hosted on Lambda does not serve static content

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a FastAPI app hosted on AWS Lambda + Api Gateway using Mangum. However it seems not to be able to serve static content returning 404 error.

    Here is how static directory is mounted

    application = FastAPI(title="MyApp")

    static_directory = Path(__file__).parent / "static"
    application.mount(
    f"{settings.formatted_api_stage}/static",
    StaticFiles(directory=static_directory, check_dir=True),
    name="static",
    )


    settings.formatted_api_stage corresponds to API Gateway stage like /dev in https://a123bcdefg.execute-api.eu-north-1.amazonaws.com/dev/

    Mangum handler

    handler = Mangum(
    application, lifespan="off", api_gateway_base_path=settings.formatted_api_stage
    )


    AWS infra is managed using CDK

    fastapi_lambda = PythonFunction(
    self,
    "MyLambda",
    entry="../app",
    index="main.py",
    handler="handler",
    runtime=_lambda.Runtime.PYTHON_3_13,
    role=lambda_role,
    memory_size=512,
    timeout=Duration.seconds(5),
    bundling=BundlingOptions(asset_excludes=["*.pyc", "__pycache__/"]),
    )

    api = apigateway.LambdaRestApi(
    self,
    "MyAPI",
    handler=fastapi_lambda,
    proxy=True,
    deploy_options=apigateway.StageOptions(
    stage_name=api_stage,
    ),
    )


    Then in the templates I reference static content like

    <link rel="stylesheet" href="{{ url_for('static', path='/css/style.css') }}" />


    But it results in a 404 error.

    I can verify that static folder is packaged ok and is present in the same folder as main.py in the lambda bundle.

    The app works as expected when run locally.

    Continue reading...

Compartilhe esta Página