Skip to content
Visual explainer 3h 30m to learn 5 steps

Serve and stream an ADK agent over HTTP

Expose the agent through the ADK API server or a small FastAPI wrapper with authenticated session creation, streamed events, errors and disconnect handling.

By Invicly Tech, , in Google ADK with Python for AI Agents. About 13 minutes to read.

Topic 13 of 29

In short

An agent becomes useful to an app once it sits behind an HTTP endpoint. ADK ships an API server (adk api_server) that exposes session and run endpoints, including /run_sse for streamed events, and you can also wrap the Runner in your own small FastAPI app. The wrapper is where you check the caller's identity, create sessions for that user only, stream events and handle errors and disconnects.

Think of it like this: The ADK API server is a test kitchen with the door open; your FastAPI wrapper is the restaurant counter that checks who ordered before the food goes out.

Explained simply

So far your support agent has run in the terminal or the ADK web UI. A real app, such as a help widget on a website, needs to reach it over HTTP. That means an address it can send a message to and a way to get the answer back.

ADK gives you a ready-made server for this. Run adk api_server in the folder that holds your agent and it starts a small web server on your machine at port 8000. It has endpoints to create a session, run the agent and list your apps, plus a docs page at /docs where you can try them.

Answers from a model take a few seconds. Instead of making the user stare at a spinner, you can stream: the server sends each piece of the reply as soon as it exists. ADK uses Server-Sent Events for this, a simple HTTP stream where each message is a line starting with data:.

The built-in server does not know who is calling. It takes the user ID from the request, so anyone could claim to be anyone. That is fine on your laptop and not fine on the internet. For real users you write a thin FastAPI app around the ADK Runner that checks a login token first and uses the ID inside that token.

The last part is handling things going wrong. A tool can fail, the model can time out, or the user can close the browser tab halfway. Your server should send a short, friendly error event, log the details with a request ID, and stop work when the client leaves.

Press Play on a diagram to walk through it one step at a time.

SequenceOne streamed request through a FastAPI wrapper
Browser
FastAPI wrapper
ADK Runner
Model and tools
  1. 1POST /chat with bearer token and message
    Browser to FastAPI wrapper: POST /chat with bearer token and message
  2. 2Verify token, derive user_id, load own session
    FastAPI wrapper to FastAPI wrapper: Verify token, derive user_id, load own session
  3. 3run_async(user_id, session_id, new_message)
    FastAPI wrapper to ADK Runner: run_async(user_id, session_id, new_message)
  4. 4Model call, then read-only tool call
    ADK Runner to Model and tools: Model call, then read-only tool call
  5. 5Yield events one by one
    ADK Runner to FastAPI wrapper: Yield events one by one
  6. 6Send each event as an SSE data line
    FastAPI wrapper to Browser: Send each event as an SSE data line
  7. 7Final event, then close the stream
    FastAPI wrapper to Browser: Final event, then close the stream
CompareBuilt-in API server or your own wrapper
adk api_server
  • One command, port 8000 by default
  • Session, /run and /run_sse endpoints
  • Caller chooses userId in the URL
  • Good for local testing and the web UI
FastAPI wrapper around Runner
  • You write the routes
  • user_id comes from the verified token
  • You shape events and error messages
  • Good for anything users can reach
MapWhat an HTTP-facing agent needs
Agent endpoint
  • Identity
    • Verify token
    • user_id from claims
    • No user IDs from clients
  • Sessions
    • Create per user
    • Check ownership on load
    • Delete on request
  • Streaming
    • SSE data lines
    • Partial and final events
    • No proxy buffering
  • Failure handling
    • Short error events
    • Request ID in logs
    • Cleanup on disconnect

In depth

What adk api_server gives you

In google-adk 2.15.1, adk api_server loads every agent folder under the current directory and serves them with FastAPI and Uvicorn on 127.0.0.1:8000 by default. Use --port to change the port and --host only if you really need other machines to reach it. Each agent folder name becomes an app name.

The main routes are listed below. Request bodies for /run and /run_sse use camelCase field names: appName, userId, sessionId and newMessage, where newMessage has a role and a list of parts. /run waits and returns every event as one JSON array. /run_sse returns the same events one at a time as SSE. Adding streaming: true to a /run_sse body also turns on partial text events, so words appear while the model is still writing.

The Swagger page at /docs is the quickest way to see the exact request shapes for your installed version.

  • GET /list-apps: names of the agents found
  • POST /apps/{app}/users/{user}/sessions/{id}: create a session
  • GET or DELETE the same path: read or remove a session
  • POST /run: all events in one JSON array
  • POST /run_sse: events streamed as Server-Sent Events

Why the built-in server is not your public API

Look at the URLs: the user ID is just a path segment chosen by the caller. The built-in server has no idea who is signed in, so a caller who changes u_123 to u_456 reads someone else's session, including any ticket numbers the agent looked up. It also exposes routes you may not want public, such as deleting sessions.

That is why this path puts a small FastAPI app in front for anything users can reach. The wrapper verifies a token (for example an ID token from your identity provider), reads the subject claim, and uses that as user_id when it creates or loads sessions. A client never names a user. If a session_id from the client does not belong to the signed-in user, the session service simply returns nothing for that user, and you answer 404.

If you prefer to keep the ADK routes, ADK also has a get_fast_api_app() helper that builds the same app in Python. You would still need your own auth in front of it, for example an authenticating proxy or Cloud Run IAM.

A streaming endpoint that survives errors and disconnects

In your wrapper, an async generator calls runner.run_async() and turns each event into an SSE line with event.model_dump_json(exclude_none=True, by_alias=True). FastAPI's StreamingResponse with media type text/event-stream sends the lines as they come. Pass RunConfig(streaming_mode=StreamingMode.SSE) if you want partial text events.

Three things go wrong in practice. First, exceptions: wrap the loop in try and except, send one event such as an error object with a request ID, and log the full error on the server. Second, disconnects: when the browser goes away, Starlette stops reading and cancels the generator, so put cleanup in a finally block and do not swallow asyncio.CancelledError. Third, proxies: some proxies buffer responses, which turns a stream into one late blob; send the header X-Accel-Buffering: no where a proxy honours it, and test through the real path.

FlowLife of one streamed response
  1. 1
    Auth check

    Bad token: 401 before any work

  2. 2
    Session check

    Not this user's session: 404

  3. 3
    Stream events

    One data: line per event

  4. 4
    On error

    Send short error event, log details

  5. 5
    On disconnect or end

    finally block cleans up

Choosing what to send to the client

An ADK event can hold a lot: model text, function calls with arguments, function responses, state changes and metadata. A browser widget usually needs far less. Sending everything leaks internal detail, such as raw tool output with other fields, and makes the client harder to change later.

A common pattern is to map events to a small public shape: partial text, a short status line when a tool runs (for example, Checking ticket status), the final answer, and an error type. Keep the full events in your server logs or traces, where you control access. Use event.is_final_response() to know which event carries the answer, and event.partial to tell streamed fragments from complete messages. This keeps your public contract stable even when you change tools or upgrade ADK.

  • Send: partial text, final text, a tool status label, an error code
  • Keep server side: tool arguments, raw tool results, state deltas
  • Add a request ID to every response for support

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Start the ADK API server~40m
  2. 2
    Wrap the runner in FastAPI~40m
  3. 3
    Create sessions for the signed-in user~40m
  4. 4
    Stream events to a client~40m
  5. 5
    Handle errors and disconnects~40m

Key points

  • adk api_server listens on 127.0.0.1:8000 by default and serves Swagger docs at /docs.
  • The built-in server trusts the userId in the request, so never expose it to real users without an auth layer in front.
  • In your own wrapper, take user_id from the verified token, never from the request body.
  • Stream with Server-Sent Events: one JSON event per data line, then close the stream cleanly.
  • Catch errors inside the generator and send a short error event; log the details server side.

Key terms

Tap a card to flip it. 0/6 known

Examples

bash
adk api_server                       # serves agents in the current folder on :8000
curl -X POST localhost:8000/apps/support_agent/users/u_demo/sessions/s_1 \
  -H 'Content-Type: application/json' -d '{}'
curl -N -X POST localhost:8000/run_sse -H 'Content-Type: application/json' -d '{
  "appName": "support_agent", "userId": "u_demo", "sessionId": "s_1",
  "newMessage": {"role": "user", "parts": [{"text": "Status of T-1001?"}]},
  "streaming": true}'

Local only. The -N flag stops curl buffering, so you see each data: line arrive.

Try the built-in API server locally

Prerequisites: the support_agent folder from earlier modules, google-adk 2.15.1 in a virtual environment, and either a model key in .env or the mock model from the foundations module. Step 1: from the folder that contains support_agent, run adk api_server. Step 2: create a session for a made-up user. Step 3: post a message to /run and check the evidence: a JSON array whose last event has author support_agent and text that mentions T-1001. Step 4: run the same call on /run_sse with curl -N and watch the data: lines arrive one by one. Cleanup: delete the session and stop the server with Ctrl+C.

bash
adk api_server
curl -s -X POST localhost:8000/apps/support_agent/users/u_demo/sessions/s_1 \
  -H 'Content-Type: application/json' -d '{}'
curl -s -X POST localhost:8000/run -H 'Content-Type: application/json' -d '{
  "appName": "support_agent", "userId": "u_demo", "sessionId": "s_1",
  "newMessage": {"role": "user", "parts": [{"text": "Status of T-1001?"}]}}'
curl -s -X DELETE localhost:8000/apps/support_agent/users/u_demo/sessions/s_1

A FastAPI wrapper that takes identity from the token

Here the user never sends a user ID. current_user() is your own dependency that verifies the bearer token and returns its subject; in tests it can return a fixed synthetic user. The route loads the session for that user only, so a foreign session ID returns 404. The generator streams events and turns any failure into one error event. Expected evidence: a 401 without a token, a 404 for another user's session, and data: lines for your own.

python
@app.post("/chat/{session_id}")
async def chat(session_id: str, body: ChatIn, user: str = Depends(current_user)):
    if not await sessions.get_session(app_name=APP, user_id=user, session_id=session_id):
        raise HTTPException(404, "Session not found")
    msg = types.Content(role="user", parts=[types.Part(text=body.text)])
    async def events():
        try:
            async for ev in runner.run_async(user_id=user, session_id=session_id, new_message=msg,
                                             run_config=RunConfig(streaming_mode=StreamingMode.SSE)):
                yield f"data: {ev.model_dump_json(exclude_none=True, by_alias=True)}\n\n"
        except Exception:
            log.exception("run failed", extra={"session": session_id})
            yield 'data: {"error": "agent_failed"}\n\n'
    return StreamingResponse(events(), media_type="text/event-stream")

Quick reference

  • adk api_server: REST API for agents in the current folder, 127.0.0.1:8000 by default
  • Swagger UI for the API server: http://localhost:8000/docs
  • POST /run returns a JSON array of events; POST /run_sse streams them
  • Request body fields: appName, userId, sessionId, newMessage {role, parts}
  • RunConfig(streaming_mode=StreamingMode.SSE) gives partial text events
  • Use curl -N to watch an SSE stream without buffering
  • Public endpoint rule: user_id comes from the verified token, never from the client

Common mistakes

  • Putting adk api_server on a public port: anyone can pick any userId and read that user's sessions.
  • Letting the client send user_id in the body, so one user can open another user's session.
  • Returning raw Python tracebacks in the stream instead of a short error event with a request ID.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why should the built-in adk api_server not face real users directly?

Question 2

2Which content type does a Server-Sent Events response use?

Question 3

3A user closes the tab while the agent is still running. What should your wrapper do?

Question 4

4Which field in a /run_sse body turns on token-level partial text?

Question 5

5What is a good thing to keep out of the events you send to the browser?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start adk api_server, create a session for user u_demo, and call /run with one question. Note which event is the final answer.

  2. Exercise 2medium

    Write a FastAPI route POST /sessions that creates a session for the signed-in user only, using a current_user dependency that returns a fixed synthetic user in tests.

  3. Exercise 3hard

    Add tests that prove: no token gives 401, Bob cannot stream into Alice's session (404), and a tool exception produces one error event, not a traceback.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need FastAPI to serve an ADK agent?
Not for local work: adk api_server already uses FastAPI under the hood. You write your own FastAPI app when you need real authentication, a smaller public API or custom error handling.
Why use SSE instead of WebSockets?
A chat answer only flows one way, from server to client, and SSE does that over plain HTTP with less code. WebSockets are worth it for two-way live audio or video, which ADK handles with its separate live streaming features.
My stream arrives all at once at the end. Why?
Something between the server and the client is buffering, often a proxy or curl without -N. Test locally first, then through each hop, and turn off buffering where the proxy supports it.

Go deeper

ShareXLinkedInWhatsApp