I have a FastAPI app and created a folder called dagger_modules. I used dagger init --sdk=python --name=hello-world to create a basic Dagger module that simply prints “Hello World”. I want to call this function from the /hello endpoint and have it run in the same way as when I execute dagger call hello-world from the CLI. The implementation below works, but I’m not sure if it’s correct—it feels more like a workaround. The cold start time is also significant, and preloading the python:3.11-slim image feels like another workaround.
`// DaggerFastAPIDemo/main.py
@app.get("/hello")
async def hello_world_module_endpoint():
"""Endpoint that executes the hello-world Dagger module"""
logger.info("/hello endpoint called. Using Dagger global client.")
try:
module_source_path = "./dagger_modules/src/hello_world"
logger.info(f"Loading Dagger module from: {os.path.abspath(module_source_path)}")
exec_command = get_module_execution_command("main", "HelloWorld", "hello_world ")
container = dag.container().from_("python:3.11-slim")
.with_exec(["pip", "install", "--upgrade", "pip"])
.with_exec(["pip", "install", "dagger-io==0.18.5"])
.with_directory("/app", dag.host().directory("dagger_modules/src/hello_world"))
.with_workdir("/app")
.with_exec(["python", "-c", exec_command])
message = await container.stdout()
logger.info(f"Received message from hello-world function: {message}")
return {"message": message.strip()}
except Exception as e:
logger.exception(f"Error executing hello-world module: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
// DaggerFastAPIDemo/dagger_modules/src/hello_world/main.py
from dagger import function, object_type
@object_type
class HelloWorld:
@function
def hello_world(self) -> str:
"""Return a Hello World greeting."""
return "Hello, World!"`