08. Programming & Technologies
REST APIs, HTTP and JSON for Agents
Most agent tools are HTTP clients: REST methods, status codes, JSON bodies, auth headers, timeouts, and idempotent retries. The model proposes tool args; your handler builds the request, validates responses with schemas, and maps status classes into safe tool results the agent can reason about.
What you will learn
- Map agent tools to REST methods and resources
- Classify 2xx / 4xx / 5xx for retry policy
- Validate JSON requests and responses with schemas
- Design timeouts, auth headers, and idempotency keys
- Answer interview questions with short, solid answers
Definition
REST APIs expose resources over HTTP using methods (GET, POST, PUT, PATCH, DELETE), status codes, and usually JSON bodies. For agents, each tool is often a thin, validated wrapper around one or more HTTP calls β not a prompt that invents URLs and Authorization headers.
JSON is the lingua franca between LLM tool args, your handler, and upstream APIs. Treat every payload as untrusted until a schema says otherwise.
Introduction
This lesson (#4 in Programming & Technologies) follows LLM Providers. Providers and tools both ride HTTP/JSON; now make that transport production-safe for agent loops.
Next: SQL and NoSQL Databases for Agent Backends.
Why agents need HTTP literacy
- Almost every external tool is an API call
- Agent loops amplify retries β bad policy burns money
- Wrong method semantics cause duplicate writes
- Status literacy decides whether to retry or fix args
- Schemas stop garbage JSON from becoming side effects
REST methods for tools
- GET - read; safe and idempotent; prefer for lookups
- POST - create or non-idempotent actions; use idempotency keys
- PUT - replace resource; often idempotent by full body
- PATCH - partial update; know upstream semantics
- DELETE - remove; confirm idempotent delete behavior
- Map one tool to one clear intent β do not expose raw βHTTP playgroundβ tools
Agent β tool β REST flow
Keep a hard boundary: the LLM emits structured tool args; your code owns URL construction, headers, and HTTP.
- Validate tool args (Pydantic/Zod) before fetch
- Build path/query/body from allowlisted templates
- Attach auth from secrets manager / env
- Enforce connect + read timeouts
- Normalize response into a small tool-result schema for the model
JSON contracts
- Content-Type: application/json β set and check it
- Prefer explicit field names over free-form blobs
- Parse then validate β do not pass raw dicts downstream
- Distinguish transport JSON errors from business error envelopes
- Return concise JSON tool results β huge dumps waste context
- Paginate list endpoints; teach tools limit/cursor args
Status codes and retries
Classify before you retry or tell the model βtry again.β
- 2xx - validate body schema; return success tool result
- 4xx - usually fix input/auth; do not hammer retries
- 429 - respect Retry-After; exponential backoff with jitter
- 5xx - retry only idempotent calls; cap attempts
- Network timeouts - retry policy like 5xx if idempotent
- Surface structured errors to the model (code, message, retryable)
Idempotency and safety
- Idempotency-Key on create/payment-like POSTs
- Deduplicate tool calls with the same key in one run
- Least-privilege API tokens scoped per tool
- Allowlist hosts β no open SSRF via model-supplied URLs
- Log method, path template, status, latency β not secrets
- Rate-limit outbound calls per tenant and per tool
Map to earlier modules
- HTTP tools = Module 05 tool-use in the wild
- Schemas = Python Pydantic / TS Zod lessons
- Providers = also HTTP clients with the same timeout rules
- Agent frameworks call your tools; they do not replace HTTP hygiene
- Next databases lesson: persist what APIs return
Failure modes
- Model-built URLs or headers (SSRF / credential leak)
- Retrying non-idempotent POSTs β duplicate orders
- Ignoring 401/403 and looping until budget dies
- Passing multi-megabyte JSON back into the prompt
- No timeouts β hung tools freeze the whole agent run
Program / implementation notes
Implement one tool as: schema in β allowlisted request β timeout β status classify β schema out. Add idempotency keys before any write tool goes to production.
- Use httpx/fetch with explicit timeouts; prefer async in agent services
- Next: SQL and NoSQL Databases for Agent Backends
Advantages and limitations
- Advantage: REST/JSON is universal across SaaS tools
- Advantage: clear status semantics for agent control flow
- Advantage: schemas make tool results model-friendly
- Limitation: chatty agent loops multiply API cost and rate limits
- Limitation: poorly designed APIs force awkward multi-call tools
- Limitation: HTTP alone does not give transactions across systems
Key points
- Agent tools wrap HTTP β models must not own raw requests.
- Map tools to clear REST intents (read vs write).
- Validate JSON both ways with schemas.
- Classify 2xx/4xx/5xx before retrying.
- Idempotency keys protect write tools under retries.
- Timeouts, allowlists, and scoped auth are mandatory.
FAQs
Should agents call APIs directly with free-form URLs?
No. Use named tools with allowlisted paths and server-side auth. Free-form URL tools invite SSRF and secret leakage.
When is a retry safe?
When the operation is idempotent (or protected by an Idempotency-Key) and the error is transient (timeouts, 429, many 5xx).
How much JSON should return to the model?
A small, schema-validated summary of what the agent needs next β not the entire upstream payload.
REST vs GraphQL for agent tools?
Either can work. REST is the common default for SaaS. GraphQL needs equally strict schemas and query allowlists β do not let the model invent arbitrary queries.
Interview questions
- How should an agent call a REST API?
Answer Through a typed tool handler that validates args, builds an allowlisted HTTP request with server-side auth and timeouts, then returns a schema-checked JSON tool result.
- How do status codes affect agent retries?
Answer 2xx succeed; most 4xx need fixed inputs (except 429 backoff); 5xx/timeouts may retry only if the call is idempotent and attempts are capped.
- What is an Idempotency-Key for agents?
Answer A client-generated key on create/write requests so retries do not create duplicate resources when the agent or network repeats a POST.
- How do you prevent SSRF in agent tools?
Answer Never accept arbitrary URLs from the model; allowlist hosts/paths, block link-local/metadata IPs, and construct requests in your code.
- Why validate JSON responses?
Answer Upstream APIs drift and return error envelopes; schemas catch shape bugs before bad data enters the next LLM turn or your database.
- What HTTP settings matter most for agent loops?
Answer Connect/read timeouts, retry/backoff policy, rate limits, and logging of status/latency per tool β without these, one hung call stalls the agent.
Related topics
Practice task
Complete each numbered practice step in a notebook or doc before opening the next lesson.
- Design a βcreate_ticketβ tool: method, path template, request schema, response schema.
- Write retry rules for 400, 401, 429, 500, and timeout for that tool.
- List headers your handler sets (including where the token comes from).
- Draft the JSON tool-result shape returned to the model on success and on failure.
- Answer interview questions 1, 2, and 3 in two sentences each.