Library

Volume 1 · Microservices, APIs & Event-Driven Architecture

Notebook
Sign in

Section 8

API Design

2,459 words · about 11 min

8.1 REST Maturity Model (Richardson Maturity Model)

Level Description Example
Level 0 Single endpoint, single HTTP verb, action encoded in body (“Swamp of POX”) POST /api with {"action": "getOrder", "id": 123}
Level 1 Multiple resource URIs, still mostly one verb POST /orders, POST /customers
Level 2 Proper HTTP verbs and status codes per resource GET /orders/123, DELETE /orders/123
Level 3 HATEOAS — response includes hypermedia links to legal next actions Response body carries _links

Most production “REST” APIs stop at Level 2, which is a pragmatic and acceptable choice for internal/B2B APIs. Level 3 (true REST/HATEOAS) is valuable for APIs with many long-lived client integrations where the server needs freedom to evolve workflows without breaking clients.

GET    /api/v1/orders              # List orders
GET    /api/v1/orders/{id}         # Get order by id
POST   /api/v1/orders              # Create order
PUT    /api/v1/orders/{id}         # Full replace
PATCH  /api/v1/orders/{id}         # Partial update
DELETE /api/v1/orders/{id}         # Delete

# Sub-resources
GET    /api/v1/orders/{id}/items
GET    /api/v1/customers/{id}/orders

# Filtering, sorting, pagination
GET /api/v1/orders?status=PENDING&sort=createdAt,desc&page=0&size=20

# HATEOAS (Level 3)
{
  "id": "ord-123",
  "status": "PENDING",
  "_links": {
    "self":   { "href": "/api/v1/orders/ord-123" },
    "cancel": { "href": "/api/v1/orders/ord-123/cancel", "method": "POST" },
    "items":  { "href": "/api/v1/orders/ord-123/items" }
  }
}

HTTP Status Codes — Correct Usage

Code Meaning When to Use
200 OK Success GET/PUT/PATCH returning data
201 Created Resource created POST that creates a resource (include Location header)
204 No Content Success, no body DELETE, or PUT/PATCH with no response body
400 Bad Request Invalid input Validation errors, malformed JSON
401 Unauthorized Not authenticated Missing/invalid token
403 Forbidden Not authorized Valid token, insufficient permissions
404 Not Found Resource doesn’t exist GET/PUT/DELETE on non-existent resource
409 Conflict Conflicting state Duplicate resource, optimistic concurrency clash
422 Unprocessable Entity Semantic error Well-formed request, business-rule violation
429 Too Many Requests Rate limited Include Retry-After header
500 Internal Server Error Server fault Unhandled exception — never leak stack traces

Standardized Error Response

public class ApiError
{
    public string Code { get; set; }          // "VALIDATION_ERROR"
    public string Message { get; set; }        // Human summary
    public string TraceId { get; set; }         // For support correlation
    public List<FieldError> Errors { get; set; }
}
{
  "code": "VALIDATION_ERROR",
  "message": "One or more validation errors occurred",
  "traceId": "abc-123-def",
  "errors": [
    { "field": "email", "message": "Must be a valid email address" },
    { "field": "quantity", "message": "Must be greater than 0" }
  ]
}
# FastAPI equivalent — standardized error handling
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ValidationError
import uuid

app = FastAPI()

class FieldError(BaseModel):
    field: str
    message: str

class ApiError(BaseModel):
    code: str
    message: str
    trace_id: str
    errors: list[FieldError] = []

@app.exception_handler(ValidationError)
async def validation_handler(request: Request, exc: ValidationError):
    trace_id = str(uuid.uuid4())
    return JSONResponse(
        status_code=400,
        content=ApiError(
            code="VALIDATION_ERROR",
            message="One or more validation errors occurred",
            trace_id=trace_id,
            errors=[FieldError(field=".".join(str(p) for p in e["loc"]), message=e["msg"])
                    for e in exc.errors()],
        ).model_dump(),
    )

8.2 gRPC vs REST vs GraphQL — Full Comparison

Aspect REST gRPC GraphQL
Protocol HTTP/1.1 (or 2) HTTP/2 HTTP (usually 1.1)
Payload format JSON (text) Protocol Buffers (binary) JSON
Contract OpenAPI/Swagger (often optional) .proto file (mandatory, strongly typed) GraphQL SDL schema
Performance Good Excellent (3–10x faster; binary + HTTP/2 multiplexing) Good, but resolver overhead can be significant
Browser support Native Limited (needs grpc-web + proxy) Native
Streaming Limited (SSE, WebSocket, chunked) Native bidirectional streaming Subscriptions (usually over WebSocket)
Over/under-fetching Common problem (fixed response shape) Fixed per RPC method Solved — client specifies exact fields
Caching Easy — HTTP caching semantics (ETag, Cache-Control) Hard — not HTTP-cache friendly Hard — single endpoint, POST-based, needs custom caching (Apollo/Relay normalized cache)
Tooling maturity Very mature, ubiquitous Mature, strong in polyglot microservices Mature but heavier client tooling needed
Versioning URI/header versioning .proto field evolution (add fields, never renumber) Schema evolution — add fields, deprecate old ones, no hard versions
Discoverability Swagger UI Reflection API / buf registry GraphQL Playground/introspection
Learning curve Low Medium (protobuf toolchain, codegen) Medium–High (schema design, N+1 resolver pitfalls)
Best for Public APIs, browser clients, simple CRUD Service-to-service, mobile, low-latency streaming, ML inference calls Client-driven data shaping (many client types with different needs), aggregation gateways
Security model Standard OAuth2/JWT, WAF-friendly mTLS commonly paired with it; less WAF tooling maturity Needs query complexity/depth limiting (a single query can trigger unbounded resolver fan-out)

Decision heuristic:

  • REST — default choice for public/partner-facing APIs and simple CRUD; maximum interoperability and cacheability.
  • gRPC — internal service-to-service calls, especially latency-sensitive (ML inference, real-time systems) or where you want compile-time-checked contracts across languages.
  • GraphQL — you have several very different client shapes (mobile, web, partner) hitting the same underlying data and don’t want to build/maintain a BFF per client, or the domain graph is naturally deep (social graphs, catalogs with many nested relations).
// gRPC contract example — ML inference service
syntax = "proto3";

service DenialPrediction {
  rpc PredictDenial (ClaimRequest) returns (PredictionResponse);
  rpc BatchPredict (stream ClaimRequest) returns (stream PredictionResponse);
}

message ClaimRequest {
  string claim_id = 1;
  string payer_id = 2;
  repeated string cpt_codes = 3;
  repeated string icd10_codes = 4;
  double billed_amount = 5;
}

message PredictionResponse {
  string claim_id = 1;
  double denial_probability = 2;
  repeated RiskFactor risk_factors = 3;
}
# gRPC server in Python
import grpc
from concurrent import futures
import prediction_pb2, prediction_pb2_grpc

class DenialPredictionServicer(prediction_pb2_grpc.DenialPredictionServicer):
    def PredictDenial(self, request, context):
        probability = model.predict(request.cpt_codes, request.icd10_codes)
        return prediction_pb2.PredictionResponse(
            claim_id=request.claim_id,
            denial_probability=probability,
        )

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
prediction_pb2_grpc.add_DenialPredictionServicer_to_server(DenialPredictionServicer(), server)
server.add_insecure_port("[::]:50051")
server.start()
server.wait_for_termination()

8.3 API Versioning Strategies

Strategy Example Pros Cons
URI path /api/v1/orders Explicit, easy to route at the gateway, easy to test URL churn; technically violates “URI identifies a resource, not a version of it”
Query parameter /api/orders?version=2 Simple to add Easy to forget; hurts HTTP caching (same URL, different content)
Header Accept-Version: 2.0 or Accept: application/vnd.api.v2+json Clean URLs Less discoverable/testable in a browser; harder to route at some gateways
Media type (content negotiation) Custom Accept header per version Most “RESTful”-pure Highest complexity, worst tooling support

Recommendation used in practice: URI versioning for major/breaking changes (v1 → v2), and purely additive, backward-compatible changes (new optional fields, new endpoints) ship with no version bump at all. Combine with a Sunset header and a documented deprecation window (commonly 3–6 months) before retiring an old version, and track version usage in API analytics so you know when it’s safe to remove.

builder.Services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ReportApiVersions = true;
    options.ApiVersionReader = new UrlSegmentApiVersionReader();
});

[ApiController]
[Route("api/v{version:apiVersion}/orders")]
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class OrdersController : ControllerBase
{
    [HttpGet, MapToApiVersion("1.0")]
    public IActionResult GetV1() => Ok(/* v1 shape */);

    [HttpGet, MapToApiVersion("2.0")]
    public IActionResult GetV2() => Ok(/* v2 shape with new fields */);
}

8.4 BFF (Backend for Frontend) Pattern

Mobile App  ──▶ Mobile BFF  ──┐
Web App     ──▶ Web BFF     ──┤──▶ Shared Microservices
Partner API ──▶ B2B BFF     ──┘

Why BFF? Each frontend has different data needs — mobile wants small payloads,
web wants richer aggregated data, partners want a curated stable contract.
A BFF aggregates and shapes data per client, avoiding both over-fetching
(wasted bandwidth) and under-fetching (extra round trips / N+1 client calls).

BFF vs plain API Gateway: a gateway is a single cross-cutting layer (auth, rate-limit, routing) shared by all clients. A BFF goes further — it is itself a small, purpose-built backend per client type, often owned by the frontend team, that composes calls to multiple downstream services into exactly the shape that client needs.

// BFF composing multiple downstream calls for a mobile client
public class MobileOrderBffController : ControllerBase
{
    [HttpGet("orders/{id}/summary")]
    public async Task<IActionResult> GetOrderSummary(int id)
    {
        var order = await _orderClient.GetOrderAsync(id);
        var customer = await _customerClient.GetMiniProfileAsync(order.CustomerId);
        // Mobile only needs a trimmed shape — no full address, no full history
        return Ok(new MobileOrderSummary(order.Id, order.Status, order.Total, customer.DisplayName));
    }
}

8.5 API Gateway Patterns

External Clients
    │
[API Gateway — Kong / AWS API Gateway / Apigee / Azure APIM / YARP / Ocelot]
    │
    ├── Authentication & Authorization (JWT validation)
    ├── Rate Limiting & Throttling
    ├── Request/Response Transformation
    ├── SSL Termination
    ├── Response Caching (edge caching)
    ├── Logging & Analytics
    ├── Circuit Breaking
    └── Traffic Routing (canary, blue-green, A/B)
    │
[Internal Services]
    ├── Order Service
    ├── Product Service
    └── User Service
Gateway Type Best For
Azure API Management Managed / policy-rich Enterprise, policy XML pipelines, developer portal
AWS API Gateway Managed, serverless-friendly Lambda-backed APIs, pay-per-call
Kong Open-source/Enterprise Multi-cloud, huge plugin ecosystem
Ocelot .NET library Lightweight .NET-native gateway
YARP .NET reverse proxy High-performance .NET proxy, full code control
Envoy / Istio Ingress Gateway Data-plane proxy When you already run a service mesh

8.6 API Security, Rate Limiting, Idempotency & Pagination

// OAuth2/JWT validation
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://login.microsoftonline.com/{tenantId}/v2.0";
        options.Audience = "api://my-api-client-id";
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(1)
        };
    });

// Rate limiting (.NET 8+)
builder.Services.AddRateLimiter(options =>
{
    options.AddSlidingWindowLimiter("sliding", opt =>
    {
        opt.Window = TimeSpan.FromMinutes(1);
        opt.SegmentsPerWindow = 6;
        opt.PermitLimit = 100;
    });
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
# Idempotency key handling — FastAPI + Redis
import json
from fastapi import FastAPI, Header
import redis.asyncio as redis

app = FastAPI()
r = redis.Redis()

@app.post("/api/v1/orders")
async def create_order(request: dict, idempotency_key: str = Header(None)):
    if idempotency_key:
        cached = await r.get(f"idempotency:{idempotency_key}")
        if cached:
            return json.loads(cached)

    order = await process_order(request)  # normal creation logic

    if idempotency_key:
        await r.set(f"idempotency:{idempotency_key}", json.dumps(order), ex=86400)
    return order
// Cursor-based (keyset) pagination — scales far better than OFFSET for large tables
[HttpGet]
public async Task<PagedResponse<OrderDto>> GetOrders(
    [FromQuery] string? cursor, [FromQuery] int limit = 20)
{
    int lastId = cursor != null ? DecodeCursor(cursor) : 0;
    var orders = await _context.Orders
        .Where(o => o.Id > lastId)
        .OrderBy(o => o.Id)
        .Take(limit + 1)
        .ToListAsync();

    bool hasMore = orders.Count > limit;
    var data = orders.Take(limit).Select(MapToDto).ToList();
    return new PagedResponse<OrderDto>
    {
        Data = data, HasMore = hasMore,
        NextCursor = hasMore ? EncodeCursor(data.Last().Id) : null
    };
}

8.7 Interview Q&A

Q1: How do you design a REST API that needs to support both mobile and web clients with very different data needs?

Three options, escalating in complexity. (1) Sparse fieldsets — GET /api/orders?fields=id,status,total for mobile vs the full field list for web; cheapest, works for many cases. (2) BFF pattern — separate mobile-bff and web-bff layers that call the same shared microservices but aggregate/trim per client; optimized per client at the cost of more code to maintain. (3) GraphQL — client specifies exactly the fields/relations it needs in one request; best when the divergence between clients is large and constantly shifting. I’d start with sparse fieldsets, move to a BFF as complexity grows, and only reach for GraphQL if there are many client types with genuinely different, evolving data shapes.

Q2: How do you handle API versioning when you need to make a breaking change?

First, avoid the breaking change if at all possible — add new fields, don’t rename or remove existing ones, and treat additive changes as non-breaking (no version bump needed). When a break truly is unavoidable, cut a new URI version (/v2/) and run it alongside v1 during a transition window; announce deprecation via a Sunset header and give consumers 3–6 months notice. Track v1 usage in API analytics and don’t retire it until usage drops below a threshold. For internal service-to-service contracts I add consumer-driven contract tests (e.g., Pact) in CI so a breaking change fails the pipeline before it ships.

Q3: Explain idempotency in APIs and how you implement it.

An idempotent operation returns the same result no matter how many times you call it with the same input — critical for reliability, because a client that times out and retries must not double-charge a customer. I implement it with an Idempotency-Key header the client generates once per logical operation; the server looks up that key before processing, and if found, returns the previously stored result without re-executing the operation. I store the key with its result and a TTL (Redis, or a DB table with key + expiry + response) — 24 hours is a common window. Note that HTTP GET and DELETE are naturally idempotent by spec; PUT should be designed idempotent by nature (a full replace, not a delta); POST needs this explicit mechanism because it’s inherently non-idempotent (create).

Q4: What’s your API governance strategy for an enterprise with 50+ APIs?

Three pillars — standards, tooling, process. Standards: an API style guide (naming, versioning, error format, pagination, security) versioned in git and reviewed periodically. Tooling: an API Gateway as the enforcement point for auth, rate limiting, and logging; mandatory OpenAPI specs stored with the code; a developer portal for discoverability; automated contract testing (Pact) to catch breaking changes before release. Process: every new API goes through an architecture review before development; breaking changes require a major version bump plus a deprecation timeline; usage analytics inform when unused APIs can be retired.

Q5: How do you prevent and handle common API security vulnerabilities?

Authentication via OAuth2/JWT with issuer/audience/expiry validation; authorization via RBAC/ABAC checked at the resource level, not just the endpoint level; input validation (reject unexpected fields, enforce max lengths) with a library like FluentValidation; per-user and per-IP rate limiting with 429 + Retry-After; restrictive CORS; parameterized queries everywhere (ORMs do this by default) to prevent injection; DTOs instead of binding requests directly to entities to prevent mass assignment; never exposing internal IDs, stack traces, or connection strings in responses; HTTPS enforced with HSTS; and audit logging of all authentication events and sensitive mutations.