스파이더 웹 개발

RESTFul 알아보기 본문

RESTful API

RESTFul 알아보기

스파이더웹 2022. 9. 18. 18:47
728x90
반응형

간단한 예제를 통해 알아보자

@RestController
public class HelloWorldController {

    //GET 방식
    //hello-world (endpoint)
    @GetMapping(path = "/hello-world")
    public String helloWorld(){
        return "Hello World";
    }
  
 }

@RestController을 사용하였기에, view가 반환되는 것이 아닌 데이터가 반환된다

 

POST MAN을 사용하여 GET 방식으로 요청했을때, 정상적으로 문자열이 반환되는 것을 확인할 수 있다.

 

이번에는 String을 반환하는 것이 아닌 Bean을 반환하는 경우를 살펴보자

   @GetMapping(path = "/hello-world-bean")
    public HelloWorldBean helloWorldBean(){
        return new HelloWorldBean("Hi Spider-webs");
    }
    
===========HelloWorldBean

@Data
@AllArgsConstructor
@NoArgsConstructor
public class HelloWorldBean {

    private String message;

}

GET 요청을 했을때 Key -Value 형태로 반환되는 것을 알 수 있다. 여기서 key에 해당하는 값은 HelloWorldBean 클래스의 생성자의 매개변수 이름인것을 알 수 있다

 

 

이번에는 api-url의 변수를 사용해보도록 해보자

    @GetMapping(path = "/hello-world-bean/path-variable/{name}")
    public HelloWorldBean helloWorldBean(@PathVariable String name){
        return new HelloWorldBean(String.format("반가워 , %s",name));
    }

기존과 비슷해보이지만, 여기서 확인할 점은 {name} 과 @PathVariable이다. {name}은 url의 가변데이터를 의미하며,

@PathVariable는 String name 변수는 url의 가변데이터에 해당되는 값입니다라는 것을 알려주는 용도이다. 혹 변수의 이름과 가변데이터의 이름이 다른경우 @PathVariable(value=) 을 사용하여 {가변데이터의 이름}과 일치시켜주면된다

 

GET 요청을 했을때 가변 데이터의 값이 정상 출력되는 것을 확인할 수 있다.

 

참고

https://www.inflearn.com/course/spring-boot-restful-web-services/dashboard

 

Spring Boot를 이용한 RESTful Web Services 개발 - 인프런 | 강의

이 강의는 Spring Boot를 이용해서 RESTful Web Services 애플리케이션을 개발하는 과정에 대해 학습하는 강의으로써, REST API 설계에 필요한 기본 지식에 대해 학습할 수 있습니다., - 강의 소개 | 인프런..

www.inflearn.com

 

728x90
반응형

'RESTful API' 카테고리의 다른 글

스프링 부트를 활용한 RESTful  (0) 2022.09.19
RESTful Service 기능 확장  (0) 2022.09.19
HTTP Method 와 Exception Handling  (0) 2022.09.18
REST/REST API /RESTFul API 란?  (0) 2022.09.18
Comments