Created
October 10, 2018 03:11
-
-
Save kiakiraki/a1e352afeb79792d39e86bfd49d46654 to your computer and use it in GitHub Desktop.
REST API server sample using Flask-RESTPlus
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from flask import Flask, request | |
from flask_restplus import Api, Namespace, Resource, fields | |
# initialize flask app | |
app = Flask(__name__) | |
api = Api( | |
app, | |
title='Hello World!', | |
version='1.0', | |
description='てすとだよ' | |
) | |
# initialize namespaces and define request & response models | |
hello_namespace = Namespace('helloworld', description='sample endpoint') | |
model_of_response = hello_namespace.model( | |
'GET & POST method response', { | |
'message': fields.String( | |
required=True, | |
description='response message', | |
example='Hello World!', | |
) | |
} | |
) | |
model_of_request = hello_namespace.model( | |
'POST method request', { | |
'アイサツ': fields.String( | |
required=True, | |
description='古事記にも記されている通り実際奥ゆかしい作法', | |
example='ヘルカイト' | |
) | |
} | |
) | |
@hello_namespace.route('') | |
class HelloWorld(Resource): | |
@hello_namespace.marshal_with(model_of_response) | |
def get(self): | |
response = { | |
'message': 'Hello World!' | |
} | |
return response, 200 | |
@hello_namespace.expect(model_of_request, varidate=True) | |
@hello_namespace.marshal_with(model_of_response) | |
def post(self): | |
response = { | |
'message': f'ドーモ、{request.json["アイサツ"]} = サン、ニンジャスレイヤーです' | |
} | |
return response, 200 | |
api.add_namespace(hello_namespace) | |
def main(): | |
app.run() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment