[Spring] REST API

JihoLee·2022년 7월 17일
0

REST API 생성

@RestController : 해당 Class를 REST API를 처리하는 Controller로 지정하는 Annotation

@RequestMapping : 요청을 담당하는 Annotation. 'path' 인자로 URI 지정하고, 'method' 인자로 요청 방식 지정

@RestController
public class ApiController {
    
    @RequestMapping(path="/api/hello",method= RequestMethod.GET)
    public String hello(){
        return "Hello World!";
    }
}

GET API

  • 리소스를 취득
  • 요청을 보낼 때 Path Variable과 Query Parameter 사용

@GetMapping : Get 요청을 담당하는 Annotation. 'path' 인자로 URI를 지정

  • Path Variable 사용법

    	1. path에 사용할 value의 변수 이름을 {}로 묶어준다.
    	2. method의 parameter로 @PathVariable annotation을 붙여준다.
    	3. 'name' 인자로 이름을 지정할 수 있다.
    @GetMapping(path="/api/path-variable/{name}")
    public String pathVariableTest(@PathVariable(name="name") String name){
        return name;
    }
  • Query Parameter 사용법

    	1. RequestParam annotation을 Method의 Parameter에 사용한다.
    	2. 각각의 변수로 받거나, Map 객체를 받거나, DTO 객체를 받아서 사용할 수 있다.

    @RequestParam 이용

    @GetMapping(path="/api/query-param1")
    public String queryParamTest1(@RequestParam(name="name") String name){
        return name;
    }

    DTO 이용

    @Data
    public class RequestDto {
      String name;
    }
    @GetMapping(path="/api/query-param2")
      public String queryParamTest12(RequestDto name){
          return name.getName();
      }

POST API

  • 리소스를 생성,추가
  • 요청을 보낼 때 Path Variable과 Data Body 사용

@PostMapping : Post요청을 담당하는 Annotation. 'path' 인자로 URI를 지정

  • Data Body 사용법

    1. @RequestBody annotation을 Method의 Parameter에 사용한다.
    2. 각각의 변수로 받거나, Map 객체를 받거나, DTO 객체를 받아서 사용할 수 있다.

    요청

    {
        "name":"test",
        "email":"test@gmail.com",
        "age":26,
        "phone_number":"010-0000-0000"
    }

    PostRequestDto

    @Data
    @ToString
    public class PostRequestDto {
    
        String name;
        String email;
        int age;
        @JsonProperty("phone_number")
        String phoneNumber;
    }

    @JsonProperty annotation을 이용하여 개별적으로 변수의 이름을 Body와 매칭시킬 수 있다.

    @Data
    @ToString
    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    public class PostRequestDto {
    
      String name;
      String email;
      int age;
      String phoneNumber;
    }

    @JsonNaming annotation을 이용하여 전체적으로 data body의 변수들의 이름을 매칭시킬 수 있다.

    @PostMapping(path="/api/make-user")
      public String queryParamTest12(@RequestBody PostRequestDto user){
          return user.toString();
      }

    PUT API

    • 리소스를 생성, 갱신

      @PutMapping을 사용하고 Post API랑 방법은 동일

      DELETE API

    • 리소스를 삭제

    • Path Variable과 Query Parameter 사용

      @DeleteMapping

      ResponseEntity

      ResponseEntity는 개발자가 직접 결과 데이터와 HTTP 상태 코드를 직접 제어할 수 있는 클래스로 개발자는 404나 500 ERROR 와 같은 HTTP 상태 코드를 전송하고 싶은 데이터와 함께 전송할 수 있기 때문에 좀 더 세밀한 제어가 필요한 경우 사용합니다.

      @Data
      @ToString
      @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
      public class User {
         String name;
         String email;
         int age;
         String phoneNumber;
         @JsonIgnore
         String password;
         }
      @PostMapping(path="/api/make-user1")
         public ResponseEntity<User> queryParamTest12(@RequestBody User user) {
             return ResponseEntity.status(HttpStatus.OK).body(user);
      
         }
       //요청
       {
           "name":"test",
           "email":"test@gmail.com",
           "age":26,
           "phone_number":"010-0000-0000",
           "password":123
       }
       //응답
       {
           "name":"test",
           "email":"test@gmail.com",
           "age":26,
           "phone_number":"010-0000-0000"
       }

      @JsonIgnore annotation을 이용하여 Response에 포함하지 않을 변수를 지정할 수 있다.

profile
안녕하세요

0개의 댓글