-
스프링 가이드 - 간단한 RESTful API 만들어보기개발 나누고 더하기/자바, 스프링 2024. 2. 13. 11:38
들어가며
토비의 스프링 유튜브 채널(https://www.youtube.com/watch?v=wlOR5ehWSjE&list=PLv-xDnFD-nnnZUzISvE6a8JnKZme-tRGU&index=2)에서 스프링 가이드를 따라하며 15분 만에 API만드는 예제가 있어 나도 따라해보았다.
다른 목적도 하나 있는데, 부하 테스트용 샘플 API가 필요했다. 새로 입사한 회사에서 백엔드팀 전체 부하테스트를 했었다. 환경 설정에 힘들어하는 주니어들도 있고 일관된 테스트 환경과 지표 분석을 위해 애플리케이션과 그라파나를 도커로 구성하는게 좋을 것 같았다. 일단 집에서 도커 테스트 환경을 만들고 회사 프로젝트에 적용할 계획이다.
준비물
- IDE와 JDK - 여기선 IntelliJ Community Edtion과 자바 17 사용
- 스프링 가이드 링크 - https://spring.io/guides/gs/rest-service
따라하기
API 명세
METHOD는 GET path는 greeting이다.
요청하면 고유 id와 함께 content 필드에 "Hello, World!"가 출력되어 나온다.
선택 파라미터로 name을 받을 수 있으며, name이 들어올 경우 World를 들어온 name으로 대치하여 출력한다.
프로젝트 초기화
예제용 Git 파일로 시작해도 되고, 스프링 이니셜라이저에서 직접 만들어도 된다.
스프링 초기 설정부터 따라해보는게 목적이니까 이니셜라이저를 이용하자.
빌드 도구와 언어는 각자 편한 걸로 고르고, 가이드대로 Dependencies에서 Srping Web만 골라서 Generate 버튼을 누르면 된다.
intelliJ에서 임포트하면 아래와 같이 프로젝트가 구성되어 있다.
Representation Class(표현 계층에서의 응답 클래스) 만들기
가이드대로 restservice 패키지에 Greeting.java 파일을 record로 만들어보자.
간단하다.
컨트롤러 만들기
아래 가이드대로 컨트롤러도 만들어보자. AtomicLong으로 id를 채번해서 응답하고, @RequestParam으로 받은 name을 Greeting의 content에 넣어주는 코드이다. name의 defaultValue가 World라 name이 전달되지 않으면 자동으로 Hello World!가 출력된다.
그냥 똑같이 만들면 된다 ㅎㅎ
테스트하기
코드를 실행시켜보자. 개인적으로 언제 발생할지 모르는 에러에 대비해 Debug 모드로 켜는걸 선호한다.
name 파라미터 없이 실행하기
name 파라미터에 juhyun 넣고 실행하기
id 값도 증가하여 잘 나오고, name 파라미터에 따라 content 출력값도 다르게 잘 나온다.
마무리
가이드가 더할나위 없이 단순하여 초보자들도 접근하기 쉬울 것 같다. 회사에서 기술 문서나 가이드 문서 만들 때 이렇게 군더더기 없이 만들어야겠다는 생각이 들었다.
샘플 API를 만드는 1차 목적은 이루었으나, 이걸 이제 도커로 원하는 환경에서 누구나 구동시킬 수 있도록 구성해야 한다. 다음 글에서 따라해보자. 다행히 스프링에서 제공하는 가이드가 있다^^
'개발 나누고 더하기 > 자바, 스프링' 카테고리의 다른 글
모니터링 체계 구축 - Spring Actuator, Prometheus, Grafana (0) 2024.02.15 이펙티브 자바 : 제네릭과 배열 그리고 리스트 (0) 2023.07.06 이펙티브 자바 : toString (0) 2023.06.30 이펙티브 자바 - equals & hashcode (0) 2023.06.28 Set에 대하여 2 : 주요 구현체 (0) 2023.06.25