Restful

Dec 16 2022
.
  • REST API의 6가지 제약 조건은 무엇입니까?
  • 클라이언트 — 서버 아키텍처 — 이 규칙은 관심사의 분리를 보장합니다. 클라이언트는 UI 문제를 관리하고 서버는 데이터 지속성 문제를 관리합니다. 그 대가로 우리는 일단 REST API가 다른 클라이언트를 관리할 수 있는 이식성이 뛰어난 시스템을 얻습니다.
  • 상태 비 저장 — 요청 사이에 서버에 클라이언트 데이터를 저장할 수 없습니다. 클라이언트 상태가 요청과 관련된 경우 요청과 함께 전송되어야 합니다. 서버가 클라이언트 세션을 저장해야 하는 경우 일정 기간 동안 DB에 저장해야 합니다.
  • 캐시 가능성 — 모든 응답은 캐시 가능 또는 캐시 불가능으로 표시되어야 합니다. 응답이 지속적으로 변경될 수 있는 경우 캐시하지 않아야 합니다. 캐시 가능성은 REST API의 성능에 중요합니다.
  • 계층화된 시스템 — 클라이언트는 원래 서버에 직접 연결되었는지 아니면 중개자인지 알 수 없으며 신경쓰지 않아야 합니다. 이는 REST가 계층화된 시스템 아키텍처를 가질 수 있고 요청이 다른 계층을 통해 전송될 수 있음을 의미합니다. 이는 보안 및 확장성(CDN, Authorization Server)에 도움이 됩니다.
  • 주문형 코드 — REST API는 필요할 때 실행 가능한 JavaScript 파일과 컴파일된 구성 요소를 클라이언트로 전송할 수 있습니다.
  • 균일한 인터페이스 — 이름에서 알 수 있듯이 API 클라이언트에 노출되는 리소스에 대한 인터페이스가 있어야 합니다. 서버의 리소스에는 리소스를 검색하거나 조작하기 위한 논리적 URI가 하나만 있어야 합니다.
    • 클라이언트-서버 아키텍처 기반
    • HTTP 프로토콜을 통해 다른 클라이언트에 서비스를 제공하려고 합니다.
    • 위에서 설명한 REST 제약 조건을 사용하려는 경우

    ############################################################################
    #                              Movie Apis Definitions                                #
    ############################################################################
    # Code completion support is available so start typing for available options.
    swagger: '2.0'
    
    # This is your document metadata
    info:
      version: "1.0.1"
      title: The movie api
    
    # Describe your paths here
    paths:
      # This is a path endpoint. Change it.
      /movies:
        # This is a HTTP operation
        get:
          # Describe this verb here. Note: you can use markdown
          description: Returns all movies
          operationId: getMovies
          # Expected responses for this operation:
          responses:
            # Response code
            200:
              description: Successful response
              # A schema describing your response object.
              # Use JSON Schema format
              schema:
                title: ArrayOfMovies
                type: array
                items:
                   $ref: '#/definitions/movie'
            default:
              description: Error
              schema:
                $ref: 'https://zalando.github.io/problem/schema.yaml#/Problem'
        post:
          description: Add a new movie
          operationId: addMovie
          parameters:
            - name: movie
              in: body
              description: The new movie
              required: true
              schema:
                $ref: '#/definitions/movie'
          responses:
            '201':
              description: The new movie
              schema:
                $ref: '#/definitions/movie'
            default:
              description: Error
              schema:
                $ref: 'https://zalando.github.io/problem/schema.yaml#/Problem'
      /movies/{id}:
        parameters:
          - name: id
            in: path
            description: ID of the movie
            required: true
            type: integer
            format: int64
        get:
          description: Returns a single movie
          operationId: getMovieById
          responses:
            200:
              description: Successful response
              schema:
                 $ref: '#/definitions/movie'
            default:
              description: Error
              schema:
                $ref: 'https://zalando.github.io/problem/schema.yaml#/Problem'
        put:
          description: Update an existing movie
          operationId: updateMovieById
          parameters:
            - name: movie
              in: body
              description: The movie
              required: true
              schema:
                $ref: '#/definitions/movie'
          responses:
            '200':
              description: The new movie
              schema:
                $ref: '#/definitions/movie'
            default:
              description: Error
              schema:
                $ref: 'https://zalando.github.io/problem/schema.yaml#/Problem'
        delete:
          description: Delete a movie
          operationId: deleteMovieById
          responses:
            '204':
              description: Movie deleted
            default:
              description: Error
              schema:
                $ref: 'https://zalando.github.io/problem/schema.yaml#/Problem'
    definitions:
      movie:
        type: object
        required:
          - id
          - title
        properties:
          id:
            type: integer
            format: int64
          title:
            type: string
          ratings:
            type: object
            properties:
              criticsScore:
                type: integer
                minimum: 0
                maximum: 100
              audienceScore:
                type: integer
                minimum: 0
                maximum: 100
          criticsConsensus:
            type: string
          abridgedDirectors:
            type: array
            items:
              type: string
          abridgedCast:
            type: array
            items:
               $ref: '#/definitions/cast'
          posters:
            $ref: '#/definitions/posters'
      cast:
        type: object
        required:
          - id
          - name
        properties:
          id:
            type: integer
            format: int64
          name:
            type: string
          characters:
            type: array
            items:
              type: string
      posters:
        properties:
          thumbnail:
            type: string
            format: uri
          profile:
            type: string
            format: uri
          detailed:
            type: string
            format: uri
          original:
            type: string
            format: uri
    

    • OAuth2 를 사용 하여 API를 보호하십시오.
    • 인증을 위해 자동 만료 Bearer 토큰을 사용하십시오( Authorisation: Bearer f0ca4227-64c4-44e1-89e6-b27c62ac2eb6).
    • HTTPS가 필요합니다.
    • JSON 웹 토큰 사용을 고려하십시오 .
    • 요청과 응답 모두에 대해 JSON을 기본값으로 사용하는 경우에도 Content-Type 및 Accept-Type 헤더를 사용하도록 합니다.
    • e.g.  Content-Type: application/json Accept-Type: application/json
      

    • 응답에는 다음 헤더가 포함됩니다.X-Frame-Options: deny
    • 레벨 0: 하나의 URI를 정의하고 모든 작업은 이 URI에 대한 POST 요청입니다.
    • 수준 1: 개별 리소스에 대해 별도의 URI를 만듭니다.
    • 수준 2: HTTP 메서드를 사용하여 리소스에 대한 작업을 정의합니다.
    • 레벨 3: 하이퍼미디어(HATEOAS, 아래 설명)를 사용합니다.

    {    
          "healthy": true,   
          "dependencies":
           {         "name": "moviesapi", 
            "healthy": true      
           } 
     }
    

    • POST 메서드의 경우 URI는 컬렉션과 같은 새 엔터티의 부모 리소스를 나타냅니다. 예를 들어 새 영화를 만들려면 URI가 /api/movies. 서버는 엔터티를 만들고 새 URI(예: /api/movies/6812360. 이 URI는 응답의 Location 헤더에 반환됩니다. 클라이언트가 요청을 보낼 때마다 서버는 새 URI로 새 엔터티를 만듭니다.
    • PUT 메서드의 경우 URI는 엔터티를 식별합니다. 해당 URI를 가진 엔터티가 이미 있는 경우 서버는 요청의 버전으로 기존 엔터티를 업데이트합니다.
    • Cache-Control — 응답을 캐시할 수 있는 최대 시간(ttl)입니다. ( Cache-Control: public, 360또는 Cache-Control: no-store)
    • 강력한 캐싱은 서버가 받는 요청 수를 최소화합니다.
    • ETag응답 헤더 를 통한 약한 캐싱 고려
    • ETag — 리소스 버전에 SHA1 해시를 사용합니다. 다른 표현을 만들기 때문에 해시 값에 미디어 유형을 포함해야 합니다. ( ETag: "2dbc2fd2358e1ea1b7a6bc08ea647b9a337ac92d"). 클라이언트는 이 메커니즘이 작동하려면 If-None-Match 헤더 를 보내야 합니다 .
    • 약한 캐싱은 서버가 수행해야 하는 작업을 최소화합니다(수신하는 요청 수는 아님).
    • 모든 프록시 및 클라이언트(예: NGINX, Apache, APIM)에서 헤더 기반 캐싱을 활성화하여 속도와 견고성을 높입니다.
    • URL의 데이터를 손상시키는 개인 정보 보호 또는 보안 없음
    • 프록시 또는 APIM이 아닌 REST 서버에서 가장 먼 엔드포인트에서 콘텐츠 암호화 구현
    • 콘텐츠 서명이 사용되면 콘텐츠가 (선택적으로) 암호화된 후에 수행됩니다.
    • X-Signing-Algorithm 헤더를 사용하여 콘텐츠 서명 유형 전달 ( X-Signing-Algorithm: RS256)
    • X-SHA256-Checksum 헤더를 사용하여 콘텐츠의 SHA256 해시 값 전달( X-SHA256-Checksum: e1d58ba0a1810d6dca5f086e6e36a9d81a8d4bb00378bdab30bdb205e7473f87)
    • X-Encryption-Algorithm 헤더를 사용하여 콘텐츠 암호화 유형 전달 ( X-Encryption-Algorithm: A128CBC-HS256)
    • 일관성(예측 가능하여 놀라움 방지)
    • 응집력(기능적 종속성이 있는 끝점만 나열)
    • 완전함(목적에 필요한 모든 끝점이 있음)
    • 최소(완료에 필요한 것보다 더 많은 엔드포인트 없음, 특징 없음)
    • 캡슐화(구현 세부정보 숨기기)
    • 자기 설명
    • 문서화됨(자체 설명이 충분하지 않은 경우)
    • WSO2
    • Apigee
    • IBM
    • 소프트웨어 AG
    • 뮬소프트