Backend Engineering

API Design Quiz

API Design Quiz — Study Guide

API Design: A Comprehensive Study Guide

APIs are the backbone of modern software — they let applications talk to each other, power mobile apps, and enable third-party integrations. Designing APIs well means building systems that are predictable, secure, and easy to use. Whether you're building a REST endpoint or a gRPC service, understanding these core concepts will make you a better engineer and prepare you for real-world API challenges.


HTTP Fundamentals & Status Codes

HTTP is the protocol that powers the web. Every API request/response follows its structure: a method, headers, a URL, and optionally a body.

Common HTTP Methods

MethodPurposeIdempotent?Safe?
GETRetrieve data✅ Yes✅ Yes
POSTCreate resource❌ No❌ No
PUTReplace resource✅ Yes❌ No
PATCHPartial update❌ No❌ No
DELETERemove resource✅ Yes❌ No
Idempotency means calling the same request multiple times produces the same result. PUT /users/1 with the same body always results in the same state — safe to retry. POST /users creates a new user each time — not idempotent.

Status Codes You Must Know

  • 200 OK — Request succeeded
  • 201 Created — A new resource was successfully created (use after POST)
  • 204 No Content — Success, but nothing to return (common after DELETE)
  • 400 Bad Request — Client sent invalid data
  • 401 Unauthorized — *Not authenticated* (no valid credentials)
  • 403 Forbidden — *Authenticated but not authorized* (you're logged in, but can't access this)
  • 404 Not Found — Resource doesn't exist
  • 429 Too Many Requests — Rate limit exceeded
  • 500 Internal Server Error — Something broke on the server
  • 💡 401 vs 403: Think of a nightclub. 401 means "I don't know who you are — show your ID." 403 means "I know who you are, but you're not on the VIP list."


    REST & Architecture

    REST (Representational State Transfer) is an architectural style with key constraints:

  • Stateless: Each request contains all needed information
  • Resource-based URLs: /users/42 not /getUser?id=42
  • Use HTTP methods semantically: GET to read, POST to create, etc.
  • HATEOAS

    HATEOAS (Hypermedia As The Engine Of Application State) means responses include links to related actions:

    {
      "id": 42,
      "name": "Alice",
      "_links": {
        "self": "/users/42",
        "orders": "/users/42/orders",
        "delete": "/users/42"
      }
    }

    This lets clients discover available actions dynamically rather than hardcoding URLs.


    Authentication & Security

    Auth Patterns

  • API Keys — Simple tokens passed in headers (X-API-Key: abc123). Easy but hard to rotate.
  • OAuth 2.0 — Delegated access. A user grants your app permission to act on their behalf.
  • JWT (JSON Web Tokens) — Self-contained tokens with encoded claims. Stateless and verifiable.
  • Basic Auth — Base64-encoded username:password. Only use over HTTPS.
  • CORS (Cross-Origin Resource Sharing)

    Browsers block requests from one origin to another by default. CORS headers tell browsers which origins are allowed:

    Access-Control-Allow-Origin: https://myapp.com
    Access-Control-Allow-Methods: GET, POST

    Security Best Practices

  • Always use HTTPS
  • Validate and sanitize all inputs
  • Use rate limiting to prevent abuse
  • Never expose sensitive data in URLs (use headers or body)

  • Pagination

    When returning large datasets, pagination is essential.

    TypeHow It WorksBest For
    Offset?page=2&limit=20Simple, small datasets
    Cursor?after=cursor_xyzLarge/real-time data
    Keyset?after_id=100Sorted, stable datasets
    Cursor-based pagination is preferred over offset when data changes frequently or datasets are large — offset pagination can skip or duplicate records when rows are inserted/deleted during pagination.


    Rate Limiting

    Rate limiting protects your API from abuse and ensures fair usage. Common algorithms:

  • Token Bucket — Tokens refill at a steady rate; burst traffic is allowed
  • Sliding Window — Tracks requests in a rolling time window
  • Fixed Window — Counts requests per fixed interval (e.g., 100 req/minute)
  • HTTP/1.1 429 Too Many Requests
    Retry-After: 30
    X-RateLimit-Limit: 100
    X-RateLimit-Remaining: 0


    API Versioning

    Versioning prevents breaking changes from affecting existing clients.

    /v1/users        ← URL versioning (most common)
    /users (Accept: application/vnd.api.v2+json)  ← Header versioning


    API Gateway

    An API Gateway sits in front of your services and handles:

  • Authentication & authorization
  • Rate limiting
  • Request routing
  • Load balancing
  • Logging & monitoring
  • Think of it as a security checkpoint + traffic director for all incoming API calls.


    Webhooks

    Instead of polling "do you have new data?", webhooks push data to you when events happen.

    Your App ──registers──▶ API: "POST to https://myapp.com/webhook on new order"
    API ──fires──▶ POST https://myapp.com/webhook  { "event": "order.created", ... }

    Always verify webhook signatures to confirm the request is legitimate.


    GraphQL vs REST vs gRPC

    RESTGraphQLgRPC
    ProtocolHTTPHTTPHTTP/2
    Data formatJSONJSONProtobuf (binary)
    FlexibilityFixed endpointsClient-defined queriesStrongly typed contracts
    Best forPublic APIsComplex data needsInternal microservices

    Protobuf

    gRPC uses Protocol Buffers (protobuf) — a binary serialization format that's faster and smaller than JSON. You define a schema:

    message User {
      int32 id = 1;
      string name = 2;
    }

    Content Negotiation

    Clients can request specific formats using the Accept header:
    Accept: application/json
    Accept: application/xml
    The server responds with the Content-Type header indicating what it actually returned.


    Key Takeaways

  • Status codes are semantic: 201 for creation, 401 for unauthenticated, 403 for unauthorized — use them correctly to communicate intent clearly.
  • Idempotent methods (GET, PUT, DELETE) can be safely retried; POST cannot — this matters for reliability and distributed systems.
  • Cursor-based pagination beats offset pagination for large or frequently-updated datasets because it avoids skipped/duplicate records.
  • Rate limiting, CORS, authentication, and HTTPS are non-negotiable security layers — an API gateway is the ideal place to enforce them centrally.
  • Choose your API style by use case: REST for public APIs, GraphQL for flexible data fetching, gRPC/protobuf for high-performance internal services.