API 작성 - GET

김민경·2022년 10월 31일
0
  • Controller 패키지 안에 Controller 클래스 생성 -> API 작성
    • @RestController
      : 해당 컨트롤러를 controller로 사용하겠다라고 선언
    • @RequestMapping(”/api/v1/get-api”)
      : 내부에 선언한 메서드의 URL 리소스 앞에 위의 값이 공통 값으로 추가 됨

GET API

  • 웹 애플리케이션 서버에서 값을 가져올 때 사용하는 API
    • @RequestMapping으로 구현하기
      • 별다른 설정 없이 선언하면 HTTP의 모든 요청을 받음
        → GET 형식의 요청만 받기 위해선 어노테이션에 별도 설정 필
        @RequestMapping(value = “/hello”, method = RequestMethod.GET)

      • 스프링 4.3 버전 이후로는 새로나온 어노테이션을 사용 해당 어노테이션은 사용 X
        - @GetMapping
        - @PostMapping
        - @PutMapping
        - @DeleteMapping

        @RequestMapping(value = "/hello", method = RequestMethod.GET)
            public String hello(){
                return "Hello World";
            }
    • 매개변수가 없는 GET 메서드 구현
      @GetMapping(value = "/name")
          public String getName() {
              return "minkyoung";
          }
    • @PathVariable을 활용한 GET 메서드 구현
      • URL 자체에 값을 담아 요청하는 것

      • @GetMapping 어노테이션 값으로 {} 중괄호를 이용해 어느 위치에 값을 받을지 정해야함

      • 매개변수와 그 값을 연결하기 위해 @Pathvariable을 명시
        → @GetMapping 어노테이션과 @PathVariable에 지정된 변수의 이름은 동일해야함
        → 동일하게 맞추기 어렵다면, @PathVariable(”variable”)로 어노테이션의 변수명 지정

        @GetMapping(value = "/variable1/{variable}") 
            public String getVariable1(@PathVariable String variable) {
                return variable;
            }
        
        @GetMapping(value = "/variable2/{variable}")
            public String getVariable2(@PathVariable("variable") String var) {
                return var;
            }
    • @RequestParam을 활용한 GET 메서드 구현
      • 쿼리 형식으로 값을 전달하는 것

      • URL에서 ‘?’을 기준으로 우측에 ‘{키}={값}’ 형태로 구성된 요청을 전송하는 것

      • ‘?’ 이후 연결 값은 ‘&’ 이다.

        // http://localhost:8080/api/v1/get-api/request1?name=value1&email=value2&organization=value3
        @GetMapping(value = "/request1")
            public String getRequestParam1(@RequestParam String name,
                                           @RequestParam String email,
                                           @RequestParam String organization) {
                return name + " " + email + " " + organization;
            }
      • 만약, 쿼리스트링에 어떤 값이 들어올지 모른다면 Map 객체 활용
        → Map<String, String> 키, 값

        @GetMapping(value = "/request2")
            public String getRequestParam2(@RequestParam Map<String, String> param) {
                param.entrySet().forEach((map)->{
                    System.out.printf("key:%s value:%s\n", map.getKey(), map.getValue());
                });
                return "request2가 호출 완료 되었습니다.";
            }
    • DTO 객체를 활용한 GET 메서드 구현
      • DTO(Data Transfer Object)는 다른 레이어 간의 데이터 교환에 활용

      • 각 클래스 및 인터페이스를 호출하면서 전달하는 매개변수로 사용되는 데이터 객체

      • 데이터 교환 용도 → 별도의 로직 X

      • 전달하고자 하는 필드 객체를 선언 → getter/setter 메서드 구현

        public class MemberDto {
            private String name;
            private String email;
            private String organization;
        
            public MemberDto(String name, String email, String organization) {
                this.name = name;
                this.email = email;
                this.organization = organization;
            }
        
            public String getName() {
                return name;
            }
        
            public String getEmail() {
                return email;
            }
        
            public String getOrganization() {
                return organization;
            }
        
            @Override
            public String toString() {
                return String.format("%s %s %s", this.name, 
        											this.email, this.organization);
            }
        }
        @GetMapping(value = "/request3")
            public String getRequestParam3(MemberDto memberDto) {
                return memberDto.toString();
            }

0개의 댓글