---
title: Building an API
summary: Designing the contract between clients and your server, covering resources, methods, validation, errors and versioning.
section: backend
phase: build
order: 1
last_reviewed: 2026-11-20
---

# Building an API

An API 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. `GET` reads, `POST` creates, `PATCH` updates part of a record, `PUT` replaces it, `DELETE` removes 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 N+1 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-Key` header).
- **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.
- **Rate limiting:** Caps on requests per user, IP or key. Return `429` when 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.

> **Note:** OWASP's API Security Top 10 (2023 edition) lists **Broken Object Level Authorization** first. It is the flaw behind "fetching a record by ID without checking that the user owns it" in the red flags below, so the ownership check belongs in every handler.

## Decisions you make (not the agent)
| 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](/docs/backend/authentication-and-authorization.md) |
| 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 `200` with `{ success: false }`
- Fetching a record by ID without checking that the user owns it (IDOR, 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 agent mistakes:** a create or payment endpoint with no protection against retries, so a timeout produces two orders; error responses with a `200` status; 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 **idempotency key**. 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
```compare
## Weak
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.
## Strong
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
```

```text
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
```text
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
```text
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 idempotent.

### Explain what happens on retry
```text
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

```quiz
Q: A client times out on POST /orders and retries. What prevents a duplicate order?
- [ ] A longer timeout
- [x] An idempotency key: the server saves the first result and returns it for repeats
- [ ] Using PUT instead of POST in the client
> Why: The server can't know whether the first request arrived. A key lets it recognize the retry and return the same result.

---

Q: A payment fails. Which response is best?
- [ ] 200 with { success: false }
- [x] An error status code with the standard error shape
- [ ] 200 with an empty body
> Why: Clients, proxies and monitoring rely on status codes. A 200 for a failure hides problems.

---

Q: A user changes /orders/1042 to /orders/1043 and sees someone else's order. What was missing?
- [ ] Rate limiting
- [x] An ownership check (object-level authorization) on that endpoint
- [ ] Pagination
> Why: Being logged in isn't the same as being allowed to see that record. Check access to the specific object on every request.
```

## 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](https://github.com/microsoft/api-guidelines)
- [OWASP API Security Top 10](https://owasp.org/API-Security/)
- [OpenAPI Specification](https://spec.openapis.org/oas/latest.html)
- [Stripe: Idempotent requests](https://docs.stripe.com/api/idempotent_requests): a widely used real-world design
- [IETF draft: The Idempotency-Key HTTP Header Field](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/): a proposed standard; still a draft
- [Authentication & authorization](/docs/backend/authentication-and-authorization.md): ownership checks and sessions
- [Reviewing and verifying AI output](/docs/ai-agents/reviewing-ai-output.md)
