Skip to lesson

REST Principles, HTTP Methods and Status Codes

A REST round has two parts: quick questions on methods and status codes, then "design the endpoints for...". The interviewer checks that you pick the right method and the right status code, and can say why in one sentence.

REST constraints and resource naming

A resource is anything the API names, such as a product or an order, identified by a URL. REST models the system as resources, acts on them with standard HTTP methods and sends representations such as JSON.

A REST URL names a thing, and the HTTP method says what to do with it. This request reads product 1 from the ShopLite API.

Example 1 · A REST request and response with curl

Runs in: the ShopLite REST API from Section 15, running on port 8080

Terminal
curl -i http://localhost:8080/api/v1/products/1
Sample output
HTTP/1.1 200
Content-Type: application/json

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}

What this code does

  • The URL names one resource (product 1) with a plural noun and an id; the method GET says "read". -i shows the status line and headers before the JSON body.
  • This runs against the ShopLite API from Sections 14 and 15; your headers may include a few more lines such as Date.

REST has six constraints: client-server, stateless, cacheable, uniform interface, layered system and optional code on demand. Use plural nouns (/products, /orders/14), one level of ownership (/customers/2/orders), lowercase words with hyphens and a version in the path (/api/v1/...).

Revise: Resources and URLs (opens in a new tab), API versioning (opens in a new tab).

Find the bug

Spot the endpoint that breaks REST

One endpoint in each list is badly designed. Click it.

Which endpoint is not RESTful?

Round 1 of 3

HTTP methods: safe and idempotent

An idempotent method has the same effect on the server whether it is sent once or many times. GET, HEAD, OPTIONS, PUT and DELETE are idempotent; POST is not, and PATCH is not guaranteed to be.

Retrying after a timeout is only safe for some methods. This example sends identical requests twice and checks what exists afterwards.

Example 2 · POST is not idempotent; PUT and DELETE are

IdempotencyDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class IdempotencyDemo {    static Map<Integer, String> orders = new LinkedHashMap<>();    static int nextId = 1;
    static String post(String item) {                 // create: a new resource every time        int id = nextId++;        orders.put(id, item);        return "201 Created /orders/" + id;    }
    static String put(int id, String item) {          // replace: same result every time        boolean existed = orders.containsKey(id);        orders.put(id, item);        return existed ? "200 OK" : "201 Created";    }
    static String delete(int id) {                    // state is the same after 1 or 2 calls        return orders.remove(id) != null ? "204 No Content" : "404 Not Found";    }
    public static void main(String[] args) {        System.out.println("POST twice:   " + post("dosa") + ", " + post("dosa"));        System.out.println("orders now:   " + orders);        System.out.println("PUT twice:    " + put(1, "masala dosa") + ", " + put(1, "masala dosa"));        System.out.println("orders now:   " + orders);        System.out.println("DELETE twice: " + delete(2) + ", " + delete(2));        System.out.println("orders now:   " + orders);    }}
Output
POST twice:   201 Created /orders/1, 201 Created /orders/2
orders now:   {1=dosa, 2=dosa}
PUT twice:    200 OK, 200 OK
orders now:   {1=masala dosa, 2=dosa}
DELETE twice: 204 No Content, 404 Not Found
orders now:   {1=masala dosa}

What this code does

  • Two identical POSTs create two orders (ids 1 and 2). Two identical PUTs leave order 1 in the same state after the first call.
  • The second DELETE returns 404 instead of 204, yet the server state is the same as after the first: idempotency is about state, not about the response code.

Safe methods (GET, HEAD, OPTIONS) do not change server state at all. Payment APIs make a POST retry-safe with an idempotency key: the server stores the first response for that key and replays it. Idempotency is about server state, not the response: a second DELETE returns 404, yet the state is the same.

Revise: Safe and idempotent methods (opens in a new tab), Idempotency keys (opens in a new tab).

Predict the output

What happens on a retry?

Predict the output. These are plain Java models of the requests.

Round 1 of 2

A client retries after a timeout. POST adds an order, PUT stores product 7. What prints?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RetryCount {
public static void main(String[] args) {
List<String> orders = new ArrayList<>();
Map<Integer, String> products = new HashMap<>();
for (int attempt = 0; attempt < 2; attempt++) {
orders.add("order for customer 2");
products.put(7, "Calculator");
}
System.out.println("orders=" + orders.size() + " products=" + products.size());
}
}

Status codes interviewers ask

401 Unauthorized means the request is not authenticated: no token, or a bad or expired one. 403 Forbidden means the server knows who you are but you are not allowed to do this.

Pick the code that tells the client what to do next. This Spring controller answers with 201 and a Location header, 404 and 409.

The first digit of a status code is its family. 2xx means success, for example 200, 201 and 204. 3xx means redirection, for example 301, 302 and 304. 4xx means the client made a mistake, 5xx means the server failed.

Example 3 · 201 with Location, 404 and 409 in a Spring controller

Runs in: a Spring Boot 4 web project (Section 15)

SProductController.javaJava
import java.math.BigDecimal;import java.net.URI;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.DeleteMapping;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.server.ResponseStatusException;import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
record ProductRequest(String sku, String name, long categoryId, BigDecimal price) {}
record Product(long id, String sku, String name, long categoryId, BigDecimal price) {}
@RestController@RequestMapping("/api/v1/products")public class SProductController {    private final Map<Long, Product> products = new ConcurrentHashMap<>();    private final AtomicLong ids = new AtomicLong();
    @GetMapping("/{id}")    public Product get(@PathVariable long id) {                       // 200 or 404        Product p = products.get(id);        if (p == null) {            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product " + id + " not found");        }        return p;    }
    @PostMapping    public ResponseEntity<Product> create(@RequestBody ProductRequest req) {   // 201 + Location        boolean skuTaken = products.values().stream().anyMatch(p -> p.sku().equals(req.sku()));        if (skuTaken) {            throw new ResponseStatusException(HttpStatus.CONFLICT, "SKU " + req.sku() + " already exists");        }        long id = ids.incrementAndGet();        Product saved = new Product(id, req.sku(), req.name(), req.categoryId(), req.price());        products.put(id, saved);        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();        return ResponseEntity.created(location).body(saved);    }
    @DeleteMapping("/{id}")    public ResponseEntity<Void> delete(@PathVariable long id) {       // 204, then 404        if (products.remove(id) == null) {            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Product " + id + " not found");        }        return ResponseEntity.noContent().build();    }}
Sample output
POST /api/v1/products            -> 201 Created
  Location: http://localhost:8080/api/v1/products/1
POST /api/v1/products (same SKU) -> 409 Conflict
GET  /api/v1/products/1          -> 200 OK
GET  /api/v1/products/99         -> 404 Not Found
DELETE /api/v1/products/1        -> 204 No Content
DELETE /api/v1/products/1        -> 404 Not Found

What this code does

  • ResponseEntity.created(location).body(saved) sends 201 with a Location header pointing at the new resource; ResponseEntity.noContent() sends 204 with no body.
  • Throwing ResponseStatusException with NOT_FOUND or CONFLICT makes Spring answer 404 or 409. Real projects use a @RestControllerAdvice to return one error format, like ShopLite's Problem Details.

2xx: 200 OK, 201 Created (with Location), 204 No Content. 4xx: 400 invalid input, 404 not found, 409 conflict (duplicate e-mail, invalid state change), 422 unprocessable, 429 too many requests. 5xx: 500 unexpected failure, 502/503/504 gateway problems. 3xx: 301 and 302 redirect, 304 means "your cached copy is still valid".

Revise: HTTP status codes (opens in a new tab), Status codes in Spring (opens in a new tab).

Predict the output

Which status code?

Pick the status the API should return.

Round 1 of 3

Which status does the API return?

GET /api/v1/orders/14 HTTP/1.1
Authorization: Bearer <token that expired an hour ago>

PUT vs PATCH

PUT replaces the whole resource, so every field must be sent. PATCH changes only the fields that are sent. Both go to a known URL such as /products/7.

A partial update must not wipe the other fields. This example applies the same price change with PATCH and with a PUT that is missing fields.

Example 4 · PUT replaces the whole resource, PATCH changes fields

PutPatchDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
public class PutPatchDemo {    static Map<String, Object> put(Map<String, Object> body) {        Map<String, Object> replaced = new LinkedHashMap<>();        for (String field : new String[] {"name", "price", "stock"}) {            replaced.put(field, body.get(field));            // missing fields become null        }        return replaced;    }
    static Map<String, Object> patch(Map<String, Object> current, Map<String, Object> changes) {        Map<String, Object> updated = new LinkedHashMap<>(current);        updated.putAll(changes);                             // only the sent fields change        return updated;    }
    public static void main(String[] args) {        Map<String, Object> product = new LinkedHashMap<>();        product.put("name", "Calculator");        product.put("price", 450);        product.put("stock", 12);        System.out.println("current:          " + product);
        Map<String, Object> onlyPrice = Map.of("price", 399);        System.out.println("PATCH {price}:    " + patch(product, onlyPrice));        System.out.println("PUT {price} only: " + put(onlyPrice) + "  <- a PUT replaces everything");
        Map<String, Object> full = new LinkedHashMap<>(product);        full.put("price", 399);        System.out.println("PUT full body:    " + put(full));    }}
Output
current:          {name=Calculator, price=450, stock=12}
PATCH {price}:    {name=Calculator, price=399, stock=12}
PUT {price} only: {name=null, price=399, stock=null}  <- a PUT replaces everything
PUT full body:    {name=Calculator, price=399, stock=12}

What this code does

  • PATCH with only price keeps name and stock. A PUT with only price replaces the resource, so the missing fields become null; that is why APIs require every field in a PUT body.
  • A PUT with the full body gives the same result as the PATCH, and sending it twice changes nothing more: PUT is idempotent.

PUT is idempotent: sending the full body twice leaves the same state. PATCH is smaller and avoids overwriting a field that another client changed, but it is not guaranteed to be idempotent (for example "add 1 to stock"). Well-designed APIs reject an incomplete PUT with 400.

Revise: CRUD methods and status codes (opens in a new tab).

Path vs query parameters, and stateless

Stateless means the server keeps no per-client session between requests. Each request carries everything the server needs, usually a token, so any server behind a load balancer can answer it.

A path variable identifies one resource (/orders/14). Query parameters filter, sort or page a collection (/orders?status=SHIPPED&page=0&size=10).

Traditional web apps keep a server-side session found through a cookie (JSESSIONID), which needs sticky sessions or a shared session store to scale. A token API such as one with JWT keeps no session: the identity sits in the signed token in the Authorization header.

Revise: Why HTTP is stateless (opens in a new tab), Token authentication basics (opens in a new tab).

Design question: endpoints for a ShopLite order

Answer design questions in four steps: name the resources, list the endpoints with methods, give the request and response shape, and state the status codes. This example runs the ShopLite order flow request by request.

Example 5 · The ShopLite order flow, request by request

Runs in: the ShopLite REST API from Section 15, running on port 8080

Terminal
curl -i -X POST http://localhost:8080/api/v1/orders \  -H "Content-Type: application/json" \  -d '{"customerId":2,"addressId":3,"items":[{"productId":1,"quantity":1}]}'curl -i -X POST http://localhost:8080/api/v1/orders/14/cancelcurl -i -X POST http://localhost:8080/api/v1/orders/14/cancelcurl -i "http://localhost:8080/api/v1/customers/2/orders?status=CANCELLED&page=0&size=10"
Sample output
HTTP/1.1 201
Location: http://localhost:8080/api/v1/orders/14
{"id":14,"customerId":2,"addressId":3,"status":"PLACED",...}

HTTP/1.1 200
{"id":14,...,"status":"CANCELLED",...}

HTTP/1.1 409
Content-Type: application/problem+json
{"type":".../invalid-state","title":"Invalid order state","status":409,...}

HTTP/1.1 200
{"content":[{"id":14,"customerId":2,"status":"CANCELLED",...}],"page":0,"size":10,"totalElements":1,"totalPages":1}

What this code does

  • Creating returns 201 and a Location; the state change is an action sub-resource (/cancel) answered with 200 and the updated order, and cancelling twice gives 409 because the order is no longer PLACED.
  • The customer's orders are a paged collection filtered with query parameters. Output is shortened with ...; ids depend on your data.

State changes that are not plain field edits become sub-resource actions: POST /orders/{id}/cancel answers 200, or 409 when the order state does not allow it. Orders are never deleted, so there is no DELETE /orders/{id}. Also mention validation (400), missing references (422), out of stock (409) and idempotency keys for payments.

Revise: REST design exercises (opens in a new tab), ShopLite API design (opens in a new tab).

Order of execution

Structure a design answer

Put the parts of a "design the endpoints" answer in a good order.

Next step

Check your understanding

12 quick questions