콘텐츠로 이동

Spring MVC REST API의 요청과 JSON 응답

Interactive Diagram

새 탭 ↗

REST API는 입력을 받는 위치와 응답 형식을 명확히 정해야 한다. 문자열로 JSON을 직접 조립하면 따옴표나 줄바꿈이 들어간 입력에서 응답이 깨질 수 있다. 객체를 반환하고 Spring의 메시지 변환기에 직렬화를 맡기는 예제로 요청과 응답의 경계를 살펴본다.

실습 준비의 기본 프로젝트에 아래 파일을 추가한다. Java 17 소스 수준과 Spring Boot 3.5.16을 기준으로 하며, 다른 장의 예제와 별도 프로젝트로 진행한다.

@RequestMapping은 공통 경로를 정하고, @GetMapping과 @PostMapping은 HTTP 메서드와 세부 경로를 정한다. @RestController는 Controller 등록과 응답 본문 직렬화를 함께 적용한다.

입력Annotation예시
쿼리 문자열@RequestParam/greeting?name=Lee
경로 변수@PathVariable/items/1
JSON 본문@RequestBodyPOST /echo
URL 인코딩 폼@RequestParamPOST /form
요청 헤더@RequestHeaderX-Client: sample
요청 쿠키@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()는 ID가 1이면 예제 객체를 반환하고, 그 외에는 404를 반환한다. echo()는 입력을 그대로 응답하는 예제이며 저장 작업은 하지 않는다. 폼은 application/x-www-form-urlencoded 형식으로 받는다.

응답 객체를 JSON으로 바꾸는 것은 Java 객체 직렬화와 다르다. java.io.Serializable 구현은 필수 조건이 아니다. 예제의 record는 JSON 변환기가 읽을 수 있는 구성요소를 제공한다. 일반 클래스를 사용한다면 변환기 설정에 맞는 접근자나 필드 구성이 필요하다.

ResponseEntity로 상태 코드와 헤더를 명시한다. 필수 name 쿼리가 없거나 정수 경로에 문자열을 넣으면 Spring MVC가 400으로 처리한다. 실제 서비스에서는 업무 규칙 검증과 일관된 오류 응답 계약을 추가한다.

/header는 X-Client를 읽고 X-Reply 응답 헤더를 추가한다. 모든 요청 헤더를 통째로 로그에 남기면 인증 정보까지 기록할 수 있으므로 필요한 값만 다룬다.

/cookie는 요청 쿠키를 읽고 HttpOnly, Secure, SameSite=Lax 속성으로 응답 쿠키를 설정한다. 쿠키 값은 학습용 고정 문자열이며 인증 토큰이 아니다. Secure 쿠키는 HTTPS 사용을 전제로 하므로 아래 HTTP 실습에서는 Set-Cookie 헤더를 확인하는 데 집중한다.

첫 명령은 서버를 실행한다. 서버가 실행된 상태에서 다른 터미널로 나머지 요청을 보낸다.

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'

첫 요청은 200과 {"message":"Hello, Lee"}를 반환한다. 두 번째는 404, 세 번째는 보낸 JSON 객체를 반환한다. 마지막 폼 요청은 따옴표를 JSON 규칙에 맞게 이스케이프한 객체를 반환한다.

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

첫 테스트는 따옴표와 줄바꿈이 포함된 폼 입력이 유효한 JSON으로 돌아오는지 확인한다. 나머지 테스트는 입력 누락과 존재하지 않는 항목의 응답을 확인한다.