Building an API
Designing the contract between clients and your server, covering resources, methods, validation, errors and versioning.
9 min read · Last reviewed November 20, 2026
Building an API
An is a promise. Once clients depend on it, changing it is expensive, so design the contract deliberately and let the agent implement it.
You'll be able to#
- Choose between REST, RPC-style, GraphQL and framework-native server functions
- Specify endpoints, payloads and errors precisely
- Review an API for validation, auth, pagination and error-handling gaps
The mental model#
Client sends request (method + path + headers + body) → server authenticates, authorizes, validates, runs business logic, touches data → server sends response (status + body). Every endpoint should walk through those steps in that order.
Key concepts#
- REST: Resources as nouns (
/orders/123), with HTTP methods as verbs.GETreads,POSTcreates,PATCHupdates part of a record,PUTreplaces it,DELETEremoves it. - RPC / tRPC / Server Actions: Call server functions directly, with types shared end-to-end. This is great when the same codebase owns both the client and the server.
- GraphQL: Clients ask for exactly the fields they want. It's powerful, but adds complexity in caching, auth and queries.
- Schema validation: Validate every input at the boundary (Zod, Valibot, Pydantic). Never trust the client.
- Idempotency: Repeating the same request has the same effect. This matters for payments and retries (
Idempotency-Keyheader). - Pagination: Offset (
?page=3) is simple. Cursor-based (?after=abc) stays stable when items are added or deleted, and scales. - Error format: Use a consistent shape such as
{ error: { code, message, details } }, with correct status codes. - : Caps on requests per user, IP or key. Return
429when the limit is hit. - Versioning:
/v1/…or headers. Only needed when outside clients depend on you. - OpenAPI: A machine-readable spec for REST APIs. It can generate docs, clients and tests.
- Webhooks: Other services calling your API when something happens (for example Stripe telling you a payment succeeded). Verify their signatures.
Decisions you make (not the agent)#
Your call, not the agent's
| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Style | Framework-native (Server Actions/tRPC) for your own app; REST for public or multi-client | Complex client-driven data needs → GraphQL |
| Validation | Zod/Pydantic schema on every input | — |
| Errors | One error shape, correct status codes | — |
| Pagination | Cursor-based for feeds/large lists | Small admin tables → offset |
| Auth | Session cookies for your web app; API keys/OAuth for third parties | See Auth |
| Documentation | OpenAPI for public REST | Internal only → types are enough |
What good output looks like#
- Input validated before any logic runs
- Auth and permission checks on every endpoint ("can this user touch this record?")
- Consistent error responses; no stack traces leaked to clients
- List endpoints paginated by default
Red flags#
- Returning
200with{ success: false } - Fetching a record by ID without checking that the user owns it (, the most common API vulnerability)
- Returning entire DB rows, password hashes included
- No pagination on list endpoints
- Logic copy-pasted across handlers instead of living in a service layer
- Common mistakes: a create or payment endpoint with no protection against retries, so a timeout produces two orders; error responses with a
200status; internal fields returned because the whole database row was serialized; ownership checked on reads but forgotten on updates and deletes
Worked example#
Task: Add POST /v1/orders, which creates an order and charges a card.
You prompt: "Add an endpoint to create an order and charge the card." The agent writes it. When the payment provider fails, the handler returns 200 with { success: false }. Nothing protects against repeats.
What a good result contains: correct status codes, one error shape, and an . The client sends a unique Idempotency-Key header. The server saves the result of the first request with that key and returns the same result for any repeat, so a retry can't create a second order.
The wrong turn: the client's request times out, so the client retries, and the server happily creates and charges a second order. The 200 responses for failures also mean clients can't tell what happened without parsing the body.
How review catches it: replay the same request twice with the same key and confirm you get the same order back, not a new one. Send the same key with a different body and confirm it is refused. Stripe's documentation describes this pattern: the first result is saved and returned for retries, and reusing a key with different parameters is an error. The IETF's Idempotency-Key header proposal, which is still an Internet-Draft and may change, suggests a conflict response while the first request is still running and an error for a key reused with a different payload.
Sample prompts#
Weak vs strong#
Make an API for todos.
Why it fails: No data shape, endpoints, ownership rules, error format or tests, so the agent decides all of it, usually without authorization or validation.
Build a REST API for todos in our Hono + TypeScript + Drizzle/Postgres backend.
Resources: todos belong to a user. Fields: id (uuid), title (1–200 chars),
done (bool), dueAt (nullable timestamp), createdAt, updatedAt.
Endpoints:
- GET /v1/todos?cursor=&limit= (max 100, default 20, newest first)
- POST /v1/todos
- PATCH /v1/todos/:id
- DELETE /v1/todos/:id
Rules: All endpoints require the session user; users may only access their own
todos (return 404, not 403, for others' todos). Validate with Zod. Errors use
{ error: { code, message } }. Never return internal fields.
Also: generate an OpenAPI spec, and write integration tests covering auth,
ownership, validation errors, and pagination. Run them.Why it works: It defines the data shape, the full contract, ownership rules, error format and the tests to run.
What changed
- Data shape is spelled out, including limits
- Endpoints and pagination are listed
- Ownership is a rule, with the exact status code to return
- Validation and errors have a named format
- Tests cover auth, ownership, validation and pagination, and must be run
Review every API route in this project. For each, check: authentication, authorization/ownership, input validation, error handling, pagination, and over-fetching. Output a table of findings ranked by severity.
Why it works: It lists the checks that agents skip most often, and asks for a ranked table you can work through.
Make a create endpoint safe to retry#
Make POST /v1/orders safe to retry. Accept an Idempotency-Key header. Store the key with the response of the first request. A repeat with the same key and the same body returns the saved response and creates nothing. The same key with a different body returns an error. A repeat that arrives while the first is still running returns a conflict. Document the key's lifetime. Write tests for each case, run them and show the output.
Why it works: It lists the four situations an idempotency key must handle, so the agent builds the whole behaviour and not just the happy path.
Replay and break it#
Test the order endpoint the way a flaky client would: send the same request twice with the same key; send it with different bodies and the same key; send it concurrently ten times; send it with no key. Show each response status and body, and the number of orders created in the database afterwards.
Why it works: The final count is the proof. If it isn't one order, the endpoint isn't .
Explain what happens on retry#
For every endpoint that creates or changes data, explain what happens if the client sends the request twice (a timeout and retry). State whether it is safe, what protects it, and what you would change if it isn't. Mark anything you haven't verified.
Why it works: It forces the agent to think about retries for every write, which is the case it most often forgets.
Check your understanding#
Check your understanding
Checklist#
- Every input is validated before any logic runs
- Each endpoint checks authentication and the user's access to the specific record
- Errors use one shape and correct status codes, and never leak internals
- List endpoints are paginated
- Create and payment endpoints are safe to retry
- Integration tests cover auth, ownership, validation, pagination and retries
Go deeper#
- Microsoft REST API Guidelines
- OWASP API Security Top 10
- OpenAPI Specification
- Stripe: Idempotent requests: a widely used real-world design
- IETF draft: The Idempotency-Key HTTP Header Field: a proposed standard; still a draft
- Authentication & authorization: ownership checks and sessions
- Reviewing and verifying AI output