개발 공부/Spring

[SpringBoot] REST API - GET

journey 2022. 2. 16. 00:37
728x90

03. GET API

  의미 CRUD 멱등성 안정성 Path
Variable
Query
Parameter
DataBody
GET 리소스 취득 R O X O O X
POST 리소스 생성, 추가 C X X O O
PUT 리소스 갱신, 생성 C / U O X O O
DELETE 리속스 삭제 D O X O O X
HEAD 헤더 데이터 취득 - O O - - -
OPTIONS 지원하는 메소드 취득 - O - - - -
TRACE 요청메세지 반환 - O - - - -
CONNECT 프록시 동작의 터널 접속으로 변경 - X - - - -

기본 구성

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/get")
public class GetApiController {

    @GetMapping(path = "/hello")    // http://localhost:8080/api/get/hello
    public String getHello() {
        return "get Hello";
    }
}

RequestMapping 메서드

  • RequestMapping = get / post / put / delete 모두 사용 가능한 매핑 방식.
  • method = "RequestMethod.GET" 로 어떤 메핑인지 판별하기. http://localhost:8080/api/get/hi
@RestController
@RequestMapping("/api/get")
public class GetApiController {

    @RequestMapping(path = "/hi", method = RequestMethod.GET)    
    public String hi() {
        return "hi";
    }
}

Path Variable

@RestController
@RequestMapping("/api/get")
public class GetApiController {

        @GetMapping("/path-variable/{name}")       
    public String pathVariable(@PathVariable String name) {     
        System.out.println("PathVariable : " + name);
        return name;
    }
}
  • @PathVariable(name = "name") 매핑되는 속성과 파라미터의 변수와 이름이 같아야 하나 파라미터의 변수의 이름을 다르게 설정해야 할 때 쓴다.
@RestController
@RequestMapping("/api/get")
public class GetApiController {

    @GetMapping("/path-variable/{name}")
    public String pathVariable(@PathVariable(name = "name") String pathName) {
        System.out.println("PathVariable : " + pathName);
        return pathName;
    }
}

Query Parm

  • 쿼리파라미터 : 검색 시 여러가지 매개변수 인자. 주소의 ? 이후를 쿼리파라미터라고한다.
  • ?key=value&key2=value2 형태로 되어있다.
/search?q=intellij&source=hp&ei=9WLtYbOTAYW7wAPDjp74AQ&iflsig=ALs-wAMAAAAAYe1xBXOicLJ2-viqzOlYHRqMFG1JPezg&oq=intell&gs_lcp=Cgdnd3Mtd...AQA&sclient=gws-wiz

1. 쿼리 파라미터를 Map으로 받기

import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/get")
public class GetApiController {

        // http://localhost:8080/api/get/query-param?user=zzangu&email=zzang@gmail.com&age=5
    @GetMapping(path = "query-param")
    public String queryParam(@RequestParam Map<String, String> queryParam) {
        StringBuilder sb = new StringBuilder();

        queryParam.entrySet().forEach(entry -> {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");

            sb.append(entry.getKey() + " = " + entry.getValue() + "\n");
        });

        return sb.toString();
    }
}

2. 쿼리 파라미터를 명시적으로 받기

@RestController
@RequestMapping("/api/get")
public class GetApiController {

        @GetMapping("query-param02")
    public String queryParam02(
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam int age
    ){
        System.out.println(name);
        System.out.println(email);
        System.out.println(age);

        return name + " " + email + " " + age;
    }

}

쿼리 파라미터에 잘못된 자료형이 들어갈 경우

  • 400 에러 클라이언트 실수. 파라미터를 int로 받기로 되어있는데 문자열이 들어갔다.

  • 스프링 부트 콘솔
2022-01-23 22:39:05.719  WARN 4850 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "5살"]

💡 파람이 map으로 들어올 땐 어떤게 들어올지 모른다. 그래서 모든 키를 받을 수 있다. 명시적으로 파람을 받는 경우에 사용한다.

3. 쿼리 파라미터를 객체로 받기

  • 파라미터에 객체가 들어올 경우 @RequestParam어노테이션은 붙이지 않는다.
  • 쿼리파라미터(? 뒤의 주소)의 주소를 스프링 부트가 판단한다.
  • ?user=zzangu&email=zzang@gmail.com&age=5 키(변수)에 해당하는 변수의 이름을 해당 객체에서 변수와 이름을 매칭한다.
public class UserRequest {

    private String name;
    private String email;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserRequest{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}
import com.example.hello.dto.UserRequest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/get")
public class GetApiController {

        @GetMapping("query-param03")
    public String queryParam02(UserRequest userRequest){
        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());

        return userRequest.toString();
    }

}

'개발 공부 > Spring' 카테고리의 다른 글

[SpringBoot] REST API - PUT  (0) 2022.02.16
[SpringBoot] REST API - POST  (0) 2022.02.16
[SpringBoot] REST API & IntelliJ 프로젝트생성  (0) 2022.02.16
[SpringBoot] 스프링 부트란  (0) 2022.02.14
[Spring boot] Lombok 사용하기  (0) 2022.01.11