Core engineeringBackendBeginner → Advanced

API Engineering: REST, HTTP, GraphQL and Beyond

How clients and servers talk, how to design APIs people can depend on, and how real systems handle auth, retries, caching, rate limits, webhooks and failure.

The short answerAn API (application programming interface) is a contract that says how one piece of software can ask another for data or actions: which endpoints exist, what to send, what comes back and what each status code means. Most web APIs are REST over HTTP: resources such as /users/42 manipulated with GET, POST, PUT, PATCH and DELETE. A production API also needs consistent errors, pagination, versioning, idempotent retries, authentication, authorization, caching and rate limits.

Spring Boot handbook
01Fundamentals

What is an API?

API stands for application programming interface: a contract that defines how one piece of software can request data or behaviour from another.

Client

The caller: a React app, an Android app, another backend service, a CLI or an IoT device.

Server

Receives the request, validates it, applies business rules, talks to dependencies and responds.

Contract

Endpoints, methods, request formats, auth, response schemas, status codes and behaviour.

Basic API communication
Client
HTTP request
Backend API
Database
HTTP response
02Architecture

API styles and audiences

REST and GraphQL are the best known, but production systems also use RPC, gRPC, WebSockets, webhooks and, occasionally, SOAP.

  1. REST

    Resources over HTTP
    Model
    Resources identified by URLs, manipulated with HTTP methods, usually JSON.
    Good fit
    Public APIs, CRUD services, web and mobile backends.
  2. GraphQL

    Typed query language
    Model
    One typed schema; clients ask for exactly the fields they need.
    Good fit
    Rich frontends with complex, changing data needs.
  3. RPC / gRPC

    Remote operations
    Model
    Call named procedures (createInvoice); gRPC uses Protocol Buffers over HTTP/2.
    Good fit
    Fast, strongly typed service-to-service calls.
  4. WebSocket

    Persistent, two-way
    Model
    A long-lived connection where both sides send messages any time.
    Good fit
    Chat, live dashboards, collaboration, games.
  5. Webhook

    Server push
    Model
    The provider calls your endpoint when an event happens.
    Good fit
    Payment updates, Git events, delivery notifications.
  6. SOAP

    XML messaging
    Model
    XML envelopes with formal WSDL contracts and WS-* standards.
    Good fit
    Legacy enterprise and banking integrations.

Who the API is for

Public API

For outside developers and customers: needs great docs, stable contracts, auth, quotas and backward compatibility.

Internal API

Used inside the organisation: still needs contracts, auth, versioning and observability.

Partner API

For approved partners, under controlled credentials, permissions and agreements.

Composite API

Combines several operations into one call to save client round trips.

03HTTP

The HTTP foundation

Most web APIs run on HTTP. Understand HTTP and REST stops being mysterious.

URL

Where the request goes: https://api.example.com/api/v1/users/42?include=orders

Method

What you intend: GET, POST, PUT, PATCH, DELETE.

Headers

Metadata: Authorization, Accept, Content-Type, Cache-Control, X-Request-ID.

Body

Optional content, usually JSON, but also form data, XML or binary.

Anatomy of a URL
PartExampleMeaning
SchemehttpsThe protocol.
Hostapi.example.comThe server's domain.
Base path/api/v1Common prefix, often with the version.
Resource/usersThe collection.
Resource ID/42One item in it.
Query string?include=ordersOptions that shape the response.
04HTTP messages

The request and response lifecycle

Every API interaction is two messages: the client's request and the server's response.

Client → serverhttp
GET /api/v1/users/42?include=orders HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer <access-token>
X-Request-ID: req_f8270
Server → clienthttp
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: private, max-age=60
ETag: "user-42-v8"
X-Request-ID: req_f8270

{ "data": { "id": 42, "name": "Aman", "email": "[email protected]" } }
What happens in between
User actionTap “View profile”
ClientBuilds the HTTP request
DNS + networkFinds and reaches the server
APIAuthenticates, validates
Business logicApplies the rules
Database / cache
ResponseStatus, headers, body
05HTTP semantics

HTTP methods

Use each method for what it means. The method tells everyone (clients, caches, proxies, crawlers) what you intend.

MethodPurposeExampleSafeIdempotentTypical success
GETRead a resource or collectionGET /api/v1/users/42YesYes200 OK
POSTCreate, or run an operationPOST /api/v1/ordersNoNo*201 Created
PUTReplace the whole resourcePUT /api/v1/users/42NoYes200 / 204
PATCHChange some fieldsPATCH /api/v1/users/42NoDepends200 / 204
DELETERemove a resourceDELETE /api/v1/users/42NoYes204 No Content
HEADHeaders only, as GET would returnHEAD /api/v1/books/100YesYes200 OK
OPTIONSDiscover allowed methods (CORS preflight)OPTIONS /api/v1/usersYesYes204

* POST becomes retry-safe with an idempotency key; see section 14.

Safe

Read-only semantics. GET must never delete data, charge a card or change an account.

Idempotent

Repeating it has the same effect as sending it once, which is what lets clients retry after network failures.

Create a userhttp
POST /api/v1/users
Content-Type: application/json
Authorization: Bearer <access-token>

{ "name": "Aman", "email": "[email protected]" }
201 Createdhttp
HTTP/1.1 201 Created
Location: /api/v1/users/42
Content-Type: application/json

{ "data": { "id": 42, "name": "Aman", "email": "[email protected]", "createdAt": "2026-11-18T10:30:00Z" } }
06HTTP responses

HTTP status codes

The status code tells the client what kind of result it got, before it parses a single byte of the body.

1xx · informational

Still processing, or switching protocols (101 for WebSocket).

2xx · success

200, 201, 202, 204, 206.

3xx · redirection

301, 302, 304 Not Modified, 307, 308.

4xx · client error

400, 401, 403, 404, 409, 422, 429.

5xx · server error

500, 502, 503, 504.

CodeUse it when
200 OKSuccess, with a body.
201 CreatedA new resource was created (add a Location header).
202 AcceptedAccepted for async processing; not finished yet.
204 No ContentSuccess, nothing to return.
304 Not ModifiedThe client's cached copy is still valid.
400 Bad RequestMalformed request: invalid JSON, wrong types.
401 UnauthorizedNot authenticated: missing or invalid credentials.
403 ForbiddenAuthenticated, but not allowed.
404 Not FoundThe resource doesn't exist (or is hidden from you).
409 ConflictClashes with the current state: duplicate, stale version.
422 Unprocessable ContentWell-formed but semantically invalid.
429 Too Many RequestsOver the rate limit (send Retry-After).
500 Internal Server ErrorUnexpected failure on the server.
502 Bad GatewayA proxy got a bad response from upstream.
503 Service UnavailableTemporarily can't serve (overload, maintenance).
504 Gateway TimeoutA proxy didn't get a timely response from upstream.
07REST

What makes an API RESTful

REST (representational state transfer) is an architectural style, not a protocol or a framework.

A REST API exposes resources (users, products, orders), identifies them with URIs, and lets clients act on them through standard HTTP semantics. The response is a representation of the resource's state, usually JSON.

ConstraintWhat it means
Client–serverUI and data concerns are separated; each evolves independently behind the contract.
StatelessEach request carries everything needed; no server-side conversation state between requests.
CacheableResponses say whether and how long they can be cached.
Uniform interfaceConsistent resource identifiers and standard method semantics everywhere.
Layered systemClients can't tell whether they reach the origin, a gateway, a proxy or a CDN.
Code on demand (optional)The server may send executable code to extend the client.
08REST design

Designing resources

Start from the domain's nouns. HTTP already provides the verbs.

AvoidPreferWhy
GET /getAllUsersGET /usersThe method already says “get”.
POST /createUserPOST /usersModel the resource, not a CRUD verb.
GET /deleteUser?id=42DELETE /users/42GET must never be destructive.
/user/42/orders/users/42/ordersConsistent plural collection names.
/api/users/getById/42/api/v1/users/42Path + method is enough.

Collection

/users: all users.

Single resource

/users/42: one user.

Nested resource

/users/42/orders: orders belonging to user 42.

Sub-resource

/orders/9001/items: the items of order 9001.

09Request design

Path, query, header and body

Four places to put information in a request, each with a clear job.

WhereExampleUse it for
PathGET /users/42Identity: which resource
QueryGET /products?page=2&sort=-priceFiltering, search, sort, pagination, shape
HeaderAuthorization: Bearer <token>Metadata: auth, content type, idempotency, tracing
Body{ "name": "Aman" }The data you're creating or changing
10Contract design

Consistent responses and errors

Predictable shapes for success, and errors a program can act on.

Single resource

  • { "data": { "id": 42, "name": "Aman" } }

Collection

  • { "data": [ … ],
  • "pagination": { "nextCursor": "…", "hasNext": true } }
A structured errorjson
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "The request contains invalid fields.",
    "requestId": "req_f8270",
    "details": [ { "field": "email", "message": "A valid email address is required." } ]
  }
}

Unhelpful

  • { "error": "Something went wrong" }
  • HTTP 200 for every failure
  • Stack traces in the response

Useful

  • Correct status code
  • Stable machine-readable code
  • Readable message + field details
  • A request ID for support

Keep field names and types stable: changing a string to an object, or renaming a field, breaks clients silently. Many teams adopt RFC 9457 problem details (application/problem+json) as a standard error shape.

11Scalability

Pagination

Never return an unbounded collection that can grow.

Offset / page paginationhttp
GET /api/v1/products?page=3&limit=20

{ "data": [ … ],
  "pagination": { "page": 3, "limit": 20, "totalItems": 242, "totalPages": 13, "hasNext": true } }
Cursor paginationhttp
GET /api/v1/feed?limit=20&after=eyJpZCI6OTg3fQ

{ "data": [ … ],
  "pageInfo": { "nextCursor": "eyJpZCI6MTAwN30", "hasNextPage": true } }
OffsetCursor
Jump to page NEasyNot directly
Deep pages, big dataGets slowStays fast
Data changing underneathMay skip or duplicateStable with a proper sort key
ImplementationSimpleMore design work
12Collections

Filtering, sorting, search and field selection

Let clients ask for exactly the slice they need, through documented query parameters.

One possible designhttp
GET /api/v1/products
    ?category=books
    &minPrice=100&maxPrice=1000
    &sort=-createdAt,price
    &fields=id,title,price
    &search=system+design

Filtering

?status=PAID&currency=INR

Sorting

?sort=-createdAt,price (minus = descending, if documented)

Search

?search=system+design

Sparse fields

?fields=id,title,price to shrink responses

13Compatibility

API versioning

Versions give breaking changes a controlled path. Most changes shouldn't need one.

URI versioning

/api/v1/users: visible and simple; the most common.

Header versioning

API-Version: 2026-09-01: clean URLs, less visible.

Media-type versioning

Accept: application/vnd.app.v2+json: via content negotiation.

Usually backward-compatible

  • Adding an optional response field
  • Adding a new endpoint
  • Adding an optional request parameter

Breaking

  • Removing or renaming a field
  • Changing a field's type or meaning
  • Making an optional request field required
  • Changing an error code clients rely on
14Distributed systems

Idempotency and safe retries

Networks fail at the worst moment: the server did the work, but the response never arrived.

How a duplicate payment happens
Client sends the payment
Server charges the card
Response is lost
Client retriesWithout protection: a second charge
POST with an idempotency keyhttp
POST /api/v1/payments
Idempotency-Key: pay_01928475
Content-Type: application/json

{ "orderId": "ORD-8429", "amount": 19900, "currency": "INR" }
  1. Receive the key

    Scope it to the caller (merchant + key).

  2. Look it up atomically

    Insert-if-absent so two concurrent retries can't both proceed.

  3. Already done?

    Return the stored status and body, unchanged.

  4. Otherwise, do the work once

    Process the payment.

  5. Store the result

    Keep it for a defined window (e.g. 24 hours).

15Security

Authentication and authorization

Authentication answers “who are you?”. Authorization answers “what may you do?”.

  1. API key

    Identifies an application
    How
    X-API-Key: sk_live_…
    Use for
    Server-to-server and developer APIs. Never ship it in frontend code.
  2. Bearer token / JWT

    Signed access token
    How
    Authorization: Bearer eyJhbGciOi…
    Use for
    Stateless APIs; short expiry plus refresh tokens.
  3. Session cookie

    Server-side session
    How
    A Secure, HttpOnly, SameSite cookie holding a session ID.
    Use for
    Browser apps; easy revocation.
  4. OAuth 2.0 / OpenID Connect

    Delegated access + login
    How
    An authorization server issues access (and ID) tokens.
    Use for
    “Sign in with Google”; third-party access to your API.
A bearer-token request
User signs in
Identity providerIssues an access token
ClientSends Authorization: Bearer …
APIVerifies signature, expiry, audience, scopes
Protected resource

Authorization models

RBAC

Role-based: permissions attach to roles such as ADMIN, EDITOR, USER.

ABAC

Attribute-based: decisions use attributes like department, owner, region, time.

Resource ownership

May user 42 read /users/42/orders? Only if they are user 42, or have a permitted relationship.

16Security

API security and CORS

A checklist for every API, then the browser rule that confuses everyone.

HTTPS everywhere

TLS protects credentials and data in transit.

Validate all input

Type, size, range and format; treat every client as untrusted.

Authorize every resource

IDs are not permissions.

Rate-limit sensitive routes

Login, OTP, password reset, expensive endpoints.

Protect secrets

Never in frontend bundles or Git; rotate them.

Short-lived credentials

Limit the blast radius of a leak.

Audit important actions

Who did what to which resource, and when.

Return only needed fields

Don't serialise whole database entities.

Bound payloads

Body size, JSON depth, GraphQL query cost.

Patch dependencies

Frameworks, gateways and libraries.

CORS: cross-origin resource sharing

Browserapp.targettrek.in
OPTIONS preflightMay I PUT with these headers?
APIAccess-Control-Allow-* headers
Actual request
A CORS responsehttp
Access-Control-Allow-Origin: https://www.targettrek.in
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
17Performance

Caching and ETags

Don't redo work when a previous answer is still good.

Client
CDN / cacheCache hit?
APIOnly on a miss
Database
Conditional request with an ETaghttp
GET /api/v1/books/42
If-None-Match: "book-42-v12"

# unchanged →
HTTP/1.1 304 Not Modified
ETag: "book-42-v12"

# changed →
HTTP/1.1 200 OK
ETag: "book-42-v13"
Content-Type: application/json

{ "id": 42, "title": "System Design" }

Cache-Control

public / private, max-age, no-store, stale-while-revalidate.

ETag + If-None-Match

Validate a cached copy; 304 saves the whole body.

304 Not Modified

“Your copy is fine”, with no body.

CDN / shared cache

Public responses served near users; private ones never.

18Reliability

Rate limiting

Control how often each caller may hit the API, to protect capacity, fairness and cost.

Fixed window

100 per minute; simple, but bursty at the boundaries.

Sliding window

Counts over a rolling period for smoother limits.

Token bucket

Refill at a rate, allow bursts up to capacity.

Leaky bucket

Process at a steady output rate.

429 with guidancehttp
HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0

{ "error": { "code": "RATE_LIMIT_EXCEEDED", "message": "Too many requests. Retry in 30 seconds." } }
19GraphQL

GraphQL, and when to choose it over REST

A typed schema, one endpoint, and clients that ask for exactly the fields they need.

Query

Read data.

Mutation

Change data or trigger side effects.

Subscription

Receive updates as events happen.

Schemagraphql
type User {
  id: ID!
  name: String!
  email: String!
  orders(first: Int, after: String): OrderConnection!
}

type Query    { user(id: ID!): User }
type Mutation { createUser(input: CreateUserInput!): User! }
Query: exactly these fields, one round tripgraphql
query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    orders(first: 3) { nodes { id total status } }
  }
}

Why teams like it

  • Clients pick the fields they need
  • Related data in one request
  • A typed, introspectable schema
  • Many UIs without new endpoints

What you must handle

  • N+1 resolver queries (use DataLoader)
  • Expensive nested queries (depth/cost limits)
  • Per-field authorization
  • Harder HTTP-level caching
RESTGraphQL
ModelResources at URLsA typed graph behind one endpoint
Data selectionThe server decides per endpointThe client selects fields
CachingNatural with GET + URLsNeeds client/app-level design
Related dataSeveral calls or custom endpointsOne nested query
Cost controlPer-endpoint, easy to reason aboutNeeds depth and complexity limits
Best forPublic, resource-oriented, cacheable APIsRich clients with changing data needs
20Event integrations

Webhooks

Instead of polling “anything new?”, the provider calls you when something happens.

Payment providerpayment.success
POST /webhooks/paymentYour public endpoint
Verify signatureHMAC over the raw body
Queue + return 2xxProcess asynchronously
A webhook deliveryhttp
POST /webhooks/payment
X-Webhook-Id: evt_18273
X-Webhook-Timestamp: 1790767200
X-Webhook-Signature: sha256=5f2b…

{ "id": "evt_18273", "type": "payment.success", "data": { "orderId": "ORD-8429", "paymentId": "PAY-2901" } }
Verifying the signature (Node.js)js
import crypto from "node:crypto";

export function verifyWebhook(rawBody, headers, secret) {
  const ts = Number(headers["x-webhook-timestamp"]);
  if (Math.abs(Date.now() / 1000 - ts) > 300) return false;          // reject replays > 5 min old

  const expected = crypto.createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
  const given = String(headers["x-webhook-signature"]).replace(/^sha256=/, "");
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(given));   // constant-time compare
}

Verify authenticity

Signature over the raw body, plus a timestamp check.

Expect retries

Deduplicate by event ID; handle events idempotently.

Acknowledge fast

Return 2xx quickly; queue the heavy work.

Observe failures

Track deliveries, signature failures and dead-lettered events.

PollingWebhook
DirectionConsumer asks repeatedlyProvider pushes
LatencyUp to the polling intervalNear real time
WasteMany empty responsesTraffic only on events
ComplexitySimple consumerPublic endpoint, security, retries
21Beyond REST

RPC, gRPC, SOAP and WebSockets

Other shapes of API, and where each one fits.

RPC: operations, not resourceshttp
POST /calculateShipping
POST /generateInvoice
POST /approveLoan
gRPC: a typed service contracttext
service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse);
}

gRPC

Protocol Buffers over HTTP/2: compact, fast, strongly typed, with streaming. Great between services; needs a proxy for browsers.

SOAP

XML envelopes, WSDL contracts, WS-Security. Mostly legacy enterprise and banking.

WebSocket

One long-lived, two-way connection: chat, live prices, collaboration.

22Documentation

OpenAPI and Swagger

A machine-readable contract that drives docs, validation, SDKs, mocks and tests.

openapi.yamlyaml
openapi: 3.1.0
info:
  title: Target Trek Learning API
  version: 1.0.0
servers:
  - url: https://api.example.com
paths:
  /api/v1/users/{userId}:
    get:
      summary: Get a user
      operationId: getUser
      parameters:
        - name: userId
          in: path
          required: true
          schema: { type: integer }
      responses:
        "200":
          description: User found
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404":
          description: User not found
components:
  schemas:
    User:
      type: object
      required: [id, name]
      properties:
        id:    { type: integer }
        name:  { type: string }
        email: { type: string, format: email }

OpenAPI

  • The specification itself
  • YAML or JSON
  • Vendor-neutral standard

Swagger

  • The original name, and a family of tools
  • Swagger UI, Editor, Codegen
  • Used to view and generate from OpenAPI
API-first workflow
Define the contract
Review
Docs + mocks
Implement
Contract tests + SDKs
23System design

API gateway and observability

The front door to your services, and the telemetry that tells you what happened when things go wrong.

Client
DNS / CDN
Load balancer
API gatewayAuth · rate limit · route
Service
Cache / database

Observability: logs, metrics, traces

Logs

Structured events with request ID, route, status, latency, caller: never secrets.

Metrics

Rate, errors and latency percentiles, aggregated over time.

Traces

Follow one request across gateway, services, queues and databases.

  • Request rate
  • p50 / p95 / p99 latency
  • 4xx rate
  • 5xx rate
  • Timeout rate
  • Upstream latency
  • Cache hit rate
  • 429 rejections
  • Database latency
  • Queue depth
24Quality

Testing an API

Layered tests, and far more than the happy path.

Unit

Business rules and validation, fast and isolated.

Integration

With a real database, cache and queue.

Contract

Provider and consumers agree on requests and responses.

End-to-end

Critical user flows across services.

Load

Behaviour at expected and peak traffic.

Security

Auth, access control, input handling.

Test the unhappy paths

  • Missing token
  • Expired or invalid token
  • Another user's resource
  • Invalid JSON
  • Missing required field
  • Wrong field type
  • Unknown resource
  • Duplicate request
  • Concurrent update
  • Rate limit exceeded
  • Database down
  • Upstream timeout
  • Malformed cursor
  • Page size over the max
  • Duplicate webhook
  • Bad webhook signature
cURLbash
curl --request POST \
  --url https://api.example.com/api/v1/users \
  --header "Authorization: Bearer <token>" \
  --header "Content-Type: application/json" \
  --data '{ "name": "Aman", "email": "[email protected]" }'
Calling an API from the frontendjs
const res = await fetch("https://api.example.com/api/v1/users/42", {
  headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
});
if (!res.ok) {
  const { error } = await res.json().catch(() => ({}));
  throw new Error(`${res.status}: ${error?.code ?? "REQUEST_FAILED"}`);
}
const { data } = await res.json();
25Backend

Putting it all together

A production API is more than a controller wired straight to a database. Each layer has one job.

Inside the service
ControllerHTTP in/out
Validation
Authorization
Service layerBusiness rules
Repository

Controller

Translates HTTP into input and output. Keep business logic out.

Service layer

Business workflows and domain rules.

Repository / DAO

All persistence access in one place.

DTOs

Public request/response models, separate from database entities.

UserController.java (Spring Boot)java
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
  private final UserService userService;
  public UserController(UserService userService) { this.userService = userService; }

  @GetMapping("/{id}")
  public ResponseEntity<UserResponse> getUser(@PathVariable Long id) {
    return ResponseEntity.ok(userService.getById(id));
  }

  @PostMapping
  public ResponseEntity<UserResponse> createUser(@Valid @RequestBody CreateUserRequest request) {
    UserResponse created = userService.create(request);
    return ResponseEntity.created(URI.create("/api/v1/users/" + created.id())).body(created);
  }
}

Concurrent updates

Optimistic concurrencysql
-- A and B both read version 8. A saves first → version 9.
UPDATE users SET name = 'New Name', version = 9
WHERE  id = 42 AND version = 8;
-- B's update matches 0 rows → return 409 Conflict (or 412 with If-Match / ETag)

Timeouts, retries and circuit breakers

Timeout

Never wait forever on a dependency; bound every call.

Retry

Only when safe; bounded, with exponential backoff and jitter.

Circuit breaker

Stop calling a dependency that keeps failing; fail fast while it recovers.

26Revision

Production API checklist

Run through this before you ship an endpoint.

  1. Naming

    Consistent resource names; methods used for their meaning.

  2. Status codes

    Correct codes, including 201, 204, 401 vs 403, 409, 422, 429.

  3. Validation

    Every input checked for type, size and range.

  4. Auth

    Authenticated where required; authorization checked per resource.

  5. Transport

    HTTPS only; no sensitive fields leaked in responses.

  6. Errors

    One predictable error shape with codes and request IDs.

  7. Collections

    Bounded pagination; documented filters and sort.

  8. Compatibility

    Additive changes; a versioning and deprecation plan.

  9. Retries

    Idempotency keys on retry-sensitive writes.

  10. Protection

    Rate limits on capacity and sensitive routes.

  11. Caching

    Explicit Cache-Control; private data never public.

  12. Resilience

    Timeouts on every dependency; bounded, safe retries.

  13. Concurrency

    Conflicting updates detected (versions / ETags).

  14. Webhooks

    Signatures verified; duplicates handled.

  15. Observability

    Request IDs in logs; latency, errors and traffic monitored.

  16. Docs and tests

    OpenAPI matches reality; contract and integration tests guard it.

Interview prep

API design interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

What is an API, and why does the contract matter?

An API is the agreed interface between two pieces of software: operations, inputs, outputs, errors and behaviour. Clients depend on that contract, not on your code, so changing it carelessly breaks everyone who integrated. Treat it like a public promise.

2

What makes an API RESTful?

It models things as resources with stable URIs, uses HTTP methods for their defined meaning, is stateless (each request carries what it needs), makes responses cacheable where appropriate, and follows a uniform interface. Using HTTP and JSON alone doesn't make an API RESTful.

3

URI vs URL?

A URI identifies a resource; a URL is a URI that also tells you how to locate it (scheme and host). In everyday API work the terms are used almost interchangeably.

4

GET vs POST vs PUT vs PATCH vs DELETE?

GET reads. POST creates or triggers an action. PUT replaces a resource with the full representation sent. PATCH changes only the fields sent. DELETE removes. GET, PUT and DELETE are idempotent; POST isn't (unless you add an idempotency key); PATCH depends on how it's written.

5

What does “safe” mean, and why is GET safe?

A safe method has read-only semantics: calling it shouldn't change server state. Browsers, crawlers and caches may fetch GET URLs freely, so a GET that deletes or charges something is a serious bug.

6

What does idempotent mean? Is POST idempotent? Why is DELETE?

Idempotent means repeating the request has the same effect as sending it once. POST isn't: two POST /orders can create two orders. DELETE is: after the first delete, the resource is gone, and repeating it changes nothing more, even if the second call returns 404.

7

401 vs 403?

401 Unauthorized means you're not authenticated: the credentials are missing, invalid or expired, so log in again. 403 Forbidden means you're authenticated but not allowed to do this, and re-authenticating won't help.

8

When do you return 400, 409 or 422?

400 when the request is malformed (invalid JSON, wrong types). 422 when it's well-formed but semantically invalid (an end date before the start date). 409 when it conflicts with the resource's current state (a duplicate email, a stale version, booking an already-booked seat).

9

200 vs 201 vs 202 vs 204?

200: success with a body. 201: a resource was created; include a Location header and usually the resource. 202: accepted for async processing and not done yet; return a status URL. 204: success with no body, common for DELETE and some PUT/PATCH.

10

Path parameters vs query parameters?

Use a path parameter when the value identifies which resource you mean (/users/42). Use query parameters to filter, search, sort, paginate or shape the representation (/products?category=books&sort=-price).

11

Offset vs cursor pagination?

Offset (?page=3&limit=20) is simple and supports jumping to a page, but large offsets are slow and changing data causes skipped or duplicated items. Cursor pagination (?after=<opaque cursor>) is fast at any depth and stable while data changes, but can't jump to page 50.

12

How would you version an API?

Most commonly with a URI prefix (/api/v1), sometimes a header (API-Version: 2026-09-01) or a media type. More importantly, avoid needing versions: make additive, backward-compatible changes, and reserve a new version for genuinely breaking changes, with a deprecation timeline.

13

What is an idempotency key, and why do payment APIs use one?

A unique key the client sends with a non-idempotent request. The server stores the result under that key; a retry with the same key returns the stored result instead of charging again. It makes POST /payments safe to retry after a timeout.

14

JWT vs session authentication?

Sessions keep state on the server and send the browser an opaque cookie: easy to revoke, but they need a shared session store. JWTs are signed, self-contained tokens the API can verify without a lookup: they scale easily but are hard to revoke before expiry, so keep them short-lived and pair them with refresh tokens.

15

Authentication vs authorization?

Authentication verifies who the caller is (login, API key, token). Authorization decides what they may do (may user 42 read order 9001?). Check authorization on every protected resource, not just at login.

16

OAuth 2.0 vs OpenID Connect?

OAuth 2.0 is an authorization framework for delegated access: an app gets an access token to call an API on a user's behalf. OpenID Connect adds an identity layer on top (an ID token and user info) so it can also be used for login.

17

What is CORS, and what is a preflight request?

CORS is how a browser decides whether JavaScript from one origin may read responses from another. For non-simple requests (custom headers, PUT or DELETE, JSON content type) the browser first sends an OPTIONS preflight, and the server answers with Access-Control-Allow-* headers. CORS doesn't protect your API from non-browser clients; that's what auth is for.

18

What do Cache-Control and ETag do?

Cache-Control tells clients and CDNs whether and how long they may cache (public, private, max-age, no-store). An ETag is a version identifier: the client sends If-None-Match, and if nothing changed the server replies 304 Not Modified with no body.

19

REST vs GraphQL: when would you use each?

REST suits resource-oriented, cache-friendly, public APIs whose costs are easy to reason about. GraphQL suits rich clients that need many related fields in one round trip and evolve quickly. GraphQL adds query-cost limits, resolver authorization and harder HTTP caching.

20

What is the N+1 problem in GraphQL?

A resolver fetches a list (one query) and then each item's related data separately (N queries). DataLoader-style batching collects those N lookups into one batched query per request.

21

What are webhooks, and webhook vs polling?

A webhook is the provider calling your HTTP endpoint when an event happens, such as payment.success. Polling asks repeatedly whether anything has changed. Webhooks are near-real-time and waste less traffic, but you need a public endpoint, signature verification and idempotent handling of retries.

22

How do you secure and process a webhook safely?

Verify the HMAC signature over the raw body with the shared secret, reject old timestamps to stop replays, deduplicate by event ID, return 2xx quickly and queue the heavy work, and monitor failures and retries.

23

API gateway vs load balancer?

A load balancer spreads traffic across instances of a service. An API gateway is an API-aware front door: routing by path, authentication, quotas, transformation and aggregation. Real systems usually have both.

24

What is OpenAPI, and OpenAPI vs Swagger?

OpenAPI is a machine-readable specification for describing HTTP APIs in YAML or JSON. Swagger is the original name and a family of tools (Swagger UI, Editor, Codegen) for working with OpenAPI documents. The spec drives docs, validation, SDKs and contract tests.

25

How do you safely retry failed API calls?

Retry only transient failures (timeouts, 502, 503, 504, 429 with Retry-After), and only idempotent requests or those with an idempotency key. Use bounded attempts with exponential backoff and jitter, respect Retry-After, and set an overall deadline.

26

How do you handle concurrent updates to the same resource?

Use optimistic concurrency: the client sends the version it read (If-Match with an ETag, or a version field) and the server updates only if it still matches, otherwise it returns 409 or 412. Use transactions or locks where conflicts are frequent.

27

How would you design a production-ready payment API?

POST /payments with an Idempotency-Key; validate the amount and currency; authenticate and authorize the merchant; create a PENDING payment, call the provider with its own idempotency key, and confirm via a signed webhook; return 201 or 202 with a status URL; consistent errors; rate limits; audit logs; and no card data in logs.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

A logged-in user requests another user's private order. What status fits best?

Reference

API design glossary

The terms from this guide, in one line each.

Endpoint
A URL + method combination clients call, e.g. GET /users/42.
Resource
A thing the API exposes (user, order) identified by a URI.
Safe method
Read-only semantics: GET, HEAD, OPTIONS.
Idempotent
Repeating the request has the same effect as once: GET, PUT, DELETE.
Status code
A three-digit result class: 2xx success, 4xx client error, 5xx server error.
Idempotency key
A client-supplied ID that makes retried writes safe.
Bearer token
An access token sent as Authorization: Bearer <token>; JWT is one format.
CORS
The browser rules for cross-origin requests, negotiated with Access-Control-* headers.
ETag
A version tag enabling conditional requests and 304 Not Modified.
Webhook
A provider pushing an event to your HTTP endpoint.
OpenAPI
A machine-readable specification of an HTTP API.
N+1 problem
One query for a list, then one more per item: fix with batching.
Summary

Key takeaways

  1. An API is a contract. Design it for the people who depend on it, and change it carefully.
  2. Use HTTP methods and status codes for what they mean: GET is safe, PUT and DELETE are idempotent, 401 ≠ 403.
  3. Model resources (nouns), not actions in URLs; use path parameters for identity and query parameters for selection.
  4. Return one consistent error shape with stable codes and a request ID; never leak internals.
  5. Bound every collection with pagination, preferably cursor-based at scale.
  6. Make retries safe: idempotency keys on writes, backoff with jitter, and timeouts everywhere.
  7. Authenticate every request, authorize every resource, rate-limit sensitive routes, and verify every webhook.
Questions

API design: frequently asked questions

What is an API?

An API (application programming interface) is a defined contract that lets software systems communicate: the operations available, the inputs they accept, the outputs they return and how errors are reported.

What is the difference between a REST API and a RESTful API?

They're used interchangeably. “RESTful” emphasises that the API consistently follows REST principles (resources, standard HTTP semantics, statelessness, cacheability) rather than merely using HTTP and JSON.

What is the difference between PUT and PATCH?

PUT replaces the entire resource with the representation you send; PATCH applies a partial change to only the fields you send.

What is the difference between 401 and 403?

401 means the request isn't authenticated (missing or invalid credentials). 403 means the caller is authenticated but doesn't have permission for that action.

Is GraphQL better than REST?

Neither is better in general. GraphQL helps clients fetch exactly the related data they need in one request; REST is simpler to cache, secure and reason about for resource-oriented APIs. Many companies use both.

What is API idempotency?

An operation is idempotent when making the same request repeatedly has the same effect as making it once. GET, PUT and DELETE are idempotent by definition; POST can be made retry-safe with an idempotency key.

Next topicAPI Gateway

Put your APIs behind one controlled front door: routing, auth, quotas, aggregation and circuit breakers.

Go deeperBuild these APIs in Spring Boot

REST controllers, validation, security, persistence, error handling and production practices, with the interview questions that go with them.

  • REST
  • Validation
  • Security
  • JPA
  • Error handling
  • Interview Q&A
Explore the Spring Boot handbook

Last reviewed 18 November 2026