반응형

전자정부프레임워크를 활용하여 RESTful API를 설계하고 구현하는 방법을 알아보겠습니다. RESTful API는 웹 애플리케이션의 데이터를 다양한 클라이언트(모바일, 웹 등)와 통신하기 위해 많이 사용됩니다. 오늘은 CRUD(Create, Read, Update, Delete) 기능을 중심으로 API를 구축하는 방법을 다룹니다.


1. RESTful API란?

REST(Representational State Transfer)는 HTTP 프로토콜을 기반으로 자원을 정의하고 상태를 전송하는 아키텍처 스타일입니다. RESTful API는 다음과 같은 특성을 가집니다.

  1. 자원(Resource) 중심: URI를 통해 자원을 식별합니다.
  2. HTTP 메서드 활용: GET, POST, PUT, DELETE 메서드로 작업을 수행합니다.
  3. 표준화된 데이터 포맷: JSON 또는 XML 형식으로 데이터를 주고받습니다.

2. RESTful API 설계

2-1. URI 설계 원칙

  • 자원은 명사를 사용하여 표현합니다.
    예: /users, /products, /orders
  • 복수형을 권장합니다.
    예: /users (O), /user (X)

2-2. HTTP 메서드 매핑

HTTP 메서드 동작 설명

GET Read 자원 조회
POST Create 자원 생성
PUT Update 자원 수정(전체)
PATCH Update 자원 수정(부분)
DELETE Delete 자원 삭제

3. API 구현 예제

3-1. 의존성 추가

pom.xml에 다음 의존성을 추가합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

3-2. Entity 클래스 정의

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

3-3. Repository 정의

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

3-4. REST 컨트롤러 작성

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    // 모든 사용자 조회
    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 사용자 생성
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    // 특정 사용자 조회
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }

    // 사용자 수정
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            user.setName(userDetails.getName());
            user.setEmail(userDetails.getEmail());
            return userRepository.save(user);
        }
        return null;
    }

    // 사용자 삭제
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

4. API 테스트

4-1. Postman 사용

  1. GET 요청: http://localhost:8080/users
    • 모든 사용자 목록 조회
  2. POST 요청:
    • URL: http://localhost:8080/users
    • Body(JSON):
      {
          "name": "John Doe",
          "email": "john.doe@example.com"
      }
      
  3. PUT 요청:
    • URL: http://localhost:8080/users/1
    • Body(JSON):
      {
          "name": "Jane Doe",
          "email": "jane.doe@example.com"
      }
      
  4. DELETE 요청: http://localhost:8080/users/1

4-2. H2 콘솔에서 데이터 확인

  • H2 데이터베이스 URL: http://localhost:8080/h2-console
  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa, Password: (비워둠)

5. 마무리

오늘은 전자정부프레임워크를 사용해 RESTful API를 설계하고 구현하는 방법을 알아보았습니다. RESTful API는 현대적인 애플리케이션 개발에서 필수적인 요소입니다. 다음 단계에서는 보안 적용과 API 문서화 방법을 다룰 예정입니다.

반응형

+ Recent posts