Definition
- REST (Representational State Transfer) is an architectural style defined by Roy Fielding in his 2000 doctoral dissertation, describing six constraints for building scalable, loosely coupled web services.
- Resource is any entity exposed by the API (account, transaction, customer), identified by a unique URI like
/api/accounts/SAV2001. - HTTP methods (GET, POST, PUT, PATCH, DELETE) define the operation performed on a resource, replacing the need for custom verbs in URIs.
- Status codes are three-digit numbers in the HTTP response that tell the client exactly what happened: success, client error, or server error.
- Statelessness means every request contains all the information the server needs. The server does not store session state between requests.
Think of a bank counter at National Bank of India. Each counter slip (HTTP request) contains the customer name, account number, and the action requested (deposit, withdrawal, balance check). The teller (server) reads the slip, performs the action, and hands back a receipt (HTTP response) with the result and a status stamp (status code). The teller does not remember previous visits. Every slip is self-contained.
Understanding the Concepts
What is REST?
REST stands for Representational State Transfer. It is an architectural style for building web services, not a protocol or a standard. Roy Fielding defined it in his 2000 doctoral dissertation as a set of constraints that, when followed, make web services scalable, simple, and loosely coupled.
A RESTful API exposes resources (accounts, transactions, customers) as URIs. Clients interact with these resources using standard HTTP methods. The server returns representations of the resource state, typically as JSON.
package com.bank.controller;
import com.bank.dto.AccountResponse;
import com.bank.service.AccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
// Resource: Account
// URI: /api/accounts
// Method: GET = list all accounts
@GetMapping
public List<AccountResponse> listAccounts() {
return accountService.findAll();
}
// URI: /api/accounts/SAV2001
// Method: GET = get one account
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
return ResponseEntity.ok(accountService.findById(accountId));
}
}
GET /api/accounts
HTTP 200 OK
[
{"accountId":"SAV2001","holderName":"Rajesh Kumar","balance":75000.00,"type":"SAVINGS"},
{"accountId":"SAV2002","holderName":"Priya Sharma","balance":120000.00,"type":"SAVINGS"}
]
What are the six REST constraints?
Fielding defined six constraints. An API is RESTful only if it follows all six.
| Constraint | Meaning | Banking Example |
|---|---|---|
| Client-Server | Client and server are independent. The client does not know how data is stored. | The mobile app does not know if accounts are in PostgreSQL or Oracle. |
| Stateless | Every request carries all information needed. No server-side session. | Each API call includes the JWT token. The server does not remember previous calls. |
| Cacheable | Responses must declare whether they can be cached. | Account balance may have Cache-Control: no-store. Branch list may have Cache-Control: max-age=3600. |
| Uniform Interface | Standard methods (GET, POST, PUT, DELETE) and standard media types. | All endpoints use JSON, standard status codes, and consistent URI patterns. |
| Layered System | The client does not know if it talks to the actual server or a proxy/load balancer. | Requests pass through an API gateway before reaching the account service. |
| Code on Demand (optional) | The server can send executable code to the client. | Rarely used in banking APIs. |
package com.bank.controller;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/api/branches")
public class BranchController {
@GetMapping
public ResponseEntity<List<String>> listBranches() {
List<String> branches = List.of(
"Mumbai Main Branch",
"Delhi Connaught Place",
"Bangalore Koramangala");
// Cacheable: branch list rarely changes
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS))
.body(branches);
}
}
GET /api/branches
HTTP 200 OK
Cache-Control: max-age=3600
["Mumbai Main Branch","Delhi Connaught Place","Bangalore Koramangala"]
How do you design resource URIs?
URIs identify resources. Use nouns for resources, not verbs. Use plural nouns. Use path hierarchy for relationships.
| Good URI | Bad URI | Why |
|---|---|---|
GET /api/accounts | GET /api/getAccounts | Use HTTP method, not verb in URI. |
GET /api/accounts/SAV2001 | GET /api/account?id=SAV2001 | Path variable is more RESTful for identifiers. |
GET /api/accounts/SAV2001/transactions | GET /api/getTransactionsForAccount?id=SAV2001 | Sub-resource shows the relationship. |
POST /api/accounts | POST /api/createAccount | POST already means "create". |
DELETE /api/accounts/SAV2001 | POST /api/deleteAccount | Use DELETE method, not verb in URI. |
Rules for URI design:
- Use lowercase letters and hyphens for multi-word segments:
/api/loan-applications. - Use plural nouns:
/api/accountsnot/api/account. - Nest sub-resources one level deep:
/api/accounts/SAV2001/transactions. - Avoid nesting beyond two levels. Use query parameters instead.
- Use query parameters for filtering, sorting, and pagination:
/api/accounts?type=SAVINGS&sort=balance,desc&page=0&size=20.
package com.bank.controller;
import com.bank.dto.TransactionResponse;
import com.bank.service.TransactionService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/accounts/{accountId}/transactions")
public class TransactionController {
private final TransactionService transactionService;
public TransactionController(TransactionService transactionService) {
this.transactionService = transactionService;
}
// GET /api/accounts/SAV2001/transactions?page=0&size=10
@GetMapping
public Page<TransactionResponse> listTransactions(
@PathVariable String accountId,
Pageable pageable) {
return transactionService.findByAccount(accountId, pageable);
}
}
GET /api/accounts/SAV2001/transactions?page=0&size=2
HTTP 200 OK
{
"content": [
{"txnId":"TXN001","amount":-5000.00,"type":"DEBIT","date":"2025-01-15"},
{"txnId":"TXN002","amount":10000.00,"type":"CREDIT","date":"2025-01-14"}
],
"totalElements": 47,
"totalPages": 24,
"number": 0,
"size": 2
}
How do HTTP methods map to CRUD operations?
Each HTTP method has a well-defined semantic meaning.
| Method | CRUD | Idempotent | Safe | Request Body | Banking Example |
|---|---|---|---|---|---|
| GET | Read | Yes | Yes | No | Get account balance |
| POST | Create | No | No | Yes | Open a new account |
| PUT | Replace | Yes | No | Yes | Replace account details completely |
| PATCH | Partial update | No* | No | Yes | Update just the email address |
| DELETE | Delete | Yes | No | No | Close an account |
*PATCH is idempotent if the patch document is idempotent (for example, "set email to X"), but the HTTP spec does not guarantee it.
package com.bank.controller;
import com.bank.dto.*;
import com.bank.service.AccountService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
@RestController
@RequestMapping("/api/accounts")
public class AccountController {
private final AccountService accountService;
public AccountController(AccountService accountService) {
this.accountService = accountService;
}
// GET: Read all
@GetMapping
public List<AccountResponse> list() {
return accountService.findAll();
}
// GET: Read one
@GetMapping("/{accountId}")
public AccountResponse get(@PathVariable String accountId) {
return accountService.findById(accountId);
}
// POST: Create
@PostMapping
public ResponseEntity<AccountResponse> create(
@Valid @RequestBody CreateAccountRequest request) {
AccountResponse created = accountService.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.accountId())
.toUri();
return ResponseEntity.created(location).body(created);
}
// PUT: Replace
@PutMapping("/{accountId}")
public AccountResponse replace(
@PathVariable String accountId,
@Valid @RequestBody UpdateAccountRequest request) {
return accountService.replace(accountId, request);
}
// PATCH: Partial update
@PatchMapping("/{accountId}")
public AccountResponse patch(
@PathVariable String accountId,
@RequestBody PatchAccountRequest request) {
return accountService.patch(accountId, request);
}
// DELETE: Remove
@DeleteMapping("/{accountId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable String accountId) {
accountService.close(accountId);
}
}
POST /api/accounts
{"holderName":"Priya Sharma","type":"SAVINGS","initialDeposit":25000.00}
HTTP 201 Created
Location: /api/accounts/SAV2003
{"accountId":"SAV2003","holderName":"Priya Sharma","balance":25000.00,"type":"SAVINGS"}
What are proper HTTP status codes?
Status codes are grouped into five families.
| Range | Category | When to Use |
|---|---|---|
| 200-299 | Success | The request worked. |
| 300-399 | Redirection | The resource moved. |
| 400-499 | Client Error | The client sent a bad request. |
| 500-599 | Server Error | The server failed. |
Common status codes for a banking API:
| Code | Name | When to Use | Banking Example |
|---|---|---|---|
| 200 | OK | Successful GET, PUT, PATCH | Account balance retrieved |
| 201 | Created | Successful POST that created a resource | New account opened |
| 204 | No Content | Successful DELETE, no response body | Account closed |
| 400 | Bad Request | Malformed request body or invalid parameters | Missing holderName in create request |
| 401 | Unauthorized | Missing or invalid authentication | No JWT token provided |
| 403 | Forbidden | Authenticated but not authorized | Customer tries to access another customer's account |
| 404 | Not Found | Resource does not exist | Account SAV9999 not found |
| 409 | Conflict | Resource state conflict | Trying to open a duplicate account |
| 422 | Unprocessable Entity | Valid syntax but business rule violation | Transfer amount exceeds balance |
| 429 | Too Many Requests | Rate limit exceeded | More than 100 requests per minute |
| 500 | Internal Server Error | Unexpected server failure | Database connection failed |
package com.bank.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.net.URI;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(AccountNotFoundException.class)
public ProblemDetail handleNotFound(AccountNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, ex.getMessage());
pd.setTitle("Account Not Found");
pd.setType(URI.create(
"https://api.nationalbank.in/errors/account-not-found"));
return pd;
}
@ExceptionHandler(InsufficientFundsException.class)
public ProblemDetail handleInsufficientFunds(
InsufficientFundsException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage());
pd.setTitle("Insufficient Funds");
pd.setType(URI.create(
"https://api.nationalbank.in/errors/insufficient-funds"));
return pd;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ProblemDetail handleValidation(
MethodArgumentNotValidException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Validation failed");
pd.setTitle("Bad Request");
pd.setProperty("errors",
ex.getFieldErrors().stream()
.map(f -> f.getField() + ": " + f.getDefaultMessage())
.toList());
return pd;
}
}
POST /api/accounts
{"type":"SAVINGS"}
HTTP 400 Bad Request
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Validation failed",
"errors": ["holderName: must not be blank", "initialDeposit: must be positive"]
}
What is HATEOAS?
HATEOAS stands for Hypermedia As The Engine Of Application State. It means the API response includes links that tell the client what actions are available next. The client does not need to hardcode URLs.
Spring HATEOAS provides EntityModel and Link to add hypermedia links to responses.
package com.bank.controller;
import com.bank.dto.AccountResponse;
import com.bank.service.AccountService;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/accounts")
public class AccountHateoasController {
private final AccountService accountService;
public AccountHateoasController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{accountId}")
public EntityModel<AccountResponse> getAccount(
@PathVariable String accountId) {
AccountResponse account = accountService.findById(accountId);
return EntityModel.of(account,
WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(
AccountHateoasController.class).getAccount(accountId))
.withSelfRel(),
Link.of("/api/accounts/" + accountId + "/transactions",
"transactions"),
Link.of("/api/accounts/" + accountId + "/statements",
"statements")
);
}
}
GET /api/accounts/SAV2001
HTTP 200 OK
{
"accountId": "SAV2001",
"holderName": "Rajesh Kumar",
"balance": 75000.00,
"type": "SAVINGS",
"_links": {
"self": {"href": "/api/accounts/SAV2001"},
"transactions": {"href": "/api/accounts/SAV2001/transactions"},
"statements": {"href": "/api/accounts/SAV2001/statements"}
}
}
The client reads the _links section to discover what it can do next: view transactions, download statements, or refresh the account. If a link is absent (for example, no "close" link for an account with a positive balance), the client knows that action is not available.
How is REST different from SOAP?
| Feature | REST | SOAP |
|---|---|---|
| Protocol | HTTP | Any (HTTP, SMTP, JMS) |
| Message format | JSON, XML, or any | XML only (SOAP envelope) |
| Contract | OpenAPI/Swagger (optional) | WSDL (mandatory) |
| State | Stateless | Can be stateful |
| Error handling | HTTP status codes | SOAP Fault in XML body |
| Performance | Lightweight, fast | Heavier due to XML overhead |
| Caching | Built-in via HTTP cache headers | Not built-in |
| Tooling | Curl, Postman, any HTTP client | Requires SOAP client libraries |
| Banking use | Modern APIs, mobile apps | Legacy core banking systems |
// REST: lightweight JSON over HTTP
// POST /api/accounts
// {"holderName":"Priya Sharma","type":"SAVINGS","initialDeposit":25000}
// SOAP: heavy XML envelope
// <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
// <soap:Body>
// <CreateAccountRequest xmlns="http://nationalbank.in/ws">
// <holderName>Priya Sharma</holderName>
// <type>SAVINGS</type>
// <initialDeposit>25000</initialDeposit>
// </CreateAccountRequest>
// </soap:Body>
// </soap:Envelope>
REST response: ~100 bytes JSON
SOAP response: ~500 bytes XML with envelope, headers, and namespaces
What are common mistakes in REST API design?
Mistake 1: Using verbs in URIs
WRONG: Verbs in URIs duplicate the meaning of HTTP methods.
POST /api/createAccount
GET /api/getAccountById?id=SAV2001
POST /api/deleteAccount
POST /api/transferMoney
CORRECT: Use nouns for resources and HTTP methods for actions.
POST /api/accounts
GET /api/accounts/SAV2001
DELETE /api/accounts/SAV2001
POST /api/accounts/SAV2001/transfers
Mistake 2: Returning 200 for everything
WRONG: Always returning 200 with an error flag in the body.
// WRONG: Returns 200 even when the account is not found
@GetMapping("/{accountId}")
public Map<String, Object> getAccount(
@PathVariable String accountId) {
try {
AccountResponse account = accountService.findById(accountId);
return Map.of("success", true, "data", account);
} catch (AccountNotFoundException e) {
return Map.of("success", false, "error", e.getMessage());
}
}
CORRECT: Use proper HTTP status codes.
// CORRECT: Returns 404 when not found, 200 when found
@GetMapping("/{accountId}")
public ResponseEntity<AccountResponse> getAccount(
@PathVariable String accountId) {
AccountResponse account = accountService.findById(accountId);
return ResponseEntity.ok(account);
}
// AccountNotFoundException is caught by @RestControllerAdvice
// and mapped to 404 Not Found with a ProblemDetail body
What should a senior or principal engineer know?
- API-first design. Write the OpenAPI (Swagger) specification before writing any code. Use springdoc-openapi to generate documentation from your Spring annotations, but design the contract first and validate that the implementation matches.
- Idempotency keys. POST is not idempotent by nature. For critical banking operations like creating a transfer, require the client to send an Idempotency-Key header. The server stores the key and returns the same response if the client retries. This prevents duplicate transactions when the network drops.
- Rate limiting and throttling. Protect banking APIs with rate limiting at the API gateway layer. Use 429 Too Many Requests with a Retry-After header when the limit is exceeded.
- ETags for optimistic concurrency. Include an ETag header in GET responses. The client sends If-Match on PUT/PATCH requests. If the ETag does not match (another client modified the resource), return 412 Precondition Failed. This prevents lost updates on shared accounts.
- RFC 7807 ProblemDetail. Spring 6 and Spring Boot 3.x natively support RFC 7807 (Problem Details for HTTP APIs). Use ProblemDetail as the return type in exception handlers for a consistent, machine-readable error format across all endpoints.
- Content negotiation. Use the Accept header to support multiple formats from the same endpoint. Spring MVC handles JSON by default (via Jackson) and can support XML by adding the jackson-dataformat-xml dependency.
package com.bank.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
@RequestMapping("/api/transfers")
public class IdempotentTransferController {
private final Map<String, TransferResponse> idempotencyStore =
new ConcurrentHashMap<>();
@PostMapping
public ResponseEntity<TransferResponse> transfer(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody TransferRequest request) {
// If we already processed this key, return the stored response
if (idempotencyStore.containsKey(idempotencyKey)) {
return ResponseEntity.ok(
idempotencyStore.get(idempotencyKey));
}
// Process the transfer
TransferResponse response = processTransfer(request);
idempotencyStore.put(idempotencyKey, response);
return ResponseEntity.status(201).body(response);
}
private TransferResponse processTransfer(TransferRequest request) {
// Business logic here
return new TransferResponse("TXN-12345", "SUCCESS");
}
record TransferRequest(String from, String to,
java.math.BigDecimal amount) {}
record TransferResponse(String txnId, String status) {}
}
// First call
POST /api/transfers
Idempotency-Key: abc-123
{"from":"SAV2001","to":"SAV2002","amount":5000.00}
HTTP 201 Created
{"txnId":"TXN-12345","status":"SUCCESS"}
// Retry with same key (network failure recovery)
POST /api/transfers
Idempotency-Key: abc-123
{"from":"SAV2001","to":"SAV2002","amount":5000.00}
HTTP 200 OK (same response, no duplicate transfer)
{"txnId":"TXN-12345","status":"SUCCESS"}
What are common interview follow-up questions?
- What is the difference between PUT and PATCH?
- When would you use 201 vs 200 for a POST request?
- How do you handle pagination in a REST API?
- What is the Richardson Maturity Model?
- How do you version a REST API?
- What is the difference between stateless and stateful APIs?
- How does content negotiation work with the Accept header?
- What is an idempotent operation and why does it matter for banking transfers?
- How do you document a REST API using OpenAPI/Swagger?
- What is the difference between REST and GraphQL?
Visual Overview
Client (Mobile App / Web)
|
| HTTP Request
| GET /api/accounts/SAV2001
| Accept: application/json
| Authorization: Bearer <jwt>
v
+---------------------------+
| API Gateway |
| Rate limiting, auth |
+---------------------------+
|
v
+---------------------------+
| DispatcherServlet |
+---------------------------+
|
v
+---------------------------+
| AccountController |
| @GetMapping("/{id}") |
+---------------------------+
|
v
+---------------------------+
| AccountService |
| Business rules |
+---------------------------+
|
v
+---------------------------+
| AccountRepository |
| SELECT * FROM accounts |
+---------------------------+
|
v
+---------------------------+
| PostgreSQL |
+---------------------------+
|
v
HTTP Response
200 OK
Content-Type: application/json
{"accountId":"SAV2001",...}
HTTP Methods and CRUD
=====================
GET /api/accounts -> List all accounts
GET /api/accounts/SAV2001 -> Get one account
POST /api/accounts -> Create new account
PUT /api/accounts/SAV2001 -> Replace account
PATCH /api/accounts/SAV2001 -> Update partially
DELETE /api/accounts/SAV2001 -> Close account
Sub-resources:
GET /api/accounts/SAV2001/transactions
POST /api/accounts/SAV2001/transfers
GET /api/accounts/SAV2001/statements
Key Takeaway
REST is an architectural style that uses URIs to identify resources and HTTP methods to define actions. In a banking API, the resource is an account or a transaction, identified by a URI like /api/accounts/SAV2001. GET reads it, POST creates it, PUT replaces it, PATCH updates a part of it, and DELETE removes it. The HTTP method carries the verb, so the URI stays a clean noun.
Status codes are not decoration. They are the first thing a client checks. A 201 tells the mobile app that the new account was created. A 404 tells it the account does not exist. A 422 tells it the transfer violates a business rule. Using 200 for everything and hiding the real status in the response body defeats the purpose of HTTP.
HATEOAS takes the API a step further by including links in the response. When Rajesh retrieves his account, the response includes links to his transactions, statements, and transfer endpoints. The client follows these links instead of constructing URLs manually. This decouples the client from the URL structure.
For production banking systems, idempotency keys prevent duplicate transactions when the client retries a failed POST. ETags prevent lost updates when two tellers modify the same account. Rate limiting protects the API from abuse. And RFC 7807 ProblemDetail gives every error a consistent, machine-readable format.
Remember one sentence: REST uses URIs for resources, HTTP methods for actions, and status codes for results.
---