4단계
4단계 — REST API 설계
30 분
4단계 — REST API 설계
REST 는 자원(resource) 을 URL 로 표현하고 HTTP 동사로 동작을 구분하는 규칙이에요. 일관된 API 의 기본기.
자원 = URL, 동작 = HTTP 동사
| URL | GET | POST | PUT | DELETE |
|---|---|---|---|---|
/api/posts |
목록 조회 | 새로 생성 | 전체 갱신 X | X |
/api/posts/{id} |
단건 조회 | X | 전체 교체 | 삭제 |
/api/posts/{id}/comments |
댓글 목록 | 새 댓글 | X | X |
자원은 명사 복수형 (/posts, /users), 동사는 URL 이 아닌 HTTP 메서드로 표현해요. /getPost 같은 URL 은 RESTful 하지 않아요.
컨트롤러 한 장
@RestController
@RequestMapping("/api/posts")
@RequiredArgsConstructor
public class PostController {
private final PostService postService;
@GetMapping
public List<PostDto> list(@RequestParam(defaultValue = "20") int limit) {
return postService.findRecent(limit);
}
@GetMapping("/{id}")
public PostDto get(@PathVariable Long id) {
return postService.findById(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public PostDto create(@Valid @RequestBody PostCreateRequest request) {
return postService.create(request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
postService.delete(id);
}
}
@Valid + @RequestBody 조합이 입력 검증 (다음 단계 zod 같은 역할) 을 해 줘요.
응답 코드 5종 만 알면 됨
200 OK— 정상 조회·갱신201 Created— 새로 만들었음204 No Content— 삭제 성공 (응답 본문 없음)400 Bad Request— 입력 오류404 Not Found— 자원 없음
서버 에러 (500) 는 자동, 인증 오류 (401/403) 는 5단계에서.
DTO 와 Entity 분리
// 입력
public record PostCreateRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String body
) {}
// 출력
public record PostDto(Long id, String title, String body, Instant createdAt) {}
엔티티는 DB 모양, DTO 는 API 모양 — 둘은 분리해야 변경에 강해요.
직접 해 보기
PostService.findRecent(limit) 를 구현하고 (JpaRepository 의 findAll(PageRequest.of(0, limit, Sort.by("createdAt").descending()))), curl http://localhost:8080/api/posts 로 호출해 보세요.
더 깊이
- REST API 입문 노트
- OpenAPI Spec 노트 — 자동 문서화
- API Handler 패턴
다음 단계
5단계에서는 이 API 에 인증을 붙여 내 글만 수정할 수 있게 해요.