Backend Development

HTTP API Design

Design predictable resources, methods, status codes, JSON contracts, and error responses.

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

  • GET reads and should not change application state.
  • POST commonly creates or starts a non-idempotent operation.
  • PUT replaces a resource representation and is intended to be idempotent.
  • PATCH applies a partial change; whether repeated application is safe depends on the patch design.
  • DELETE removes 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

SituationStatus
Successful read or update200 OK
Successful creation201 Created
Successful action with no body204 No Content
Malformed request400 Bad Request
Missing or invalid credentials401 Unauthorized
Authenticated but not permitted403 Forbidden
Resource absent404 Not Found
State conflict or duplicate409 Conflict
Valid media type but validation failed422 Unprocessable Entity
Unsupported media type415 Unsupported Media Type
Rate limit exceeded429 Too Many Requests
Unexpected server failure500 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 200 for every outcome: clients must parse messages to know what happened.
  • Using map[string]any for 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.

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.

Copyright © 2026