스프링부트3 블로그 만들기 - 블로그 글 목록 조회를 위한 API 구현하기
본문 바로가기

웹/Spring

스프링부트3 블로그 만들기 - 블로그 글 목록 조회를 위한 API 구현하기

728x90
반응형

안녕하세요 놀이방사장입니다.

 

이번 포스팅에서는 스프링부트 블로그 만들기

글 목록 조회 API 구현입니다.

 

package me.joyeonggyu.springbootdeveloper.service;

import lombok.RequiredArgsConstructor;
import me.joyeonggyu.springbootdeveloper.domain.Article;
import me.joyeonggyu.springbootdeveloper.dto.AddArticleRequest;
import me.joyeonggyu.springbootdeveloper.repository.BlogRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@RequiredArgsConstructor
@Service

public class BlogService {
    private final BlogRepository blogRepository;

    public Article save(AddArticleRequest request){
        return blogRepository.save(request.toEntity());
    }

    public List<Article> findAll(){
        return blogRepository.findAll();
    }
}

 

JPA 지원 메서드인 findAll()을 호출해 article 테이블에 저장되어 있는 모든 데이터를 조회한다.

 

컨트롤러 메서드 코드 작성하기

 

/api/articles GET요청이 오면 글 목록을 조회할 findAllArticles() 메서드를 작성

이 메서드는 전체 글 목록을 조회하고 응답하는 역활을 한다.

 

package me.joyeonggyu.springbootdeveloper.dto;

import lombok.Getter;
import me.joyeonggyu.springbootdeveloper.domain.Article;

@Getter
public class ArticleResponse {
    private final String title;
    private final String content;

    public ArticleResponse(Article article){
        this.title = article.getTitle();
        this.content = article.getContent(); 
    }
}

 

 

dto 디렉터리에 ArticleResponse.java파일을 생성

글을 제목과 내용구성으로 해당 필드를 가지는 클래스를 만든 다음, 엔티티를 인수로 받는 생성자를 추가

 

controller 디렉터리에 있는 BlogApiController.java파일을 열어 전체 글을 조회한 뒤 반환하는 findAllArticles() 메서드를 추가 합니다.

package me.joyeonggyu.springbootdeveloper.cotroller;

import lombok.RequiredArgsConstructor;
import me.joyeonggyu.springbootdeveloper.domain.Article;
import me.joyeonggyu.springbootdeveloper.dto.AddArticleRequest;
import me.joyeonggyu.springbootdeveloper.dto.ArticleResponse;
import me.joyeonggyu.springbootdeveloper.service.BlogService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequiredArgsConstructor
@RestController
public class BlogApiController {
    private final BlogService blogService;

    @PostMapping("/api/articles")
    public ResponseEntity<Article> addArticle(@RequestBody AddArticleRequest
                                                        request){
        Article saveArticle = blogService.save(request);

        return ResponseEntity.status(HttpStatus.CREATED)
                .body(saveArticle);
    }

    @GetMapping("/api/articles")
    public ResponseEntity<List<ArticleResponse>> findAllArticles() {
        List<ArticleResponse> articles = blogService.findAll()
                .stream()
                .map(ArticleResponse::new)
                .toList();

        return ResponseEntity.ok()
                .body(articles);
    }
}

/api/articles GET 요청이 오면 글 전체를 조회하는 findAll() 메서드를 호출한 다음 응답용 객체인 ArticleResponse로 파싱해 body에 담아 

 

 

 

이상으로 스프링부트3 블로그 만들기 - 블로그 글 목록 조회를 위한 API 구현하기 포스팅을 마치겠습니다.

반응형