Skip to lesson

@RestController and @RequestMapping

A customer opens the ShopLite app and asks for the list of categories. The app sends an HTTP request, and some Java method on the server must answer with data the app can read.

@RestController = @Controller + @ResponseBody

@RestController marks a class as a REST controller: a class whose methods answer HTTP requests and return data, not web pages. It is @Controller (this bean handles requests) plus @ResponseBody (the return value is the response body).

ShopLite needs a Java class that answers web requests with data, not with web pages. Spring has one annotation for it. The example returns a plain message, first the short way, then the long way.

Example 1 · HelloController.java, OldStyleHelloController.java

Runs in: the rest-lab practice project (Spring Boot 4.1)

HelloController.javaJava
// src/main/java/com/shoplite/lab/HelloController.javapackage com.shoplite.lab;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class HelloController {
    @GetMapping("/lab/hello")    public String hello() {        return "ShopLite lab is running";    }}
// src/main/java/com/shoplite/lab/OldStyleHelloController.javapackage com.shoplite.lab;
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;
@Controllerpublic class OldStyleHelloController {
    @GetMapping("/lab/hello-old")    @ResponseBody    public String hello() {        return "ShopLite lab is running";    }}
Output
$ curl http://localhost:8080/lab/hello
ShopLite lab is running
$ curl http://localhost:8080/lab/hello-old
ShopLite lab is running

What this code does

  • HelloController uses @RestController, so the returned text is the response body.
  • OldStyleHelloController writes the same thing the long way: @Controller on the class and @ResponseBody on the method. Both answer with the same body.
  • No line in either class creates the controller with new: Spring finds it at startup, like any @Component, and calls the method when a matching request arrives.

Example 2 · GreetingController.java: @Controller without @ResponseBody

Runs in: the rest-lab practice project (Spring Boot 4.1)

GreetingController.javaJava
// src/main/java/com/shoplite/lab/GreetingController.javapackage com.shoplite.lab;
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;
@Controllerpublic class GreetingController {
    @GetMapping("/lab/greeting")    public String greeting() {        return "Welcome to ShopLite";    }}
Sample output
$ curl -i http://localhost:8080/lab/greeting
HTTP/1.1 404
Content-Type: application/json
Content-Language: en-IN
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:44:14 GMT

{"timestamp":"2026-10-16T04:44:14.004Z","status":404,"error":"Not Found","path":"/lab/greeting"}

What this code does

  • The method runs, but a plain @Controller treats "Welcome to ShopLite" as the name of a view (a page template). The project has no such page, so the client gets 404, not the text.
  • This 404 is confusing because the mapping is correct. When a @Controller method "returns 404", check for a missing @ResponseBody first.
  • The fix: change @Controller to @RestController. Then the response is 200 with the text as its body.

Without @ResponseBody, a plain @Controller treats a returned String as the name of a view, an HTML page template to show. That is how server-side web pages work. A REST API sends data, not pages, so every ShopLite controller uses @RestController.

The examples in this module run in a practice project, rest-lab. Create it on start.spring.io like shoplite-api (Maven, Java 17, Spring Boot 4.1), with the Spring Web MVC dependency, artifact rest-lab and package name com.shoplite.lab. Start it with mvnw spring-boot:run (Windows: mvnw.cmd spring-boot:run); it listens on port 8080.

A method annotated @GetMapping("/lab/hello") answers GET requests for that path. The next lesson covers every mapping annotation.

A base path with class-level @RequestMapping

@RequestMapping on a class sets a base path shared by every method of the controller. A method mapping is added after it: the class path /api/v1/categories plus @GetMapping with no path answers GET /api/v1/categories.

Every category endpoint starts with the same URL. Writing that URL once on the class keeps all the methods consistent. The example gives CategoryController its base path and one list method.

Example 3 · Category.java, CategoryController.java

Runs in: the rest-lab practice project (Spring Boot 4.1)

Category.javaJava
// src/main/java/com/shoplite/lab/Category.javapackage com.shoplite.lab;
public record Category(long id, String name, Long parentId) {}
// src/main/java/com/shoplite/lab/CategoryController.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/api/v1/categories")public class CategoryController {
    // Fixed data for now: the ShopLite seed categories    private static final List<Category> CATEGORIES = List.of(            new Category(1, "Electronics", null),            new Category(2, "Mobiles", 1L),            new Category(3, "Laptops", 1L),            new Category(4, "Accessories", 1L),            new Category(5, "Books", null),            new Category(6, "Fashion", null),            new Category(7, "Home & Kitchen", null));
    @GetMapping    public List<Category> list() {        return CATEGORIES;    }}
Output
$ curl http://localhost:8080/api/v1/categories
[{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Mobiles","parentId":1},{"id":3,"name":"Laptops","parentId":1},{"id":4,"name":"Accessories","parentId":1},{"id":5,"name":"Books","parentId":null},{"id":6,"name":"Fashion","parentId":null},{"id":7,"name":"Home & Kitchen","parentId":null}]

What this code does

  • The class-level @RequestMapping("/api/v1/categories") gives the base path; @GetMapping with no path of its own maps list() to exactly that URL.
  • The method returns a List<Category>, and the client receives a JSON array with one object per record. parentId is a Long, so a top-level category shows "parentId":null, as the ShopLite contract asks.
  • The list is fixed in the controller for now. Data belongs in a service, which the next lesson adds.

Without a base path, every method repeats /api/v1/categories/.... One typo in one method then puts that endpoint at a different URL, and nobody notices until a client gets a 404. With the base path, the resource's URL is written once, at the top, where a reader sees it first.

ShopLite uses one controller per resource, each with its own base path from the API contract: /api/v1/categories, /api/v1/products, /api/v1/customers, /api/v1/orders. Paths are case-sensitive and start with /.

Returning objects: Jackson writes the JSON

Jackson is the JSON library that Spring Boot includes with Spring Web MVC. It turns a returned object into JSON text and sets Content-Type: application/json. This step is called serialization (object to text).

The category list is a Java object, but the app needs JSON text. Spring hands each returned object to Jackson, which writes the JSON. The example returns a record and a list of records.

The journey of one request. The client sends GET /api/v1/categories. Tomcat, the server inside Spring Boot, receives it and Spring MVC picks the controller method whose method and path match. The method returns a Java object.

Example 4 · StoreInfo.java, StoreController.java

Runs in: the rest-lab practice project (Spring Boot 4.1)

StoreInfo.javaJava
// src/main/java/com/shoplite/lab/StoreInfo.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;
public record StoreInfo(String name, String city, boolean openNow, int deliveryDays,                        BigDecimal deliveryFee, List<String> paymentModes, String helpline) {}
// src/main/java/com/shoplite/lab/StoreController.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/lab/store")public class StoreController {
    @GetMapping    public StoreInfo info() {        return new StoreInfo("ShopLite", "Bengaluru", true, 3,                new BigDecimal("40.00"), List.of("UPI", "Card", "Cash on delivery"), null);    }
    @GetMapping("/payment-modes")    public List<String> paymentModes() {        return List.of("UPI", "Card", "Cash on delivery");    }}
Output
$ curl http://localhost:8080/lab/store
{"name":"ShopLite","city":"Bengaluru","openNow":true,"deliveryDays":3,"deliveryFee":40.00,"paymentModes":["UPI","Card","Cash on delivery"],"helpline":null}
$ curl http://localhost:8080/lab/store/payment-modes
["UPI","Card","Cash on delivery"]

What this code does

  • Jackson maps each record component to a field of the same name and type: boolean to true, int and BigDecimal to numbers, the List<String> to an array, and the null helpline to null.
  • BigDecimal("40.00") is written as 40.00, keeping both decimals. That is why ShopLite keeps money in BigDecimal.
  • The two methods share the base path /lab/store: @GetMapping answers /lab/store, and @GetMapping("/payment-modes") answers /lab/store/payment-modes.

For a record, each component becomes one JSON field with the same name. Jackson maps the types for you: String to a JSON string, int and BigDecimal to numbers, boolean to true/false, a List to an array, another record to a nested object, and null to null. Field order follows the record components.

A method that returns a String is the exception: the text is sent as it is, with Content-Type: text/plain. Spring Boot 4.1 uses Jackson 3, whose classes live in the tools.jackson packages; the annotations you may meet later (@JsonProperty) are still in com.fasterxml.jackson.annotation.

Calling the endpoint with curl

curl -i sends a request and prints the whole response: the status line, the headers, a blank line, then the body. Plain curl prints only the body, and curl -v also shows the request that curl sent.

To trust an endpoint, look at the whole response and not only the body. The example calls the category endpoint with curl -i and then with curl -v.

Example 5 · Reading a response with curl -i and curl -v

Terminal
curl -i http://localhost:8080/api/v1/categoriescurl -v http://localhost:8080/lab/hello
Sample output
$ curl -i http://localhost:8080/api/v1/categories
HTTP/1.1 200
Content-Type: application/json
Content-Length: 299
Date: Fri, 16 Oct 2026 04:44:15 GMT

[{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Mobiles","parentId":1},{"id":3,"name":"Laptops","parentId":1},{"id":4,"name":"Accessories","parentId":1},{"id":5,"name":"Books","parentId":null},{"id":6,"name":"Fashion","parentId":null},{"id":7,"name":"Home & Kitchen","parentId":null}]
$ curl -v http://localhost:8080/lab/hello
* Host localhost:8080 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
*   Trying [::1]:8080...
* Connected to localhost (::1) port 8080
> GET /lab/hello HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/8.8.0
> Accept: */*
>
* Request completely sent off
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 23
< Date: Fri, 16 Oct 2026 04:44:16 GMT
<
* Connection #0 to host localhost left intact
ShopLite lab is running

What this code does

  • -i shows status 200, Content-Type: application/json and the 299-byte body. Tomcat 11 sends the code without the reason words, so you see HTTP/1.1 200, not 200 OK.
  • -v adds the request (> lines) and the response headers (< lines). The hello endpoint returns a String, so its type is text/plain;charset=UTF-8, not JSON.
  • Your Date values and the curl version will differ. On Windows PowerShell, type curl.exe instead of curl.

Read a response from the top. The status line HTTP/1.1 200 says it worked. Tomcat 11, the server inside Spring Boot 4.1, sends only the number, without the words "OK" or "Not Found". Content-Type tells you the body's format and Content-Length its size in bytes.

On Windows PowerShell type curl.exe, because plain curl there runs a different command. Command Prompt, Git Bash and the macOS Terminal run the real curl as curl.

A path with no mapping: what the 404 looks like

404 Not Found is the status Spring Boot sends when no controller method matches the request path. The body is its default error JSON with timestamp, status, error and path. A browser shows the same error as a "Whitelabel Error Page".

A typo in a URL is the most common reason an endpoint seems to be missing. The example calls paths with no mapping and reads the answer.

Example 6 · Paths with no mapping

Terminal
curl -i http://localhost:8080/api/v1/categorycurl -i -H "Accept: text/html" http://localhost:8080/api/v1/categorycurl -i http://localhost:8080/api/v1/categories/curl -i http://localhost:8080/API/v1/categories
Sample output
$ curl -i http://localhost:8080/api/v1/category
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:44:17 GMT

{"timestamp":"2026-10-16T04:44:17.474Z","status":404,"error":"Not Found","path":"/api/v1/category"}
$ curl -i -H "Accept: text/html" http://localhost:8080/api/v1/category
HTTP/1.1 404
Content-Type: text/html;charset=UTF-8
Content-Language: en-IN
Content-Length: 275
Date: Fri, 16 Oct 2026 04:44:18 GMT

<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Fri Oct 16 10:14:18 IST 2026</div><div>There was an unexpected error (type=Not Found, status=404).</div></body></html>
$ curl -i http://localhost:8080/api/v1/categories/
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:44:19 GMT

{"timestamp":"2026-10-16T04:44:19.824Z","status":404,"error":"Not Found","path":"/api/v1/categories/"}
$ curl -i http://localhost:8080/API/v1/categories
HTTP/1.1 404
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 04:44:20 GMT

{"timestamp":"2026-10-16T04:44:20.259Z","status":404,"error":"Not Found","path":"/API/v1/categories"}

What this code does

  • A typo (category), a trailing slash and capital letters each give 404 with Spring Boot's default error JSON. The path field shows exactly what the server received.
  • With Accept: text/html, as a browser sends, the same 404 comes back as the HTML Whitelabel Error Page.
  • The body has no message saying why. Spring Boot hides details by default; the Exception handling module gives ShopLite clear Problem Details errors.

The usual causes are small: a typo (/api/v1/category instead of /categories), a trailing slash (/api/v1/categories/ does not match, since Spring Framework 6), wrong capital letters, or a controller class outside the main class's package, so it is never scanned. Read the path field in the error first: it shows exactly what the server received.

The ShopLite API contract wants every error as a Problem Details body (application/problem+json). The Exception handling module replaces this default error JSON with that format in one place.

Predict the output

Predict the status

Spring Boot runs this controller. What does each request get back?

Round 1 of 2

GET /api/v1/categories/ (a slash at the end)

@RestController
@RequestMapping("/api/v1/categories")
public class CategoryController {
@GetMapping
public List<Category> list() {
return CATEGORIES;
}
}
Interview angle: "you get a 404 for an endpoint you just wrote" usually expects these checks: the URL, the HTTP method, and whether the controller is in a scanned package.

Next step

Check your understanding

11 quick questions