# Default to 200 OK
class Todo1(Resource):
def get(self):
return {'task': 'Hello world'}
# Set the response code to 201
class Todo2(Resource):
def get(self):
return {'task': 'Hello world'}, 201
# Set the response code to 201 and return custom headers
class Todo3(Resource):
def get(self):
return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}
add_resource() 메서드나 route() decorator에 여러 URL을 전달할 수 있다.
api.add_resource(HelloWorld, '/hello', '/world')
class HelloWorld(Resource):
pass
@api.route('/hello', '/world')
class HelloWorld(Resource):
pass
from flask_restplus import reqparse
parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Rate to charge for this resource')
args = parser.parse_args()
$ curl -d 'rate=foo' http://127.0.0.1:5000/todos
{'status': 400, 'message': 'foo cannot be converted to int'}
args = parser.parse_args(strict=True)
from flask import Flask
from flask_restplus import fields, Api, Resource
app = Flask(__name__)
api = Api(app)
model = api.model('Model', {
'task': fields.String,
'uri': fields.Url('todo_ep')
})
class TodoDao(object):
def __init__(self, todo_id, task):
self.todo_id = todo_id
self.task = task
# This field will not be sent in the response
self.status = 'active'
@api.route('/todo')
class Todo(Resource):
@api.marshal_with(model)
def get(self, **kwargs):
return TodoDao(todo_id='my_todo', task='Remember the milk')
공개 필드이름이 내부 필드 이름과 다를 경우 attribute 키워드 인자를 사용하면 된다.
model = {
'name': fields.String(attribute='private_name'),
'address': fields.String,
}
model = {
'name': fields.String(attribute=lambda x: x._private_name),
'address': fields.String,
}