By Sagar Shankaran, Founder of CallSphere
Learn how to design RESTful APIs purpose-built for AI agent interactions, covering conversation endpoints, session management, structured payloads, and versioning strategies that keep agents running during upgrades.
Key takeaways
Standard CRUD APIs serve human-driven UIs well, but AI agents place fundamentally different demands on your API layer. Agents send longer payloads, expect structured tool-call responses, maintain multi-turn conversations across many requests, and may retry aggressively on failures. Designing for these patterns upfront saves months of refactoring later.
The core challenge is modeling conversations and agent actions as REST resources. A human user clicks a button and waits. An agent fires dozens of requests per minute, chains tool calls, and expects deterministic response structures it can parse programmatically.
The first design decision is treating conversations (or sessions) as first-class resources. Each conversation gets a unique identifier, and messages within that conversation are sub-resources:
flowchart LR
CLIENT(["Client SDK"])
GW["API Gateway<br/>auth plus rate limit"]
APP["FastAPI app<br/>handlers and DI"]
VAL["Pydantic validation"]
SVC["Service layer<br/>business logic"]
DB[(Database)]
QUEUE[(Background queue)]
OBS[(Tracing)]
CLIENT --> GW --> APP --> VAL --> SVC
SVC --> DB
SVC --> QUEUE
SVC --> OBS
SVC --> CLIENT
style GW fill:#4f46e5,stroke:#4338ca,color:#fff
style APP fill:#f59e0b,stroke:#d97706,color:#1f2937
style DB fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from uuid import uuid4
from datetime import datetime
app = FastAPI(title="AI Agent API", version="v1")
class MessagePayload(BaseModel):
role: str = Field(..., pattern="^(user|agent|system|tool)$")
content: str
tool_call_id: str | None = None
metadata: dict = Field(default_factory=dict)
class ConversationCreate(BaseModel):
agent_id: str
system_prompt: str | None = None
parameters: dict = Field(default_factory=dict)
class ConversationResponse(BaseModel):
id: str
agent_id: str
created_at: str
message_count: int
conversations_db: dict = {}
@app.post("/v1/conversations", status_code=201)
async def create_conversation(body: ConversationCreate) -> ConversationResponse:
conv_id = str(uuid4())
conversations_db[conv_id] = {
"id": conv_id,
"agent_id": body.agent_id,
"messages": [],
"created_at": datetime.utcnow().isoformat(),
}
return ConversationResponse(
id=conv_id,
agent_id=body.agent_id,
created_at=conversations_db[conv_id]["created_at"],
message_count=0,
)
@app.post("/v1/conversations/{conv_id}/messages")
async def add_message(conv_id: str, body: MessagePayload):
if conv_id not in conversations_db:
raise HTTPException(status_code=404, detail="Conversation not found")
conversations_db[conv_id]["messages"].append(body.model_dump())
return {"status": "ok", "message_index": len(conversations_db[conv_id]["messages"]) - 1}
This structure gives agents a clear lifecycle: create a conversation, send messages, retrieve history, and eventually close it. The sub-resource pattern /conversations/{id}/messages keeps the URL hierarchy intuitive and lets you paginate message history independently.
Hear it before you finish reading
Talk to a live CallSphere AI voice agent in your browser — 60 seconds, no signup.
AI agents frequently need to invoke tools and receive structured results. Your API should define explicit payload schemas for tool invocations rather than stuffing everything into a generic content string:
from pydantic import BaseModel
from typing import Any
class ToolCallRequest(BaseModel):
tool_name: str
arguments: dict[str, Any]
call_id: str
class ToolCallResult(BaseModel):
call_id: str
success: bool
result: Any
error: str | None = None
@app.post("/v1/conversations/{conv_id}/tool-results")
async def submit_tool_result(conv_id: str, body: ToolCallResult):
if conv_id not in conversations_db:
raise HTTPException(status_code=404, detail="Conversation not found")
conversations_db[conv_id]["messages"].append({
"role": "tool",
"tool_call_id": body.call_id,
"content": str(body.result) if body.success else body.error,
})
return {"status": "accepted"}
The call_id field links every tool result back to the specific invocation, which is critical when agents run multiple tool calls in parallel.
AI agent APIs evolve rapidly as you add new capabilities. Use URL-based versioning as the primary strategy because agents hard-code endpoint URLs in their configurations:
from fastapi import APIRouter
v1_router = APIRouter(prefix="/v1")
v2_router = APIRouter(prefix="/v2")
@v1_router.post("/conversations/{conv_id}/complete")
async def complete_v1(conv_id: str):
# V1: returns plain text response
return {"response": "Agent reply text here"}
@v2_router.post("/conversations/{conv_id}/complete")
async def complete_v2(conv_id: str):
# V2: returns structured response with token usage
return {
"response": "Agent reply text here",
"usage": {"prompt_tokens": 150, "completion_tokens": 45},
"model": "gpt-4o",
"finish_reason": "stop",
}
app.include_router(v1_router)
app.include_router(v2_router)
Keep deprecated versions running for at least two release cycles. Add a Sunset header to deprecated endpoints so agent developers know when to migrate.
Still reading? Stop comparing — try CallSphere live.
CallSphere ships complete AI voice agents per industry — 14 tools for healthcare, 10 agents for real estate, 4 specialists for salons. See how it actually handles a call before you book a demo.
Agent sessions can last minutes or hours. Implement explicit session timeouts and let agents extend them:
from datetime import datetime, timedelta
SESSION_TIMEOUT = timedelta(minutes=30)
@app.post("/v1/conversations/{conv_id}/heartbeat")
async def heartbeat(conv_id: str):
if conv_id not in conversations_db:
raise HTTPException(status_code=404, detail="Conversation not found")
conversations_db[conv_id]["last_active"] = datetime.utcnow().isoformat()
expires = (datetime.utcnow() + SESSION_TIMEOUT).isoformat()
return {"status": "alive", "expires_at": expires}
Use a request-response pattern with polling. Return a 202 Accepted with a status URL when the agent submits a completion request. The agent polls the status URL until the result is ready. For real-time use cases, consider Server-Sent Events on a dedicated streaming endpoint instead.
Use request bodies for anything complex or sensitive — model parameters, system prompts, tool definitions. Reserve query parameters for simple filtering and pagination on GET endpoints, such as ?limit=50&after=msg_abc123 for message history retrieval.
Beyond the standard 200, 201, and 404, pay special attention to 429 (rate limited) with a Retry-After header that agents can parse, 422 for validation errors with structured error bodies, and 409 for concurrent modification conflicts on the same conversation.
#RESTAPI #AIAgents #APIDesign #FastAPI #Versioning #AgenticAI #LearnAI #AIEngineering

Written by
Sagar Shankaran· Founder, CallSphere
LinkedInSagar Shankaran is the founder of CallSphere, where he builds production AI voice and chat agents deployed across healthcare, hospitality, real estate, and home services. He writes about agentic AI, LLM engineering, and shipping voice agents that handle real calls in production.
See how AI voice agents work for your industry. Live demo available -- no signup required.
A founder's guide to the personal AI assistant market: best AI assistant apps, business-grade options, and how CallSphere's voice agent fits in.
A founder's guide to free AI agents, low-code AI agent builders, and how to know when you should pay for a real platform like CallSphere.
Graphiti is the open-source temporal knowledge graph for AI agents in 2026. Learn how bi-temporal memory beats vector RAG for voice agents and long-running LLMs.
Chatbot app vs ChatGPT in 2026: a founder's clear take on the difference, when to use which, and how a real AI chatbot app development works.
How we built a fault-tolerant HVAC emergency triage and tech-dispatch platform on Kubernetes — three-tier CQRS, 11 micro-agents on the OpenAI Agents SDK + LangGraph, NATS JetStream, DTMF/SMS/WebSocket acceptance, circuit breakers, and an evaluation pipeline that catches regressions before they wake a tech at 3 AM.
Head-to-head: OpenAI Frontier and Anthropic's managed agent stack — strengths, fit, and what each means for enterprise AI voice and chat deployment.
© 2026 CallSphere Inc. All rights reserved.
Made within San Francisco
Watch how CallSphere handles real customer calls, schedules appointments, and processes payments — live.