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.
API styles and audiences
REST and GraphQL are the best known, but production systems also use RPC, gRPC, WebSockets, webhooks and, occasionally, SOAP.
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.
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.
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.
WebSocket
Persistent, two-way- Model
- A long-lived connection where both sides send messages any time.
- Good fit
- Chat, live dashboards, collaboration, games.
Webhook
Server push- Model
- The provider calls your endpoint when an event happens.
- Good fit
- Payment updates, Git events, delivery notifications.
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.
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.
| Part | Example | Meaning |
|---|---|---|
| Scheme | https | The protocol. |
| Host | api.example.com | The server's domain. |
| Base path | /api/v1 | Common prefix, often with the version. |
| Resource | /users | The collection. |
| Resource ID | /42 | One item in it. |
| Query string | ?include=orders | Options that shape the response. |
The request and response lifecycle
Every API interaction is two messages: the client's request and the server's response.
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_f8270HTTP/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]" } }HTTP methods
Use each method for what it means. The method tells everyone (clients, caches, proxies, crawlers) what you intend.
| Method | Purpose | Example | Safe | Idempotent | Typical success |
|---|---|---|---|---|---|
| GET | Read a resource or collection | GET /api/v1/users/42 | Yes | Yes | 200 OK |
| POST | Create, or run an operation | POST /api/v1/orders | No | No* | 201 Created |
| PUT | Replace the whole resource | PUT /api/v1/users/42 | No | Yes | 200 / 204 |
| PATCH | Change some fields | PATCH /api/v1/users/42 | No | Depends | 200 / 204 |
| DELETE | Remove a resource | DELETE /api/v1/users/42 | No | Yes | 204 No Content |
| HEAD | Headers only, as GET would return | HEAD /api/v1/books/100 | Yes | Yes | 200 OK |
| OPTIONS | Discover allowed methods (CORS preflight) | OPTIONS /api/v1/users | Yes | Yes | 204 |
* 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.
POST /api/v1/users
Content-Type: application/json
Authorization: Bearer <access-token>
{ "name": "Aman", "email": "[email protected]" }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" } }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.
| Code | Use it when |
|---|---|
| 200 OK | Success, with a body. |
| 201 Created | A new resource was created (add a Location header). |
| 202 Accepted | Accepted for async processing; not finished yet. |
| 204 No Content | Success, nothing to return. |
| 304 Not Modified | The client's cached copy is still valid. |
| 400 Bad Request | Malformed request: invalid JSON, wrong types. |
| 401 Unauthorized | Not authenticated: missing or invalid credentials. |
| 403 Forbidden | Authenticated, but not allowed. |
| 404 Not Found | The resource doesn't exist (or is hidden from you). |
| 409 Conflict | Clashes with the current state: duplicate, stale version. |
| 422 Unprocessable Content | Well-formed but semantically invalid. |
| 429 Too Many Requests | Over the rate limit (send Retry-After). |
| 500 Internal Server Error | Unexpected failure on the server. |
| 502 Bad Gateway | A proxy got a bad response from upstream. |
| 503 Service Unavailable | Temporarily can't serve (overload, maintenance). |
| 504 Gateway Timeout | A proxy didn't get a timely response from upstream. |
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.
| Constraint | What it means |
|---|---|
| Client–server | UI and data concerns are separated; each evolves independently behind the contract. |
| Stateless | Each request carries everything needed; no server-side conversation state between requests. |
| Cacheable | Responses say whether and how long they can be cached. |
| Uniform interface | Consistent resource identifiers and standard method semantics everywhere. |
| Layered system | Clients 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. |
Designing resources
Start from the domain's nouns. HTTP already provides the verbs.
| Avoid | Prefer | Why |
|---|---|---|
| GET /getAllUsers | GET /users | The method already says “get”. |
| POST /createUser | POST /users | Model the resource, not a CRUD verb. |
| GET /deleteUser?id=42 | DELETE /users/42 | GET must never be destructive. |
| /user/42/orders | /users/42/orders | Consistent plural collection names. |
| /api/users/getById/42 | /api/v1/users/42 | Path + 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.
Path, query, header and body
Four places to put information in a request, each with a clear job.
| Where | Example | Use it for |
|---|---|---|
| Path | GET /users/42 | Identity: which resource |
| Query | GET /products?page=2&sort=-price | Filtering, search, sort, pagination, shape |
| Header | Authorization: Bearer <token> | Metadata: auth, content type, idempotency, tracing |
| Body | { "name": "Aman" } | The data you're creating or changing |
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 } }
{
"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.
Pagination
Never return an unbounded collection that can grow.
GET /api/v1/products?page=3&limit=20
{ "data": [ … ],
"pagination": { "page": 3, "limit": 20, "totalItems": 242, "totalPages": 13, "hasNext": true } }GET /api/v1/feed?limit=20&after=eyJpZCI6OTg3fQ
{ "data": [ … ],
"pageInfo": { "nextCursor": "eyJpZCI6MTAwN30", "hasNextPage": true } }| Offset | Cursor | |
|---|---|---|
| Jump to page N | Easy | Not directly |
| Deep pages, big data | Gets slow | Stays fast |
| Data changing underneath | May skip or duplicate | Stable with a proper sort key |
| Implementation | Simple | More design work |
Filtering, sorting, search and field selection
Let clients ask for exactly the slice they need, through documented query parameters.
GET /api/v1/products
?category=books
&minPrice=100&maxPrice=1000
&sort=-createdAt,price
&fields=id,title,price
&search=system+designFiltering
?status=PAID¤cy=INR
Sorting
?sort=-createdAt,price (minus = descending, if documented)
Search
?search=system+design
Sparse fields
?fields=id,title,price to shrink responses
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
Idempotency and safe retries
Networks fail at the worst moment: the server did the work, but the response never arrived.
POST /api/v1/payments
Idempotency-Key: pay_01928475
Content-Type: application/json
{ "orderId": "ORD-8429", "amount": 19900, "currency": "INR" }Receive the key
Scope it to the caller (merchant + key).
Look it up atomically
Insert-if-absent so two concurrent retries can't both proceed.
Already done?
Return the stored status and body, unchanged.
Otherwise, do the work once
Process the payment.
Store the result
Keep it for a defined window (e.g. 24 hours).
Authentication and authorization
Authentication answers “who are you?”. Authorization answers “what may you do?”.
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.
Bearer token / JWT
Signed access token- How
- Authorization: Bearer eyJhbGciOi…
- Use for
- Stateless APIs; short expiry plus refresh tokens.
Session cookie
Server-side session- How
- A Secure, HttpOnly, SameSite cookie holding a session ID.
- Use for
- Browser apps; easy revocation.
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.
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.
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
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: 600Caching and ETags
Don't redo work when a previous answer is still good.
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.
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.
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." } }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.
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 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
| REST | GraphQL | |
|---|---|---|
| Model | Resources at URLs | A typed graph behind one endpoint |
| Data selection | The server decides per endpoint | The client selects fields |
| Caching | Natural with GET + URLs | Needs client/app-level design |
| Related data | Several calls or custom endpoints | One nested query |
| Cost control | Per-endpoint, easy to reason about | Needs depth and complexity limits |
| Best for | Public, resource-oriented, cacheable APIs | Rich clients with changing data needs |
Webhooks
Instead of polling “anything new?”, the provider calls you when something happens.
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" } }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.
| Polling | Webhook | |
|---|---|---|
| Direction | Consumer asks repeatedly | Provider pushes |
| Latency | Up to the polling interval | Near real time |
| Waste | Many empty responses | Traffic only on events |
| Complexity | Simple consumer | Public endpoint, security, retries |
RPC, gRPC, SOAP and WebSockets
Other shapes of API, and where each one fits.
POST /calculateShipping
POST /generateInvoice
POST /approveLoanservice 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.
OpenAPI and Swagger
A machine-readable contract that drives docs, validation, SDKs, mocks and tests.
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 gateway and observability
The front door to your services, and the telemetry that tells you what happened when things go wrong.
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
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
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]" }'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();Putting it all together
A production API is more than a controller wired straight to a database. Each layer has one job.
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.
@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
-- 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.
Production API checklist
Run through this before you ship an endpoint.
Naming
Consistent resource names; methods used for their meaning.
Status codes
Correct codes, including 201, 204, 401 vs 403, 409, 422, 429.
Validation
Every input checked for type, size and range.
Auth
Authenticated where required; authorization checked per resource.
Transport
HTTPS only; no sensitive fields leaked in responses.
Errors
One predictable error shape with codes and request IDs.
Collections
Bounded pagination; documented filters and sort.
Compatibility
Additive changes; a versioning and deprecation plan.
Retries
Idempotency keys on retry-sensitive writes.
Protection
Rate limits on capacity and sensitive routes.
Caching
Explicit Cache-Control; private data never public.
Resilience
Timeouts on every dependency; bounded, safe retries.
Concurrency
Conflicting updates detected (versions / ETags).
Webhooks
Signatures verified; duplicates handled.
Observability
Request IDs in logs; latency, errors and traffic monitored.
Docs and tests
OpenAPI matches reality; contract and integration tests guard it.
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.
1What 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.
2What 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.
3URI 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.
4GET 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.
5What 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.
6What 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.
7401 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.
8When 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).
9200 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.
10Path 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).
11Offset 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.
12How 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.
13What 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.
14JWT 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.
15Authentication 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.
16OAuth 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.
17What 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.
18What 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.
19REST 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.
20What 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.
21What 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.
22How 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.
23API 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.
24What 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.
25How 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.
26How 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.
27How 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
A logged-in user requests another user's private order. What status fits best?
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.
Key takeaways
- An API is a contract. Design it for the people who depend on it, and change it carefully.
- Use HTTP methods and status codes for what they mean: GET is safe, PUT and DELETE are idempotent, 401 ≠ 403.
- Model resources (nouns), not actions in URLs; use path parameters for identity and query parameters for selection.
- Return one consistent error shape with stable codes and a request ID; never leak internals.
- Bound every collection with pagination, preferably cursor-based at scale.
- Make retries safe: idempotency keys on writes, backoff with jitter, and timeouts everywhere.
- Authenticate every request, authorize every resource, rate-limit sensitive routes, and verify every webhook.
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.
Put your APIs behind one controlled front door: routing, auth, quotas, aggregation and circuit breakers.
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
Last reviewed 18 November 2026