본문 바로가기
Network/Server

[Swagger] Swagger Hub를 이용한 Swagger 사용하기

by 며루치꽃 2021. 5. 4.

 

Swagger의 필요성 

과거 프로젝트에서는 API를 작성하면 구글 스프레드시트를 이용하여 직접 수기로 입력하였습니다. 수기로 입력하다보니, 대소문자 구분과 오타 같은 부분은 확인하기 어렵다보니, 프론트엔드 개발자 분들에게 피해를 끼치는 일이 발생하였고 이를 통해 Swagger이라는 툴을 알게 되었습니다. Swagger 툴은 백엔드 개발자가 API를 작성하면 프론트엔드 개발자가 어떤 데이터를 주고 받아야하는지 알기 위해 기록해두는 문서가 필요합니다. 이 때 Swagger는 백엔드 개발자와 프론트엔드 개발자와 사이에서 어떤 방식으로 데이터를 주고 받고 데이터를 요청했을 때, 받아야할 response는 무엇인지에 대한 명세서인 API를 관리할 수 있는 도구입니다. 

 

Swagger Hub

https://swagger.io/tools/swaggerhub/

 

SwaggerHub | API Design and Documentation with OpenAPI

 

swagger.io

 

우선 간단하게 어떻게 작동되는지 알아보기 위해서 가입을 진행하였고 Create New API로 다음과 같이 만들어 주었습니다.

또한, 실습을 위해서는 json 파일이 필요하였는데 테스트를 위해 jsonplaceholder 에서 만들어진 json을 통해 

테스트를 진행할 수 있습니다.

 

jsonplaceholder을 이용하여 테스트하기 

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB As of Dec 2020, serving ~1.8 billion requests each month.

jsonplaceholder.typicode.com

response 데이터를 받기 위해 파라미터, 요청할 서버를 설정해주기 위해서 코드 작성칸에 아래와 같이 명시해주어야

합니다. 

openapi: 3.0.0
info:
  version: 1.0.0
  title: swagger-example2
  description: Swagger 실습을 위한 API Example

servers:
  # Added by API Auto Mocking Plugin
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/skykchmin/swagger-example2/1.0.0
  - description: JSON Placeholder API
    url: https://jsonplaceholder.typicode.com
paths:
  /todos/{id}:
    get:
      summary: Return a user by ID
      parameters: 
        - name: id
          in: path
          required: true
          description: The ID of the user to return 
          schema:
            type: integer
      responses: 
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  userId: 
                    type: integer 
                  id:
                    type: integer
                  title:
                    type: string
                  completed:
                    type: boolean

Info 부분에는 openapi 버젼과 정보가 들어가고 

servers 부분에는 이용할 서버 URL과 제목, 설명을 적어주면 됩니다.

paths 부분에는 전달할 파라미터의 이름, 자료형, 설명 등을 적어주면 됩니다.

response 부분에는 응답 코드와 함께 content에는 json이나 text 같이 return 받을 데이터 타입과 

response에 포함될 객체 이름과 자료형을 명시해주면 됩니다. 

 

코드를 작성 후에 Save를 누르고 새로고침을 하여 확인을 할 수 있습니다. 

사용할 서버를 아래와 같이 체크 후에 명시한 파라미터나 패스를 넣어서 실행해보면 작성했던 결과를 테스트 해볼수 있습니다. 

servers 부분에서 작성한 URL이 설명과 함께 나와있으며 jsonplaceholder 를 이용하였기에 서버를 선택하였습니다.

GET 요청을 보낼 URL 주소와 함께 오른쪽 상단에 있는 Try it out 버튼을 누르고, path variable에 원하는 id 값인 7을 입력해주면 아래와 같은 Responses 화면을 확인할 수 있습니다. 

상태코드 200과 함께 response body가 반환되며 서버의 응답 데이터를 확인할 수 있습니다.

만약 문제가 발생하였다면, 이와 같이 테스트를 할 수 있기 때문에 쉽게 해결할 수 있습니다. 

 

구글 API 자동완성 적용해보기 

 

구글에는 문자를 입력할 때마다 자동완성 기능을 위해서, 구글의 자동완성 API를 요청을 합니다.

보통의 경우에는, 두 개의 API가 같이 사용되는 일은 없지만 실습을 위해 같이 작성합니다. 

 

openapi: 3.0.0
info:
  version: 1.0.0
  title: swagger-example2
  description: Swagger 실습을 위한 API Example

servers:
  # Added by API Auto Mocking Plugin
  - description: SwaggerHub API Auto Mocking
    url: https://virtserver.swaggerhub.com/skykchmin/swagger-example2/1.0.0
  - description: JSON Placeholder API
    url: https://jsonplaceholder.typicode.com
  - description: Google API
    url: https://www.google.com
paths:
  /todos/{id}:
    get:
      summary: Return a user by ID
      parameters: 
        - name: id
          in: path
          required: true
          description: The ID of the user to return 
          schema:
            type: integer
      responses: 
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  userId: 
                    type: integer 
                  id:
                    type: integer
                  title:
                    type: string
                  completed:
                    type: boolean
  /complete/search:
    get:
      summary: 자동완성 검색결과 반환
      parameters: 
        - name: q
          in: query
          schema:
            type: string
        - name: client
          in: query
          schema:
            type: string
      responses: 
        '200':
          description: A text file
          content:
            text/plain:
              schema:
                type: string

아까와 같이 코드를 작성하고 저장하여 새로고침한 다음, 서버를 아래와 같이 www.google.com 으로 선택해주고,

 

Try it out 버튼을 누르고, query string에 원하는 값인 q에 ABC와 함께 client에는 psy-ab을 입력해주면 아래와 같은 Responses 화면을 확인할 수 있으면서 유니코드로 되어있는 text file을 받을 수 있습니다.  

 

위와 같이 응답코드와 response를 받을 수 있으며 응답받을 코드에는 text로 하였기 때문에 아래와 같이 유니코드로 구성된 text 파일을 받을 수 있습니다!

 

'Network > Server' 카테고리의 다른 글

[Cloud] Google app engine에 대하여  (0) 2021.07.05
[Server] oAuth 의 개념  (0) 2021.06.22
[Server] src 폴더 구성  (0) 2021.01.22
[Server] connection Pool 이용하기  (0) 2021.01.22
[Server] Rest API config 파일 설명  (0) 2021.01.22

댓글