-
API 정리[공부] 프로그래밍/Spring・Spring Boot (JAVA) 2025. 4. 13. 16:22
API
API (Application Programming Interface)는 프로그램과 프로그램 사이의 소통 방법을 뜻한다. 쉽게 말해서 API는 두 시스템이 서로 대화할 수 있게 해주는 "메뉴판" 또는 "전화기" 같은 것이다.
🍽️ 예시
레스토랑에서 음식을 주문한다고 했을때
고객: 원하는 메뉴가 있어요.
웨이터(API): 주방과 당신을 연결해주는 사람
주방(서버): 실제로 요리를 만드는 곳
=> 당신은 웨이터(API)에게 메뉴를 주문하고 웨이터(API)는 주방(서버)에 그것을 전달해 요리(데이터)를 가져다준다.
🛠️ 날씨 API
어떤 앱에서 "서울의 현재 날씨"를 알고 싶다고 할 때, 앱은 날씨 회사의 API에 이렇게 요청을 보낸다.
・요청 (Request)
GET https://api.weather.com/seoul/today
・응답 (Response)
{ "city": "Seoul", "temperature": "15°C", "weather": "맑음" }
🌐 REST와 SOAP이란?
서버와 클라이언트가 데이터를 주고받는 규칙(방식)이다.▷ REST (Representational State Transfer) :
간단하고 가볍고 웹에 딱 맞는 API 방식✨ 특징:
- HTTP(웹에서 쓰는 프로토콜)를 기반으로 함
- URL로 자원을 표현하고 (/users/1, /products/3)
- GET, POST, PUT, DELETE 같은 HTTP 메서드로 동작
- 보통 JSON 형식으로 데이터를 주고받음
- 모바일 앱, 웹 프론트엔드에서 가장 많이 사용함
▷ SOAP (Simple Object Access Protocol) :
엄격하고 무겁지만, 신뢰성과 보안이 중요한 환경에 적합한 방식✨ 특징:
- XML 형식만 사용
- 메시지 형식이 복잡하고 정해진 규칙이 많음
- HTTP뿐만 아니라 SMTP(이메일) 같은 다양한 프로토콜도 사용 가능
- 주로 기업 내부 시스템, 금융, 보험 등에서 사용
프로젝트 예제
① Controller
package test.test01.controller; import ... @RestController public class Test01RestController { private final Test01Service test01Service; public Test01RestController(Test01Service test01Service) { this.test01Service = test01Service; } @GetMapping(Test01Constant.REQUEST_KEY_Test01) public Test01ResponseDto search(@RequestParam Map<String, String> params) throws Exception { // 요청 파라미터를 Test01ConditionDto 객체로 변환 Test01ConditionDto conditionDto = ConvertUtils.doConvertToBean(params, Test01ConditionDto.class, null); // 서비스 계층 호출하여 비즈니스로직 수행 Test01ServiceDto serviceList = test01Service.search(conditionDto); // 결과 데이터를 응답 DTO로 변환 (resultList → serviceList 변수명 수정 필요) Test01ResponseDto response = ConvertUtils.convertToBean(resultList, Test01ResponseDto.class, null); // 응답에 성공 플래그 설정 response.setResultFlag(CommonConstant.SUCCESS); return response; } }
② Service
package test.test01.service; import ... public interface Test01Service { Test01ServiceDto search(Test01ConditionDto conditionDto) throws Exception; }
package test.test01.service.impl; import ... @Service public class Test01ServiceImpl implements Test01Service { private final TestDbRepository testDbRepository; public Test01ServiceImpl(TestDbRepository testDbRepository) { this.testDbRepository = testDbRepository; } @Override public Test01ServiceDto search(Test01ConditionDto conditionDto) throws Exception { // 입력된 조건 DTO를 DB 검색용 DTO로 변환 TestDbSearchDto testDbSearchDto = ConvertUtils.convertToBean(conditionDto, TestDbSearchDto.class, null); // DB 조회 수행 - 검색 결과를 DTO 리스트로 받음 List<TestDbResultDto> testDbResultDto = testDbRepository.select01(testDbSearchDto); // DB 결과 DTO 리스트를 비즈니스 로직용 DTO 리스트로 변환 List<TestDbDto> resultList = ConvertUtils.convertList(testDbResultDto, TestDbDto.class); // 응답용 DTO에 변환된 리스트를 세팅 Test01ServiceDto resultDto = new Test01ServiceDto(); resultDto.setResultList(resultList); return resultDto; } }
③ DTO
package test.test01.dto; import ... @Data @EqualsAndHashCode(callSuper = false) public class Test01ServiceDto extends ResponseBaseDto implements Serializable { private static final long serialVersionUID = 1L; private List<TestDbDto> resultList; }
🔍 @EqualsAndHashCode(callSuper = false)
equals()랑 hashCode()라는 함수는 객체끼리 같은지 비교할 때 사용하는 함수이다. 롬복(Lombok)이라는 라이브러리가 대신 만들어주는 기능이다. @EqualsAndHashCode를 쓰면 자동으로 equals()랑 hashCode()를 만들어준다.
🧱 그런데 callSuper = false는?
callSuper = false는 '부모 클래스(상속받은 클래스)의 내용은 비교하지 마' 라는 뜻이다.
이렇게 되어 있으면?class 부모 { String name; } @EqualsAndHashCode(callSuper = false) class 자식 extends 부모 { int age; }
equals()랑 hashCode()를 만들 때 name은 무시하고, age만 보고 비교한다.
🤔 그럼 언제?
내가 만든 클래스만 비교하면 될 때 callSuper = false를 사용한다.
부모 클래스 속성도 같이 비교하고 싶으면 callSuper = true로 하면 된다.
④ Repository
package test.test01.repository; import ... @Mapper public interface TestDbRepository { List<TestDbResultDto> select01(TestDbSearchDto conditionDto); }
2024.03.13 - [[공부] 프로그래밍/프로그래밍의 기초] - API
API
API API(응용 프로그램 프로그래밍 인터페이스)란 소프트웨어끼리 손쉽게 소통할 수 있도록 도와주는 도구입니다. 예를 들어 당신이 레스토랑에 있다고 상상해보세요.당신은 손님이고 음식을 주
woodisco.tistory.com
2024.04.02 - [[공부] 프로그래밍/Spring Boot (JAVA)] - HTTP DELETE 처리
HTTP DELETE 처리
HTTP DELETE 처리 private Map delete(String _id, IF_Token _if_Token) throws Exception { Map returnMapinsert = new HashMap(); try { HttpURLConnection httpURLConnection = null; try { //connection URL url = new URL(config.get base URL().concat(Const_Url.toSt
woodisco.tistory.com
'[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글
Batch 정리 (0) 2025.04.12 Logback 구현 - 2 (0) 2024.05.23 Logback 구현 - 1 (0) 2024.05.22 Feign Client 구현 - 4 (0) 2024.05.22 Feign Client 구현 - 3 (0) 2024.05.22