Book Study/스프링 부트 핵심 가이드

05. API를 작성하는 다양한 방법 (1)

정진킴 2023. 10. 23. 09:00

5.1 프로젝트 설정

5.2 GET API 만들기

  • 서버로 부터 데이터를 가져올 때 사용하는 API 이다.

5.2.1 @RequestMapping 으로 구현하기

  • RequestMapping은 컨트롤러 Group Uri 로 사용하는 것을 추천한다.
  • 스프링 4.3 버전 이후로는 새로 나온 어노테이션을 사용하다 보니 RequestMapping 을 잘 사용하지 않는다.
    • @GetMapping
    • @PostMapping
    • @PutMapping
    • @DeleteMapping

5.2.2 매개변수가 없는 GET 메서드 구현하기

  • 소스
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class GetController {
	@GetMapping("/get")
	public String hello() {
		return "Success Get Method";
	}
}
  • 결과

5.2.3 @PathVariable을 활용한 GET 메서드 구현하기

  • 소스
    • @GetMapping 어노테이션에 지정한 변수명과 매개변수명을 동일하게 맞추기 어렵다면 아래와 같이 수정도 가능하다.
      • @PathVariable([변수명]) String [다른변수명] - @PathVariable("variable") String var
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class GetController {
	@GetMapping("/get/{variable}")
	public String getVariable(@PathVariable String variable) {
		return "Success Get Method Variable " + variable;
	}
}
  • 결과

5.2.4 @RequestParam 을 활용한 GET 메서드 구현

  • 소스
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class GetController {
	@GetMapping("/get-query-param")
	public String getQueryParam(
		@RequestParam String name,
		@RequestParam String email,
		@RequestParam String organization
	) {
		return "Success Get Query Param: " + name + "," + email + "," + organization;
	}
 }
  • 결과

  • 쿼리스트링이 어떤 값인지 모르는 경우 소스
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class GetController {
	@GetMapping("/get-any-query-param")
	public String getAnyQueryParam(
		@RequestParam Map<String, String> param
	) {
		StringBuilder sb = new StringBuilder();
		
		param.entrySet().forEach(map -> {
			sb.append(map.getKey() + ":" + map.getValue() + "\n");
		});
		
		return sb.toString();
	}
  • 결과

5.2.5 DTO 객체를 활용한 GET 메서드 구현

  • DTO 란 Data Transfer Object의 약자로, 다른 레이어 간의 데이터 교환에 활용된다. 간략하게 정리하면 각 클래스및 인터페이스를 호출하면서 전달되는 매개변수로 사용되는 데이터 객체
  • DTO 는 데이터를 교환하는 용도로만 사용되기 때문에 별도의 로직이 포함되지 않는다.
  • DTO 객체를 이용한 Get 메서드 구현 예시
/**
 * dto 예시
 */

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class MemberDto {
	private String name;
	private String email;
	private String organization;
}
/**
 * get method
 */

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zerobase.account.dto.MemberDto;

@RestController
@RequestMapping("/api/v1")
public class GetController {
	@GetMapping("/get-dto-query-param")
	public String getDtoQueryParam(MemberDto memberDto) {
		return memberDto.toString();
	}
 }

GET 요청 시 응답 데이터