Lesson 4 of 12 · 9 min · Building REST APIs

REST controllers and request mapping

Covers: Spring Boot 4.1 and Spring Framework 7 on Java 17 or newer. Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • What REST means in practice: resources, HTTP methods and JSON
  • Write controllers with @RestController, @GetMapping, @PostMapping and friends
  • Read data with @PathVariable, @RequestParam and @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 5 in /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: GET read, POST create, PUT replace, PATCH change part, DELETE remove.
  • 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, @PatchMapping and @DeleteMapping are 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) or defaultValue for optional parameters; Optional<String> also works.
  • Parameter names must match unless you write @PathVariable("id"); Spring Boot's build keeps parameter names (the -parameters flag is on with the Boot Maven and Gradle plugins), but being explicit is safe.
  • A path variable that cannot convert (/orders/abc for a long) 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.

Trying it out

  • curl -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{"customerId":3,"productIds":[1,2]}'
  • Tools: Postman, Bruno, IntelliJ HTTP client files, or the browser for GET.
  • Add springdoc-openapi to generate OpenAPI documentation and a Swagger UI automatically (check that the version matches your Boot version).
  • Spring Boot 4 adds HTTP service clients and API versioning support in Spring MVC for evolving APIs; for most projects, a simple URI prefix such as /api/v1/orders is enough to start.

Other mapping features

  • @RequestMapping can 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 Pageable parameter reads ?page=0&size=20&sort=amount,desc with Spring Data.
  • File upload: MultipartFile with @RequestParam("file").
  • CORS (a browser app on another origin): @CrossOrigin or a global WebMvcConfigurer (the security lesson shows the secure way).
  • Async and streaming: return CompletableFuture, Flux (WebFlux) or SseEmitter; 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 GET to change data, or POST for everything.
  • Forgetting @RequestBody, so the object arrives empty.
  • Putting the main class in the wrong package, so controllers are not scanned.
  • Mixing up @RestController and @Controller.

Try it yourself

  1. Create an OrderController with in-memory storage (a Map) for list, get, create and delete.
  2. Call each endpoint with curl and inspect headers with -i.
  3. Add a filter record with status and minAmount bound from query parameters.
  4. Move the storage logic into a @Service and make the controller call it.
  5. Rename a JSON field with @JsonProperty and 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.
  • @RestController with @GetMapping, @PostMapping and 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

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.