HTTP API Design
What you will learn
By the end of this lesson, you will be able to:
- design resource-oriented routes and choose appropriate methods;
- separate request, domain, and response types;
- return consistent status codes and error bodies;
- reason about idempotency, pagination, and API evolution;
- test the observable HTTP contract.
Mental model: the API is a contract
Clients depend on paths, methods, status codes, headers, and JSON shapes. Once published, accidental changes can break software you do not control.
Design the contract before optimising handler code.
Model resources with nouns
GET /lessons list lessons
POST /lessons create a lesson
GET /lessons/{id} retrieve one lesson
PATCH /lessons/{id} partially update a lesson
DELETE /lessons/{id} delete a lesson
Use action endpoints only when the operation does not map clearly to resource state, and name them deliberately.
Method semantics
GETreads and should not change application state.POSTcommonly creates or starts a non-idempotent operation.PUTreplaces a resource representation and is intended to be idempotent.PATCHapplies a partial change; whether repeated application is safe depends on the patch design.DELETEremoves a resource and is intended to be idempotent from the client's desired-state perspective.
Idempotent means repeating the same request has the same intended effect, not necessarily the same response or internal side effects.
Separate transport and domain types
type createLessonRequest struct {
Title string `json:"title"`
}
type lessonResponse struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
}
Do not expose database models automatically. Request types express what clients may send; response types express the public contract; domain types express business meaning.
Decode one bounded JSON value
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
return fmt.Errorf("decode JSON: %w", err)
}
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("request body must contain one JSON value")
}
return nil
}
The second decode rejects extra JSON values. Decide whether unknown fields should be rejected or ignored, then keep that policy consistent.
Write responses consistently
func writeJSON(w http.ResponseWriter, status int, value any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(value)
}
For high-assurance code, encode into a buffer before sending headers if an encoding failure must still produce a controlled error response.
Useful creation response:
HTTP/1.1 201 Created
Location: /lessons/lesson-42
Content-Type: application/json
Stable error shape
type errorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"`
}
Code is stable for program logic. Message is safe text for people. Fields can describe validation failures.
Never return stack traces, SQL messages, filesystem paths, tokens, or raw internal errors to a client.
Status-code guide
| Situation | Status |
|---|---|
| Successful read or update | 200 OK |
| Successful creation | 201 Created |
| Successful action with no body | 204 No Content |
| Malformed request | 400 Bad Request |
| Missing or invalid credentials | 401 Unauthorized |
| Authenticated but not permitted | 403 Forbidden |
| Resource absent | 404 Not Found |
| State conflict or duplicate | 409 Conflict |
| Valid media type but validation failed | 422 Unprocessable Entity |
| Unsupported media type | 415 Unsupported Media Type |
| Rate limit exceeded | 429 Too Many Requests |
| Unexpected server failure | 500 Internal Server Error |
Teams differ on some client-error choices. Consistency and clear documentation matter more than arguing over one reasonable mapping.
Pagination
Do not return an unbounded collection. Offset pagination is easy to understand but can become slow or inconsistent for frequently changing large data sets. Cursor pagination can provide stable traversal but requires a well-defined ordering and opaque cursor handling.
Return navigation information without exposing database internals.
API evolution
- Add optional response fields when clients tolerate unknown fields.
- Avoid changing the meaning or type of existing fields.
- Make new request fields optional or provide a transition path.
- Version only when compatibility cannot be maintained, and document the support policy.
- Test the contract from the client's point of view.
Common mistakes
- Returning
200for every outcome: clients must parse messages to know what happened. - Using
map[string]anyfor stable contracts: type guarantees and documentation disappear. - Leaking internal errors: attackers gain details and clients become coupled to implementation text.
- Ignoring body limits: one request can consume excessive memory or disk.
- Paginating without a deterministic order: records can be skipped or repeated unpredictably.
Practice
Design and implement POST /lessons and GET /lessons/{id}. Reject a missing title, reject unknown fields, limit body size, return a stable validation error, set Location on creation, and test every status code.
func (h *Handler) createLesson(w http.ResponseWriter, r *http.Request) {
var request createLessonRequest
if err := decodeJSON(w, r, &request); err != nil {
h.writeError(w, http.StatusBadRequest, "invalid_json", "Request body is not valid JSON.", nil)
return
}
request.Title = strings.TrimSpace(request.Title)
if request.Title == "" {
h.writeError(w, http.StatusUnprocessableEntity, "validation_failed", "Check the highlighted fields.", map[string]string{
"title": "Title is required.",
})
return
}
lesson, err := h.lessons.Create(r.Context(), request.Title)
if err != nil {
h.handleApplicationError(w, err)
return
}
w.Header().Set("Location", "/lessons/"+url.PathEscape(lesson.ID))
_ = writeJSON(w, http.StatusCreated, toLessonResponse(lesson))
}
handleApplicationError maps known domain errors to safe public responses and logs unexpected errors at the boundary. Tests should use httptest and assert status, headers, and decoded JSON—not private helper calls.
Summary
- Treat paths, methods, status codes, headers, and bodies as a versioned contract.
- Keep transport types separate from business and storage representations.
- Bound and validate all input.
- Return stable machine-readable errors without leaking internal details.
- Test behaviour through HTTP rather than only testing private helpers.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.