HTTP & REST fundamentals
Every backend you have built speaks HTTP. Learn methods, status codes, headers, statelessness and what actually makes an API "RESTful".
The concept
HTTP is a request/response protocol. A client sends a request made of a method, a path, headers and an optional body. The server returns a status code, headers and an optional body. The protocol itself is stateless, so each request must carry everything the server needs to understand it, such as an Authorization header or a cookie.
REST (Representational State Transfer) is an architectural style built on top of HTTP:
- Resources are nouns identified by URLs:
/products/42,/companies/{id}/accounts. - Methods are the verbs you apply to those resources.
- Representations are formats such as JSON that you exchange.
- Status codes describe the outcome.
Methods and their guarantees
| Method | Meaning | Safe? | Idempotent? | Typical success |
|---|---|---|---|---|
| GET | Read a resource | ✅ | ✅ | 200 OK |
| POST | Create / trigger an action | ❌ | ❌ | 201 Created, 202 Accepted |
| PUT | Replace a resource completely | ❌ | ✅ | 200 / 204 |
| PATCH | Partially update | ❌ | ❌ (usually) | 200 |
| DELETE | Remove | ❌ | ✅ | 204 No Content |
Safe means the request doesn’t change state. Idempotent means sending the same request twice leaves the server in the same state as sending it once. Idempotency matters because networks retry: if a client times out and resends a PUT, nothing breaks, but resending a POST /checkout could charge twice. Module 6 covers idempotency keys, which make POST safe to retry.
Status codes you must know cold
| Code | When to use it |
|---|---|
| 200 OK | Successful read or update returning a body |
| 201 Created | A resource was created; include a Location header |
| 202 Accepted | Work queued for later (e.g. an async export) |
| 204 No Content | Success with nothing to return (DELETE) |
| 400 Bad Request | Malformed input / validation failure |
| 401 Unauthorized | Not authenticated (missing or invalid token) |
| 402 Payment Required | Rarely used, but meaningful for failed payment |
| 403 Forbidden | Authenticated but not allowed |
| 404 Not Found | Resource does not exist (or you hide that it does) |
| 409 Conflict | State conflict: duplicate, optimistic lock failure, invalid transition |
| 422 Unprocessable Entity | Syntactically fine but semantically invalid |
| 429 Too Many Requests | Rate limited; include Retry-After |
| 500 Internal Server Error | Bug on the server |
| 502/503/504 | Upstream/gateway/unavailable/timeout |
Detailed example
A full lifecycle for a “product” resource:
POST /products HTTP/1.1
Content-Type: application/json
Authorization: Bearer eyJhbGci...
{ "name": "Headphones", "price": 79.99, "categoryId": 3 }
HTTP/1.1 201 Created
Location: /products/42
Content-Type: application/json
{ "id": 42, "name": "Headphones", "price": 79.99, "categoryId": 3 }
In Spring that becomes:
@PostMapping
public ResponseEntity<ProductDto> create(@Valid @RequestBody ProductDto dto,
UriComponentsBuilder uri) {
ProductDto saved = service.create(dto);
URI location = uri.path("/products/{id}").buildAndExpand(saved.getId()).toUri();
return ResponseEntity.created(location).body(saved); // 201 + Location
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build(); // 204
}
In your projects
controllers/ProductController.java · UserController.javaSpring-Boot-Store follows REST conventions closely. Creation returns ResponseEntity.created(uri) built with UriComponentsBuilder, and deletes return noContent(). Resources are plain nouns: /users, /products, /carts/{id}/items, /orders/{id}.
ledger/web/JournalController.javaSperoTek uses action endpoints for state transitions that don’t fit CRUD: POST /api/v1/companies/{companyId}/journals/{id}/post, /submit, /withdraw and /reverse. That is a pragmatic REST style. “Posting” a journal is a business command, not a field update, so modelling it as PATCH {"status":"POSTED"} would hide the rules involved: balance checks, an open period, gap-free numbering.
shared/exception/GlobalExceptionHandler.javaThe Hostel app maps domain failures onto precise status codes:
RoomFullyOccupiedException,BookingAlreadyExistsExceptionandInvalidBookingTransitionExceptionreturn 409.PaymentFailedExceptionreturns 402.DisabledExceptionreturns 403.- Validation failures return 400.
Alternatives to REST
| Style | Strength | Weakness | When |
|---|---|---|---|
| REST/JSON (what you use) | Simple, cacheable, universal tooling | Over/under-fetching, many round trips | Public & most internal APIs |
| GraphQL | Client chooses fields, one round trip | Caching harder, N+1 risk, complex auth per field | Many clients with different data needs |
| gRPC | Binary (Protobuf), fast, streaming, typed contracts | Not browser-native, harder to debug | Service-to-service |
RPC over HTTP (POST /doThing) |
Matches commands naturally | Loses HTTP semantics | Internal tooling |
The bonus module covers GraphQL and gRPC in depth.
Related concepts you must know
- Headers:
Content-Type,Accept,Authorization,Cache-Control,ETag/If-None-Match,Location,Retry-After, andX-Correlation-Id(used in SperoTek). - HTTP/1.1 vs HTTP/2 vs HTTP/3: HTTP/2 multiplexes many requests over one TCP connection. Hostel enables it with
server.http2.enabled. HTTP/3 runs over QUIC/UDP. - TLS/HTTPS: encrypts the connection. HSTS forces browsers to use it (Module 4).
- Content negotiation: the
Acceptheader tells the server which representation the client wants. SperoTek’s report export can serve PDF, XLSX or CSV. - HATEOAS: strict REST puts links in responses. It is rarely used in practice, but interviewers ask about it.
- The Richardson Maturity Model: level 0 is RPC over POST, level 1 adds resources, level 2 adds proper verbs and status codes (where you are), and level 3 adds hypermedia.