Spring MVC REST API Requests and JSON Responses
A REST API needs clear input locations and response formats. Building JSON by concatenating strings can break responses when input contains quotes or newlines. Return objects and let Spring message converters serialize them to keep the request and response boundaries clear.
Add these files to the base project from lab setup. The example targets Java 17 source and Spring Boot 3.5.16. Use a separate project from the other chapters.
Where inputs come from
Section titled “Where inputs come from”@RequestMapping defines a shared path, while @GetMapping and @PostMapping define the HTTP method and subpath. @RestController combines controller registration with response body serialization.
| Input | Annotation | Example |
|---|---|---|
| Query string | @RequestParam | /greeting?name=Lee |
| Path variable | @PathVariable | /items/1 |
| JSON body | @RequestBody | POST /echo |
| URL-encoded form | @RequestParam | POST /form |
| Request header | @RequestHeader | X-Client: sample |
| Request cookie | @CookieValue | tutorial-session=sample |
Complete controller
Section titled “Complete controller”package com.example.tutorial;
import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.http.ResponseCookie;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.CookieValue;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.RequestHeader;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;
@RestController@RequestMapping("/tutorial")public class TutorialController { public record Greeting(String message) {} public record TodoItem(int id, String title, String description) {} public record FormInput(String title, String description) {}
@GetMapping("/greeting") public Greeting greeting(@RequestParam("name") String name) { return new Greeting("Hello, " + name); }
@GetMapping("/items/{id}") public ResponseEntity<TodoItem> find(@PathVariable("id") int id) { return id == 1 ? ResponseEntity.ok(new TodoItem(1, "First item", "Example")) : ResponseEntity.notFound().build(); }27 collapsed lines
@PostMapping("/echo") public TodoItem echo(@RequestBody TodoItem item) { return item; }
@PostMapping(value = "/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public FormInput form(@RequestParam("title") String title, @RequestParam("description") String description) { return new FormInput(title, description); }
@GetMapping("/header") public ResponseEntity<Greeting> header( @RequestHeader(value = "X-Client", defaultValue = "guest") String client) { return ResponseEntity.ok().header("X-Reply", "tutorial") .body(new Greeting(client)); }
@GetMapping("/cookie") public ResponseEntity<Greeting> cookie( @CookieValue(value = "tutorial-session", defaultValue = "none") String session) { var cookie = ResponseCookie.from("tutorial-session", "sample") .httpOnly(true).secure(true).sameSite("Lax").path("/").build(); return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie.toString()) .body(new Greeting(session)); }}find() returns the sample object for ID 1 and 404 for other IDs. echo() returns its input without persisting it. The form endpoint accepts application/x-www-form-urlencoded.
JSON and status codes
Section titled “JSON and status codes”Converting a response object to JSON differs from Java object serialization. Implementing java.io.Serializable is not required. The record in this example exposes components that the JSON converter can read. A regular class needs accessors or fields compatible with the converter configuration.
Use ResponseEntity to specify status codes and headers. Spring MVC returns 400 for a missing required name parameter or a non-integer value in the integer path variable. A real service also needs business validation and a consistent error response contract.
Headers and cookies
Section titled “Headers and cookies”/header reads X-Client and adds the X-Reply response header. Logging every request header can expose credentials, so handle only the values you need.
/cookie reads a request cookie and sets a response cookie with HttpOnly, Secure, and SameSite=Lax. Its fixed sample value is not an authentication token. A Secure cookie assumes HTTPS, so the HTTP exercise below focuses on inspecting the Set-Cookie header.
Requests and expected responses
Section titled “Requests and expected responses”The first command starts the server. Keep it running and send the remaining requests from another terminal.
mvn spring-boot:runcurl -G --data-urlencode 'name=Lee' http://localhost:8080/tutorial/greetingcurl -i http://localhost:8080/tutorial/items/9curl -X POST http://localhost:8080/tutorial/echo \ -H 'Content-Type: application/json' \ -d '{"id":2,"title":"Second item","description":"Example"}'curl -X POST http://localhost:8080/tutorial/form \ --data-urlencode 'title=Say "hello"' --data-urlencode 'description=Example'The first request returns 200 with {"message":"Hello, Lee"}. The second returns 404, and the third returns the submitted JSON object. The final form request returns an object whose quotes are escaped according to JSON rules.
Regression tests
Section titled “Regression tests”package com.example.tutorial;
import org.junit.jupiter.api.Test;import org.springframework.http.MediaType;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
class TutorialControllerTest { private final MockMvc mvc = MockMvcBuilders .standaloneSetup(new TutorialController()).build();
@Test void serializesQuotesInFormValues() throws Exception { mvc.perform(post("/tutorial/form") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("title", "Say \"hello\"") .param("description", "line1\nline2")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.title").value("Say \"hello\"")) .andExpect(jsonPath("$.description").value("line1\nline2")); }
@Test void rejectsMissingRequiredQueryParameter() throws Exception { mvc.perform(get("/tutorial/greeting")).andExpect(status().isBadRequest()); }
@Test void returnsNotFoundForUnknownItem() throws Exception { mvc.perform(get("/tutorial/items/9")).andExpect(status().isNotFound()); }}mvn test -Dtest=TutorialControllerTestThe first test checks that form input containing quotes and newlines returns valid JSON. The remaining tests check missing input and an unknown item.