Skip to content

Spring MVC REST API Requests and JSON Responses

Interactive Diagram

새 탭 ↗

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.

@RequestMapping defines a shared path, while @GetMapping and @PostMapping define the HTTP method and subpath. @RestController combines controller registration with response body serialization.

InputAnnotationExample
Query string@RequestParam/greeting?name=Lee
Path variable@PathVariable/items/1
JSON body@RequestBodyPOST /echo
URL-encoded form@RequestParamPOST /form
Request header@RequestHeaderX-Client: sample
Request cookie@CookieValuetutorial-session=sample
src/main/java/com/example/tutorial/TutorialController.java
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.

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.

/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.

The first command starts the server. Keep it running and send the remaining requests from another terminal.

Terminal window
mvn spring-boot:run
Terminal window
curl -G --data-urlencode 'name=Lee' http://localhost:8080/tutorial/greeting
curl -i http://localhost:8080/tutorial/items/9
curl -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.

src/test/java/com/example/tutorial/TutorialControllerTest.java
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());
}
}
Terminal window
mvn test -Dtest=TutorialControllerTest

The first test checks that form input containing quotes and newlines returns valid JSON. The remaining tests check missing input and an unknown item.