오늘은 웹 개발의 핵심 기술 중 하나인 RESTful API에 대해 알아보려고 합니다. RESTful API는 오늘날 웹 애플리케이션의 통신 방식을 주도하는 중요한 개념이므로, 개념부터 설계 원칙까지 함께 정리해보겠습니다.
REST(Representational State Transfer)는 로이 필딩(Roy Fielding)이 2000년에 제안한 웹 아키텍처 스타일입니다. REST는 HTTP 프로토콜을 기반으로 하며, 자원(Resource)을 기반으로 웹 서비스 간에 데이터를 교환하는 방식입니다. 이를 구현한 API를 RESTful API라고 부릅니다.
RESTful API는 다음과 같은 개념을 따릅니다.
자원(Resource)
/api/users, /api/orders표현(Representation)
메서드(Method)
상태 전이(State Transfer)
RESTful API를 설계할 때는 다음의 원칙들을 따르는 것이 중요합니다.
클라이언트-서버(Client-Server) 구조
무상태(Stateless)
캐시 가능(Cacheable)
계층화 시스템(Layered System)
통일된 인터페이스(Uniform Interface)
RESTful API에서 주로 사용하는 HTTP 메서드와 그 의미는 다음과 같습니다.
| HTTP 메서드 | 의미 | 설명 |
|---|---|---|
| GET | 조회 | 서버에서 자원 조회 |
| POST | 생성 | 서버에 새로운 자원 생성 |
| PUT | 전체 수정 | 서버에 자원의 모든 정보를 업데이트 |
| PATCH | 부분 수정 | 서버에 자원의 일부 정보를 업데이트 |
| DELETE | 삭제 | 서버에서 자원 삭제 |
RESTful API의 URI 설계는 매우 중요합니다. 올바른 설계를 위해 다음의 규칙을 따릅니다.
자원은 복수형 사용
GET /api/user ❌ -> GET /api/users ⭕GET /api/orders/1 (단수도 포함)명확하고 일관된 구조 사용
/api/users/{userId}/orders/{orderId}행위는 URI가 아닌 메서드로 표현
GET /api/users/{userId}/activate ❌ -> POST /api/users/{userId}/activation ⭕URI는 소문자 사용
/api/Users ❌ -> /api/users ⭕UserController를 통해 간단한 RESTful API를 만들어 봅시다.
package com.moonBam.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
private Map<Long, User> users = new HashMap<>();
private long nextId = 1;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(new ArrayList<>(users.values()));
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = users.get(id);
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
return ResponseEntity.ok(user);
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User newUser) {
newUser.setId(nextId++);
users.put(newUser.getId(), newUser);
return ResponseEntity.status(HttpStatus.CREATED).body(newUser);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
if (!users.containsKey(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
updatedUser.setId(id);
users.put(id, updatedUser);
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
if (!users.containsKey(id)) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
users.remove(id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}
class User {
private Long id;
private String name;
private String email;
// getter 및 setter 생략
}
RESTful API는 웹 애플리케이션 간의 통신을 간소화하고 일관성 있는 인터페이스를 제공하는 데 중요한 역할을 합니다. 이번 포스팅에서는 RESTful API의 개념과 설계 원칙, 그리고 실제 구현을 함께 살펴보았습니다.
참고 자료