11일차 - HTTP와 REST 컨트롤러

2024. 8. 12. 12:30코딩 자율학습 스프링 부트3 자바 백엔드 개발 입문 스터디

REST API의 구현과정

  1. REST API 주소 설계
    • 조회 요청
      • /api/articles, /api/articles/{id}
    • 생성 요청
      • /api/articles
    • 수정 요청
      • /api/articles/{id}
    • 삭제 요청
      • /api/articles/{id}
  2. URL 요청을 받아 JSON 으로 반환하는 컨트롤러 만들기

REST API 구현하기

GET 구현하기

1. 모든 게시글 조회하기

  • /api/articles 주소로 오는 API 요청을 받는다.
  • 레포지토리에서 findAll() 를 통해 전체 데이터를 조회해서 반환한다.
@RestController 
public class ArticleApiController { 

    @Autowired 
    private ArticleRepository articleRepository; 

    @GetMapping("/api/articles") 
        public List<Article> index() { 
        return articleRepository.findAll(); 
    } 
}

 

2. 단일 게시글 조회하기

  • /api/articles/{id} 주소로 오는 API 요청을 받는다.
  • 레포지토리에서 findById(Long id) 를 통해 id 에 맞는 데이터를 조회해서 반환한다.
@GetMapping("/api/articles/{id}") 
public Article show(@PathVariable Long id) { 
    return articleRepository.findById(id).orElse(null); 	
}

POST 구현하기

  1. 게시글 작성
    • /api/articles 주소로 오는 API 요청을 받는다.
    • 요청한 데이터를 dto 로 받아와 엔티티로 변환한다.
      • 요청한 데이터는 JSON 형식이므로 dto 로 받을 때에는 @RequestBody 를 이용해 자바 코드로 받을 수 있다.
    • 엔티티를 DB에 저장한 후 반환한다.
@PostMapping("/api/articles") 
public Article create(@RequestBody ArticleForm dto) { 
    Article article = dto.toEntity(); 
    return articleRepository.save(article); 
}

PATCH 구현하기

1. 단일 데이터 전체 수정

  • /api/articles/{id} 주소로 오는 API 요청을 받는다.
  • 수정 요청한 데이터를 dto 로 받아와 엔티티로 변환한다.
  • id 로 데이터를 조회한다.
  • 잘못된 요청 설정
    • id 로 데이터를 조회했을때 데이터가 없거나, 요청 주소의 id 값과 수정 요청한 데이터의 id 값이 일치하지 않으면 잘못된 요청 (400) 코드를 반환한다.
  • 레포지토리에 수정 요청 데이터를 엔티티로 변환한 값을 저장하고, 요청 성공 (200) 코드와 함께 값을 JSON 형식으로 반환한다.
@PatchMapping("/api/articles/{id}") 
public ResponseEntity<Article> update(@PathVariable Long id, @RequestBody ArticleForm form) { 
    Article article = form.toEntity(); 
    Article target = articleRepository.findById(id).orElse(null); 
    
    if (target == null || id != article.getId()) { 
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); 
    } 
    
    Article updated = articleRepository.save(article); 
    return ResponseEntity.status(HttpStatus.OK).body(updated); 
}

 

2. 단일 데이터 일부 수정

  • title 을 제외한 content 의 값만 입력하여 요청을 보내면 title 값이 null 로 들어오게 된다.
  • article 은 요청 데이터를 엔티티로 변환한 데이터, target 은 id 로 DB 를 조회한 데이터로 기존 데이터에 요청 데이터를 붙여주면 일부 데이터만 수정이 가능하다.
  • Article의 patch(Article article) 메서드는 수정할 내용이 있는 경우에만 동작하여 각 내용을 갱신한다.
  • 최종적으로는 target 을 데이터에 저장한다.
@PatchMapping("/api/articles/{id}") 
public ResponseEntity<Article> update(@PathVariable Long id, @RequestBody ArticleForm form) { 
    Article article = form.toEntity(); 
    Article target = articleRepository.findById(id).orElse(null); 
    
    if (target == null || id != article.getId()) { 
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); 
    } 
    
    target.patch(article); 
    Article updated = articleRepository.save(target); 
    return ResponseEntity.status(HttpStatus.OK).body(updated); 
} 

// Article.java 
public void patch(Article article) { 
    if (article.title != null) { 
        this.title = article.title; 
    } 
    if (article.content != null) { 
        this.content = article.content; 
    } 
}

DELETE 구현하기

  1. 게시글 삭제
    • /api/articles/{id} 주소로 오는 API 요청을 받는다.
    • id 로 DB를 조회하여 null 인 경우 잘못된 요청 (400) 코드를 반환한다.
    • 데이터가 있는 경우 DB에서 삭제 한 후 요청 성공 (200) 코드를 반환한다. body(null)build() 는 결과가 같다. build() 는 HTTP 응답의 body가 없는 ResponseEntity 객체를 생성한다.
@DeleteMapping("/api/articles/{id}") 
public ResponseEntity<Article> delete(@PathVariable Long id) { 
    Article target = articleRepository.findById(id).orElse(null); 
    
    if (target == null) { 
    	return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); 
    } 
    
    articleRepository.delete(target); 
    
    return ResponseEntity.status(HttpStatus.OK).build(); 
}