FastAPI wraps agent code in an HTTP service so clients can submit requests and receive clean responses. A POST endpoint suits longer prompts and potentially slow operations. section 8.1.2
Image-generation endpoint
A client posts {"input":"an agent generating an image"} to /generate. The endpoint runs the agent, decodes the returned image data, and responds with PNG bytes that the client saves as out.png.
Listing 8.2 02_app.py (API code only)
app = FastAPI(
title="Fixed-Config Image Generator API",
version="1.0.0") #1
class GenerateIn(BaseModel):
input: str = Field(...,
description="Plain-language request (the agent crafts the prompt)."
) #2
@app.post("/generate", response_class=Response) #3
async def generate(body: GenerateIn):
agent = build_agent()
with trace("Image generation"):
result = await Runner.run(agent, body.input)
b64 = extract_image_b64(result) #4
if not b64:
raise HTTPException(
status_code=500, detail="Image generation tool produced no output."
)
png_bytes = base64.b64decode(b64)
return Response(content=png_bytes, media_type="image/png") #5
Inspect the compact API implementation, including the typed input model, asynchronous route, missing-output error, and PNG response. section 8.1.2




