REST and GraphQL API Design

Resource-oriented REST design, versioning, pagination, errors and idempotency; when GraphQL fits; gRPC for internal calls; and Java implementations of each.

REST design essentials

Topic Guidance
Resources Nouns, plural: /orders/{id}/lines; actions as sub-resources when needed: /orders/{id}/cancellations
Methods GET (safe), PUT (idempotent replace), PATCH (partial), POST (create/non-idempotent), DELETE (idempotent)
Status codes 200/201/202/204; 400 validation; 401 unauthenticated; 403 forbidden; 404; 409 conflict; 422 semantic errors; 429; 5xx
Errors RFC 9457 Problem Details (application/problem+json)
Pagination Cursor-based for large/changing collections; limit maximum page size
Idempotency Idempotency-Key header for POSTs that create side effects
Concurrency ETags + If-Match for optimistic concurrency
Versioning URI major version (/v1) for public APIs; additive changes without new versions; deprecation headers
Contracts OpenAPI 3.1 as source of truth; lint with Spectral; contract tests
@RestController
@RequestMapping("/v1/orders")
class OrderController {
    private final OrderService service;
    OrderController(OrderService service) { this.service = service; }

    @PostMapping
    ResponseEntity<OrderView> create(@RequestHeader("Idempotency-Key") String key,
                                     @Valid @RequestBody CreateOrderRequest req) {
        OrderView created = service.create(key, req);
        return ResponseEntity.created(URI.create("/v1/orders/" + created.id())).eTag(created.version()).body(created);
    }

    @GetMapping
    Page<OrderView> list(@RequestParam(required = false) String cursor, @RequestParam(defaultValue = "20") @Max(100) int limit) {
        return service.list(cursor, limit);
    }
}

@RestControllerAdvice
class Errors {
    @ExceptionHandler(InsufficientStockException.class)
    ProblemDetail stock(InsufficientStockException e) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
        pd.setType(URI.create("https://api.example.com/problems/insufficient-stock"));
        pd.setProperty("sku", e.sku());
        return pd;
    }
}

GraphQL

GraphQL exposes a typed schema; clients request exactly the fields they need in one round trip.

type Query { order(id: ID!): Order }
type Order { id: ID!, status: String!, lines: [OrderLine!]!, customer: Customer! }
@Controller
class OrderGraphQl {
    @QueryMapping Order order(@Argument String id) { return orders.find(id); }
    @BatchMapping Map<Order, Customer> customer(List<Order> orders) { return customers.byOrders(orders); }  // avoids N+1
}
Use GraphQL when Avoid when
Many clients with different data needs Simple CRUD with one client
Aggregating many services (federation) Heavy caching via HTTP/CDN is essential
Rapid front-end iteration Team lacks schema governance and query cost control

Security: depth/complexity limits, persisted queries, field-level authorization, disable introspection in production if needed.

gRPC for internal services

Protobuf contracts, HTTP/2, streaming, generated clients; efficient for service-to-service calls; use with L7 load balancing. Not browser-native (needs gRPC-Web or a gateway).

Interview questions and answers

How do you version APIs without breaking clients?

Prefer additive, backward-compatible changes; new optional fields; never change meanings. Introduce a new major version only for breaking changes, run both versions in parallel, publish deprecation timelines (Deprecation/Sunset headers) and track consumer usage before removal.

REST, GraphQL or gRPC?

REST for public, cacheable, resource-oriented APIs; GraphQL for client-driven aggregation across many sources; gRPC for low-latency internal service calls and streaming.