반응형

0. 들어가기

-. flask-restx를 이용한 swagger 문서화 상세설정

-. documentation 에 대한  한글 자료가 별로 없어서 공부할 겸 정리할 겸...

-. 바꿔얘기하면, 틀린게 있을수도 있다는거.

 

1. 입력변수 설정

-. API 각 단말에 대한 입력 요구 변수들을 문서화 할 수 있다.

1) PATH routing

-. API endpoint에 대해 routing이 필요한 경우 입력되는 path에 대해 변수 선언을 할 수 있다. (ex. bbs/read/글번호)

-. Flask routing과 동일한 방식으로 <type:variable> 형태로 선언하면 path에 대해 *required 태그가 달린다.

@ns.route('/read/<string:articleNo>')
class BbsRead(Resource):
    @staticmethod
    def get(articleNo):

2) GET parameters

-. get 호출 시 입력 가능한 변수들 문서화. add_argument(변수명, type='type', default='기본값', required=True/False)

-. required=True 설정 시 필수 parameter가 되고, 이 경우 default 값 설정을 하더라도 미입력 에러가 뜬다.

listFrom = reqparse.RequestParser()
listFrom.add_argument('last', type=int, default=None, help='마지막 글 articleId')


@ns.route('/')
class BbsList(Resource):
    @staticmethod
    @ns.expect(listFrom)
    def get():

-. 여러개의 get parameters를 받기를 원하면 action='split' or action='append' 추가를 할 수 있다. 이 경우 swagger document는 둘 다 query를 여러개 입력 하는 것으로 변경된다. 기능은 동일하니 선택해서 쓰자.

-. 'split' action을 사용 시에는 comma (' , ')로 구분된 문자열을 입력하여 작동한다. (python split 함수와 동일함)

listFrom.add_argument(... action='split')

input: http://127.0.0.1:9998/api/v2/bbs/?last=1,2,3,4,4,4
output: [1, 2, 3, 4, 4, 4]

-. 'append' action을 사용 시에는 동일한 parameter 명을 여러번 입력해야 한다. 

listFrom.add_argument(... action='append')

input: http://127.0.0.1:9998/api/v2/bbs/?last=1&last=2&last=3&last=4&last=4&last=4
output: [1, 2, 3, 4, 4, 4]

3) POST body

-. post method의 body payload 문서화. get에도 설정할 수는 있는데 쓰진 않으니...

-. api.model로 input body 구조를 정의하고, 이를 api 단말의 post route에 데코레이터로 달아서 적용할 수 있다.

model = ns.model('new article', strict=True, model={
    'writer': fields.String(title='글 작성자', default='writer', required=True),
    'password': fields.String(title='비밀번호', default='password', required=True),
    'category': fields.String(title='글 카테고리', default='잡담', required=True),
    'title': fields.String(title='글 제목', default='title', required=True),
    'description': fields.String(title='글 본문', default='description', required=True),
})


@ns.route('/write')
class BbsWrite(Resource):
    @staticmethod
    @ns.expect(model, validate=True)
    def post():

-. model 설정 시 strict=True/False와 각 field에 대한 required=True/False 설정을 할 수 있고, model strict=True 설정이 된 경우, required field가 payload에 들어있지 않은 경우, 400(bad request) eror 가 뜬다.

-. 설정된 model들은 swagger 최 하단에서 확인할 수 있다.

 

2. 추가 documentation

-. doc() 함수로 swagger document에 세부 명세를 작성할 수 있다.

1) status code

-. api.doc(responses={code: 'description'} 방식으로 각 단말의 응답코드를 document에 추가하는 것이 가능하다. 예를들어, 아래와같이 상태 코드를 추가하자. 

@ns.route('/write')
class BbsWrite(Resource):
    @staticmethod
    @ns.doc(responses={404: 'Not found'})
    @ns.doc(responses={405: 'Not allowed'})
    @ns.doc(responses={400: 'Bad request'})
    def get():

-. swagger document에 아래와 같이 추가된다. (주의: 해당 코드 방출 시 실제로 저런 메시지가 나오진 않는다. 코드에 대한 설명일 뿐.)

-. api.doc(responses={}) 는 api.response로 대체 가능.

@ns.route('/write')
class BbsWrite(Resource):
    @staticmethod
    @ns.response(404, 'Not found')
    @ns.response(405, 'Not allowed')
    @ns.response(400, 'Bad request')
    # @ns.doc(responses={404: 'Not found'})
    # @ns.doc(responses={405: 'Not allowed'})
    # @ns.doc(responses={400: 'Bad request'})
    def get():

2) path routing documentation

-. path routing (~/<type:variable>) 방식으로 추가된 get parameter에 대한 documentation을 설정할 수 있다.

@ns.route('/read/<int:articleNo>')
@ns.doc(params={'articleNo': 'article number'})
class BbsRead(Resource):
    @staticmethod
    def get(articleNo):

-. 마찬가지로 api.doc(params={}) 는 api.param()로 대체 가능. document에는 api.params()를 쓰라고 되어있는데, .param이 맞다.

@ns.route('/read/<int:articleNo>')
# @ns.doc(params={'articleNo': 'article number'})
@ns.param('articleNo', 'article number')
class BbsRead(Resource):
    @staticmethod
    def get(articleNo):

 

728x90
반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기