Lesson 4 of 12 · 9 min · Building REST APIs
REST controllers and request mapping
What you will learn
- What REST means in practice: resources, HTTP methods and JSON
- Write controllers with
@RestController,@GetMapping,@PostMappingand friends - Read data with
@PathVariable,@RequestParamand@RequestBody - How Spring turns Java objects into JSON and back
- Keep controllers thin and call a service
In simple words
A REST API is a set of web addresses that programs (a phone app, a React page) call to get or change data, sending and receiving JSON. A controller is the receptionist: it receives the request, works out which method should handle it from the address and the HTTP verb, passes the details to the business code, and returns the answer. A good receptionist does not do the work personally.
Words to know
- REST: a style of web API where addresses stand for resources and HTTP methods say what to do.
- Controller: the class that receives web requests and returns responses.
- Path variable: a value inside the address, such as the
5in/orders/5. - JSON: the text format used to send data to and from APIs.
REST in four lines
- A resource is a thing: an order, a customer. It has an address (a URI):
/orders/5. - HTTP methods say what to do:
GETread,POSTcreate,PUTreplace,PATCHchange part,DELETEremove. - The body is usually JSON; the response has a status code (next lesson).
- Requests are stateless: each carries everything the server needs.
| Request | Meaning |
|---|---|
GET /orders |
list orders |
GET /orders/5 |
get order 5 |
POST /orders |
create an order (body has the data) |
PUT /orders/5 |
replace order 5 |
DELETE /orders/5 |
delete order 5 |
Use plural nouns for collections, not verbs in the path (/orders, not /getOrders); sub-resources nest (/customers/3/orders); put filters in the query string (/orders?status=paid&page=2).
A first controller
With spring-boot-starter-webmvc:
@RestController
@RequestMapping("/orders")
public class OrderController {
private final OrderService service;
public OrderController(OrderService service) {
this.service = service;
}
@GetMapping
public List<OrderResponse> list(@RequestParam(defaultValue = "paid") String status) {
return service.findByStatus(status);
}
@GetMapping("/{id}")
public OrderResponse get(@PathVariable long id) {
return service.get(id);
}
@PostMapping
public OrderResponse create(@RequestBody CreateOrderRequest request) {
return service.create(request);
}
@PutMapping("/{id}")
public OrderResponse replace(@PathVariable long id, @RequestBody CreateOrderRequest request) {
return service.replace(id, request);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable long id) {
service.delete(id);
}
}
@RestController=@Controller+@ResponseBody: the return value is written to the response body as JSON, not looked up as a view name.@RequestMapping("/orders")on the class sets a common prefix;@GetMapping,@PostMapping,@PutMapping,@PatchMappingand@DeleteMappingare shortcuts for@RequestMapping(method = ...).- Run the application and call it:
curl localhost:8080/orders/5.
Getting data from the request
| Annotation | Reads | Example |
|---|---|---|
@PathVariable |
a part of the path | /orders/{id} → @PathVariable long id |
@RequestParam |
a query or form parameter | ?status=paid → @RequestParam String status |
@RequestBody |
the request body, converted from JSON | @RequestBody CreateOrderRequest r |
@RequestHeader |
a header | @RequestHeader("X-Request-Id") String id |
@CookieValue |
a cookie |
Useful details:
@RequestParam(required = false)ordefaultValuefor optional parameters;Optional<String>also works.- Parameter names must match unless you write
@PathVariable("id"); Spring Boot's build keeps parameter names (the-parametersflag is on with the Boot Maven and Gradle plugins), but being explicit is safe. - A path variable that cannot convert (
/orders/abcfor along) gives 400 Bad Request automatically. - For many query parameters, bind to an object (a record) without
@RequestParam:public List<OrderResponse> list(OrderFilter filter, Pageable pageable). - Restrict by content type or headers:
@PostMapping(consumes = "application/json", produces = "application/json").
JSON conversion
Spring MVC converts Java objects to JSON and back with Jackson. Boot 4 uses Jackson 3 (packages under tools.jackson); the annotations such as @JsonProperty, @JsonIgnore and @JsonFormat still live in com.fasterxml.jackson.annotation. Records make clean request and response types:
public record CreateOrderRequest(long customerId, List<Long> productIds) {}
public record OrderResponse(long id, String customer, double amount, String status) {}
A request body {"customerId": 3, "productIds": [1, 2]} becomes a CreateOrderRequest. A returned OrderResponse becomes {"id":101,"customer":"Asha","amount":1200.0,"status":"paid"}. Customise with properties (spring.jackson.*), annotations (@JsonProperty("order_id") to rename, @JsonIgnore to hide a field, @JsonInclude(NON_NULL) to omit nulls), or by defining a JsonMapper bean. Dates: use java.time types (LocalDate, Instant); they serialise to ISO-8601 strings, which is the standard for APIs. Never return JPA entities directly (next lesson).
Keep controllers thin
A controller should only: receive the request, validate the input, call a service, and shape the response. Business rules, transactions and database access belong in the service and repository layers.
Controller → Service → Repository → Database
(HTTP) (business) (data)
A controller that contains if statements about prices and loops over database rows is hard to test and reuse. Test the service as plain Java and the controller with a slice test (@WebMvcTest) that mocks the service.
Other mapping features
@RequestMappingcan match on method, path patterns (/files/{*path}), params and headers.ResponseEntity<T>gives full control of status, headers and body (the next lesson).- Pagination and sorting: a
Pageableparameter reads?page=0&size=20&sort=amount,descwith Spring Data. - File upload:
MultipartFilewith@RequestParam("file"). - CORS (a browser app on another origin):
@CrossOriginor a globalWebMvcConfigurer(the security lesson shows the secure way). - Async and streaming: return
CompletableFuture,Flux(WebFlux) orSseEmitter; virtual threads (spring.threads.virtual.enabled=true) let blocking code scale.
Common mistakes
- Business logic in controllers.
- Verbs in URLs and inconsistent naming.
- Returning entities instead of DTOs.
- Using
GETto change data, orPOSTfor everything. - Forgetting
@RequestBody, so the object arrives empty. - Putting the main class in the wrong package, so controllers are not scanned.
- Mixing up
@RestControllerand@Controller.
Try it yourself
- Create an
OrderControllerwith in-memory storage (aMap) for list, get, create and delete. - Call each endpoint with
curland inspect headers with-i. - Add a filter record with
statusandminAmountbound from query parameters. - Move the storage logic into a
@Serviceand make the controller call it. - Rename a JSON field with
@JsonPropertyand hide another with@JsonIgnore.
Check yourself
What does @RestController do?
It marks a class as a web controller whose return values are written directly to the response body (as JSON), combining @Controller and @ResponseBody.
What is the difference between @PathVariable and @RequestParam?
@PathVariable reads a value embedded in the URL path (/orders/5); @RequestParam reads a query string or form parameter (?status=paid).
Which HTTP method is used to create a resource?
POST, typically to the collection address such as /orders.
Why keep controllers thin?
So business logic can be tested and reused independently of HTTP, and the web layer only handles requests and responses.
Interview questions
Explain how a request flows through Spring MVC.
The embedded server passes the request to the DispatcherServlet, which asks the handler mapping which controller method matches, converts arguments (path variables, parameters, JSON body), calls the method, converts the return value to JSON through message converters and writes the response.
What are the main HTTP methods and which are idempotent?
GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (remove). GET, PUT and DELETE are idempotent: repeating them has the same effect as doing them once; POST is not.
What is the difference between @Controller and @RestController?
@Controller returns view names for rendered pages by default; @RestController adds @ResponseBody so every method returns data written to the body.
Summary
- REST maps resources to URIs and actions to HTTP methods; use plural nouns and JSON.
@RestControllerwith@GetMapping,@PostMappingand so on; read input with@PathVariable,@RequestParam,@RequestBody.- Jackson converts records and objects to and from JSON; Boot 4 uses Jackson 3.
- Keep the controller thin and delegate to services.
Going deeper
- Spring MVC: Annotated controllers: mappings and method arguments.
- Spring Boot: Developing web applications: Spring MVC with Boot.
- Building a RESTful Web Service (Spring guide): a short working tutorial.
- MDN: HTTP request methods: what each method means.
See how much of this you can explain
A free mock interview asks you new questions on Spring Boot, REST and JPA for Java Full Stack Developer and scores every answer, with what to fix.