Sub topic 11
Adding a First REST Endpoint
This chapter adds an HTTP endpoint to the generated Spring Boot project and explains how a request reaches your Java method. It then extends the endpoint to read input and return JSON, and tests it without starting a server.
Prerequisites
This chapter assumes you have:
- A project generated with Spring Initializr that includes the Spring Web dependency (
spring-boot-starter-web). - A main class annotated with
@SpringBootApplication, as covered earlier. - The ability to run the app with
./mvnw spring-boot:run. - Basic knowledge of HTTP methods, paths, and status codes.
What an endpoint is in Spring MVC
An endpoint is a Java method that Spring calls when a request matches an HTTP method and a path. Spring Web MVC does the matching. It is the web framework that spring-boot-starter-web brings in, and it runs on the embedded server.
You declare an endpoint with annotations. A class marked @RestController is registered as a bean. Methods inside it marked @GetMapping, @PostMapping, and similar annotations become handlers for specific requests.
The minimal controller
Create HelloController.java in the same package as your main class:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}The annotations do the following:
@RestControllercombines@Controllerand@ResponseBody. The return value is written directly to the HTTP response body. It is not treated as the name of a view template.@GetMapping("/hello")mapsGET /helloto this method. It is shorthand for@RequestMapping(method = RequestMethod.GET, path = "/hello").- The method returns a
String, so the response has the content typetext/plain.
You did not register the controller anywhere. Component scanning found it, because @SpringBootApplication scans its own package and every sub-package.
How a request reaches your method
Spring MVC routes every request through one front controller, the DispatcherServlet. It asks the handler mapping which method matches the request. It calls that method, then passes the return value to a message converter that writes the response.
The message converter explains why the same annotations produce plain text for a String and JSON for an object. Spring chooses a converter based on the return type and the request's Accept header.
Running and calling it
Start the app and call the endpoint from a second terminal:
./mvnw spring-boot:run
curl -i http://localhost:8080/helloIf you set server.port=8081 in application.properties, use port 8081. The -i flag prints the status line and headers. You should see HTTP/1.1 200 and Content-Type: text/plain;charset=UTF-8, followed by the body.
Spring Boot does not reload code automatically unless DevTools is on the classpath. After you change a controller, stop the app and start it again.
Reading input and returning JSON
Real endpoints take input and return structured data. The next controller uses a path variable, a query parameter, and a Java record as the response.
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class GreetingController {
public record Greeting(String name, String message) {}
@GetMapping("/greetings/{name}")
public Greeting greet(@PathVariable String name,
@RequestParam(defaultValue = "Hello") String salutation) {
return new Greeting(name, salutation + ", " + name + "!");
}
}Request it with and without the query parameter:
curl http://localhost:8080/api/greetings/Ada
curl "http://localhost:8080/api/greetings/Ada?salutation=Welcome"The first call returns {"name":"Ada","message":"Hello, Ada!"}. The second returns {"name":"Ada","message":"Welcome, Ada!"}.
Here is what each part does:
@RequestMapping("/api")on the class sets a path prefix for every method in it.{name}in the path is a template variable.@PathVariablebinds it to thenameparameter.@RequestParamreads?salutation=...from the query string. WithoutdefaultValue, a missing parameter returns 400 Bad Request, becauserequiredistrueby default.- The record is converted to JSON by Jackson.
spring-boot-starter-webincludes Jackson, and Boot registers it automatically through auto-configuration.
Choosing the annotation for the HTTP method
Each HTTP method has a matching shortcut annotation.
| Annotation | HTTP method | Typical use |
|---|---|---|
| `@GetMapping` | GET | Read a resource. Must not change state. |
| `@PostMapping` | POST | Create a resource or run an action. |
| `@PutMapping` | PUT | Replace a resource. |
| `@PatchMapping` | PATCH | Partially update a resource. |
| `@DeleteMapping` | DELETE | Remove a resource. |
For POST and PUT, you read the request body with @RequestBody. Jackson then converts the JSON into a Java object.
Controlling the status code
A handler that returns a value normally gives status 200. To return something else, return a ResponseEntity, which carries the status, headers, and body together:
package com.example.demo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class StatusController {
@GetMapping("/items/{id}")
public ResponseEntity<String> item(@PathVariable int id) {
if (id > 100) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok("Item " + id);
}
}Calling /items/5 returns 200 with Item 5. Calling /items/500 returns 404 with an empty body. If id is not a number, as in /items/abc, Spring rejects the request with 400 before your method runs.
Testing the endpoint without a server
spring-boot-starter-test is already in the build file with test scope. It includes JUnit 5 and Spring's MockMvc. A @WebMvcTest slice test loads only the web layer, so it starts faster than a full application test and does not open a port.
package com.example.demo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(HelloController.class)
class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void helloReturnsGreeting() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, Spring Boot!"));
}
}Run it with ./mvnw test. Naming HelloController.class in the annotation limits the slice to that controller, so other controllers are not loaded.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 404 on every request, and the controller class exists | The controller is outside the main class's package tree, or `@RestController` is missing | Move it under the main package and check the annotation |
| 404 only for one path | The path in the mapping differs from the request, including the class-level prefix | Combine the `@RequestMapping` prefix and the method path, then compare |
| Browser shows a "Whitelabel Error Page" | No handler matched, so Boot's default error page was served | Check the path and HTTP method |
| 405 Method Not Allowed | The path exists, but not for this HTTP method, for example POST to a `@GetMapping` | Use the right method or add a mapping for it |
| 400 Bad Request on a valid-looking URL | A required `@RequestParam` is missing, or a value has the wrong type | Add `defaultValue` or `required = false`, or fix the request |
| Port 8080 already in use at startup | Another process holds the port | Stop it, or set `server.port` |
| Text appears as a view name or you get a template error | You used `@Controller` without `@ResponseBody` | Use `@RestController` |
Exercise
You add @GetMapping("/status") to a new class StatusController annotated with @RestController, placed in the package com.example.web. The main class is com.example.demo.DemoApplication. The app starts without errors, but curl localhost:8080/status returns 404. What is the cause, and what are two ways to fix it?
Show answer
Component scanning from @SpringBootApplication covers only com.example.demo and its sub-packages. com.example.web is a sibling package, so the controller is never registered as a bean. Fix it by moving the class into com.example.demo or a sub-package, for example com.example.demo.web. Alternatively, widen the scan with @SpringBootApplication(scanBasePackages = "com.example"). Moving the class is the usual choice.
Exercise
Write a @GetMapping method for GET /api/square/{n} that returns n * n as JSON in the form {"n":4,"square":16}. Which Spring component converts the returned object to JSON, and what status does /api/square/abc produce?
Show answer
Define public record Square(int n, int square) {} and the method @GetMapping("/api/square/{n}") public Square square(@PathVariable int n) { return new Square(n, n * n); } inside a @RestController. Jackson, through Spring's JSON message converter, writes the record as JSON. /api/square/abc cannot be converted to int, so Spring rejects it with 400 Bad Request before the method is called.