2022.08.13 - [Launguage/Python] - [Python][Flask] 02. Route 구조설계 - Restx
[Python][Flask] 02. Route 구조설계 - Restx
Flask 의 Blueprint 외에 RESTful API 개발을 위한 Flask-Restx 라는 라이브러리 있습니다. 해당 라이브러리에서는 Swagger와 같은 API 문서화 및 테스트와 Validation 등의 다양한 기능을 제공하며, 해당 포스트..
tailerbox.tistory.com
앞선 포스트에서 설명했던 코드를 기반으로 Swagger 를 통해 API 의 사양 및 요청 테스트를 할 수 있도록 몇가지 코드를 추가합니다.
from flask_restx import Resource, Namespace, fields
# Define Namespace
ns = Namespace(name='api/v1/users', description='User APIs')
# Define Namespace Model
user_model = ns.model('User', {
'id': fields.Integer(example=1),
'name': fields.String(description="this is description", example="tailor")
})
@ns.response(400, 'BadRequest', ns.model('BadRequest', {
"errors": fields.Nested(
ns.model('InvalidParams', {"field_name": fields.String})
)
}))
@ns.response(401, 'Unauthorized', ns.model('Unauthorized', {
"message": fields.String(example="Invalid API credentials")
}))
class User(Resource):
def get(self):
return 'user list'
@ns.expect(ns.model('CreateUser', {
"name": fields.String(example="tailor")
}))
@ns.response(201, 'Success', model=user_model)
def post(self):
created = 2
return 'create', 201, {
'x-resource-id': created,
'x-resource-uri': '/api/users/{}'.format(created)
}
# @ns.expect(parser)
class UserByIdx(Resource):
@ns.expect(ns.parser().add_argument('idx', type=int, help='User IDx'))
@ns.doc(
responses={
200: '조회 성공',
204: '조회 결과 없음',
400: '잘못된 요청',
}
)
def get(self, idx: int):
return f'specific user {idx}', 200
def put(self, idx: int):
return 'update', 200, {
'x-resource-id': idx,
'x-resource-uri': '/api/users/{}'.format(idx)
}
def delete(self, idx: int):
return f'delete {idx}', 204
# Add Resources
ns.add_resource(User, '/')
ns.add_resource(UserByIdx, '/<idx>')
- ns.model : Namespace Class에서 제공하는 모델 생성 메소드로 첫번째 인자는 name, 두번째 인자로 모델의 property 를 전달한다.
- ns.response : Class 또는 Method 에 사용 가능한 데코레이터로 해당 라우트의 응답에 대한 정보를 전달한다.
위와 같은 데코레이터와 Model 을 추가한 후 Swagger Doc 페이지를 확인해보면 아래와 같은 결과를 확인할 수 있으며, 해당 엔드포인트에 대한 API Request Test 가 가능하다.
Flask-Restx 에서 제공하는 Swagger 의 보다 상세한 내용은 아래의 공식 레퍼런스 문서를 참고
Ref. https://flask-restx.readthedocs.io/en/latest/swagger.html#
'Launguage > Python' 카테고리의 다른 글
[Python][기본 03] async/await (0) | 2023.02.08 |
---|---|
[Python][Django] 00. 설치 (0) | 2023.02.06 |
[Python][Flask] 02. Route 구조설계 - Restx (0) | 2022.08.13 |
[Python][Flask] 02. Route 구조설계 - Blueprint (0) | 2022.08.13 |
[Python][Flask] 01. 기본 라우트 & 순환참조 & Blueprint (0) | 2022.07.31 |