[初心-Spring Boot] Spring Boot Restful API 설정

0

초심-spring boot

목록 보기
3/16

1. Rest API란?


출처

1-1. rest의 정의 및 개념


“Representational State Transfer” 의 약자
자원을 이름(자원의 표현)으로 구분하여 해당 자원의 상태(정보)를 주고 받는 모든 것을 의미한다.
데이터가 요청되어지는 시점에서 자원의 상태(정보)를 전달한다.
JSON 혹은 XML를 통해 데이터를 주고 받는 것이 일반적이다.
HTTP URI(Uniform Resource Identifier)를 통해 자원(Resource)을 명시하고, HTTP Method(POST, GET, PUT, DELETE)를 통해 해당 자원에 대한 CRUD Operation을 적용하는 것을 의미한다

1-2. rest 구성요소


자원(Resource): URI

모든 자원에 고유한 ID가 존재하고, 이 자원은 Server에 존재한다.
자원을 구별하는 ID는 ‘/groups/:group_id’와 같은 HTTP URI 다.
Client는 URI를 이용해서 자원을 지정하고 해당 자원의 상태(정보)에 대한 조작을 Server에 요청한다.

행위(Verb): HTTP Method

HTTP 프로토콜의 Method를 사용한다.
HTTP 프로토콜은 GET, POST, PUT, DELETE 와 같은 메서드를 제공한다.

표현(Representation of Resource)

Client가 자원의 상태(정보)에 대한 조작을 요청하면 Server는 이에 적절한 응답(Representation)을 보낸다.
REST에서 하나의 자원은 JSON, XML, TEXT, RSS 등 여러 형태의 Representation으로 나타내어 질 수 있다.
JSON 혹은 XML를 통해 데이터를 주고 받는 것이 일반적이다.

1-3. API(Application Programming Interface)의 정의


데이터와 기능의 집합을 제공하여 컴퓨터 프로그램간 상호작용을 촉진하며, 서로 정보를 교환가능 하도록 하는 것

1-4. rest API 특징


  • 사내 시스템들도 REST 기반으로 시스템을 분산해 확장성과 재사용성을 높여 유지보수 및 운용을 편리하게 할 수 있다.
  • REST는 HTTP 표준을 기반으로 구현하므로, HTTP를 지원하는 프로그램 언어로 클라이언트, 서버를 구현할 수 있다.
  • 즉, REST API를 제작하면 델파이 클라이언트 뿐 아니라, 자바, C#, 웹 등을 이용해 클라이언트를 제작할 수 있다.

1-5. rest API 설계 규칙


URI는 정보의 자원을 표현해야 한다.

resource는 동사보다는 명사를, 대문자보다는 소문자를 사용한다.
resource의 도큐먼트 이름으로는 단수 명사를 사용해야 한다.
resource의 컬렉션 이름으로는 복수 명사를 사용해야 한다.
resource의 스토어 이름으로는 복수 명사를 사용해야 한다.

  • Ex) GET /Member/1 -> GET /members/1

자원에 대한 행위는 HTTP Method(GET, PUT, POST, DELETE 등)로 표현한다.

URI에 HTTP Method가 들어가면 안된다.

  • Ex) GET /members/delete/1 -> DELETE /members/1

URI에 행위에 대한 동사 표현이 들어가면 안된다.

(즉, CRUD 기능을 나타내는 것은 URI에 사용하지 않는다.)

  • Ex) GET /members/show/1 -> GET /members/1
  • Ex) GET /members/insert/2 -> POST /members/2

경로 부분 중 변하는 부분은 유일한 값으로 대체한다.

(즉, :id는 하나의 특정 resource를 나타내는 고유값이다.)

  • Ex) student를 생성하는 route: POST /students
  • Ex) id=12인 student를 삭제하는 route: DELETE /students/12

슬래시 구분자(/ )는 계층 관계를 나타내는데 사용한다.

URI 마지막 문자로 슬래시(/ )를 포함하지 않는다.

URI에 포함되는 모든 글자는 리소스의 유일한 식별자로 사용되어야 하며 URI가 다르다는 것은 리소스가 다르다는 것이고, 역으로 리소스가 다르면 URI도 달라져야 한다.
REST API는 분명한 URI를 만들어 통신을 해야 하기 때문에 혼동을 주지 않도록 URI 경로의 마지막에는 슬래시(/)를 사용하지 않는다.

하이픈(- )은 URI 가독성을 높이는데 사용

불가피하게 긴 URI경로를 사용하게 된다면 하이픈을 사용해 가독성을 높인다.

밑줄(_ )은 URI에 사용하지 않는다.

밑줄은 보기 어렵거나 밑줄 때문에 문자가 가려지기도 하므로 가독성을 위해 밑줄은 사용하지 않는다.

URI 경로에는 소문자가 적합하다.

URI 경로에 대문자 사용은 피하도록 한다.
RFC 3986(URI 문법 형식)은 URI 스키마와 호스트를 제외하고는 대소문자를 구별하도록 규정하기 때문

파일확장자는 URI에 포함하지 않는다.

REST API에서는 메시지 바디 내용의 포맷을 나타내기 위한 파일 확장자를 URI 안에 포함시키지 않는다.
Accept header를 사용한다.

리소스 간에는 연관 관계가 있는 경우

/리소스명/리소스 ID/관계가 있는 다른 리소스명

  • Ex) GET : /users/{userid}/devices (일반적으로 소유 ‘has’의 관계를 표현할 때)

2. REST API 설정하기


2-1.Controller method 추가


RptpController.java
package com.rptp.rptpSpringBoot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RptpController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello rptp!!");
        return "hello";
    }

    @GetMapping("hello-get-parameter")
    public String helloGetParameter(
            @RequestParam("name") String name,
            Model model) {
        model.addAttribute("getData", name);
        return "hello-get-parameter";
    }

//=============add=============
    @GetMapping("hello-rest-api")
    @ResponseBody
    public String helloRestApi(
            @RequestParam("name") String name) {
            
        return "hello" + name;

    }
//=============add=============
}

@ResponseBody

http body부에 리턴값 데이터를 직접 넣어준다.
위 메서드에서는 ViewResolver가 이동할 뷰를 찾아 이동하는데 반해, 이 메서드는HttpMessageConverter로 이동한다.
즉, 이 Annotation을 사용하면 view로 이동하지 않고 해서 문자열 그대로 return 한다.

2-2. Controller Class형식을 return하는 method 추가


RptpController.java
package com.rptp.rptpSpringBoot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RptpController {

    @GetMapping("hello")
    public String hello(Model model) {
        model.addAttribute("data", "hello rptp!!");
        return "hello";
    }

    @GetMapping("hello-get-parameter")
    public String helloGetParameter(
            @RequestParam("name") String name,
            Model model) {
        model.addAttribute("getData", name);
        return "hello-get-parameter";
    }

    @GetMapping("hello-rest-api")
    @ResponseBody
    public String helloRestApi(
            @RequestParam("name") String name) {
        return "hello" + name;
    }
//=============add=============
    @GetMapping("hello-rest-api-get-class")
    @ResponseBody
    public Hello helloRestApiGetClass(
            @RequestParam("name") String name) {
        Hello hello = new Hello();
        hello.setName(name);
        
        return hello;
    }

    static class Hello {
        private String name;

        public String getName() {
            return name;
        }

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

}


JSON 형식으로 출력하는 것을 볼 수 있다.
문자열 같은 경우는 기본적으로 StringHttpMessageConverter에서 처리하고,
객체 같은 경우는 기본적으로 MappingJackson2HttpMessageConverter에서 처리한다.

참조


https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%EC%9E%85%EB%AC%B8-%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/lecture/49578?tab=curriculum
rest Api란? https://gmlwjd9405.github.io/2018/09/21/rest-and-restful.html

0개의 댓글