liveBook · Manning

FastAPI

As explained in AI Agents in Action, Second Edition

FastAPI is a Python web framework for building APIs with type-based request validation and automatic interface documentation.

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

How AI Agents in Action, Second Edition covers it

How deep it goes
Demonstrates typed input, asynchronous POST handling, binary responses, launch commands, and missing-output errors.
Examples
Uses an image-generator endpoint, curl and PowerShell requests, saved PNG files, and Dockerized service runs.
What it assumes
Assumes an existing agent and configured OPENAI_API_KEY while teaching the surrounding API wrapper and service run loop.
What you can do after
Operate/configure a FastAPI agent service, call its POST endpoint, verify image output, and run it in Docker.
How it connects
Connects HTTP APIs with agents, Uvicorn, command-line clients, Docker, and environment-based API-key configuration.

Also explained in

Compare how 5 books explain FastAPI →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of AI Agents in Action, Second Edition. The section links point to the parts of the book it draws on.