python3のfalconでapiをサクッと作成してみる。
環境
CentOS6
python3.5.1
falcon-1.0.0
手順
falconインストール
pip install --upgrade falcon
テスト用コード
vi falcon_test.py
# -*- coding: utf-8 -*- # sample.py import falcon import json class ItemsResource: def on_get(self, req, resp): value = req.params['key'] items = { 'title': 'WebAPIテスト', 'tags': [ { 'name': 'テスト','バージョン':[] }, { 'name': 'request', value:[] } ] } print(req.headers) resp.status = falcon.HTTP_200 resp.content_type = 'text/plain' resp.body = json.dumps(items,ensure_ascii=False) def on_post(self, req, resp): params = req.stream.read().decode('utf-8') items = { 'title': 'WebAPI(POST)', 'tags': [ { 'name': 'テスト','バージョン':[] }, { 'name': 'request', params:[] } ] } resp.status = falcon.HTTP_200 resp.content_type = 'text/plain' resp.body = json.dumps(items,ensure_ascii=False) api = falcon.API() api.add_route('/test_api', ItemsResource()) if __name__ == "__main__": from wsgiref import simple_server httpd = simple_server.make_server("127.0.0.1", 8008, api) httpd.serve_forever()
起動してみる
※BGプロセスで起動
python falcon_test.py &
curlでアクセスしてみる
get
[root@localhost falcon]# curl http://localhost:8008/test_api?key=TEST {'ACCEPT': '*/*', 'CONTENT-TYPE': 'text/plain', 'CONTENT-LENGTH': '', 'HOST': 'localhost:8008', 'USER-AGENT': 'curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.21 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2'} 127.0.0.1 - - [14/Sep/2016 22:32:37] "GET /test_api?key=TEST HTTP/1.1" 200 117 {"tags": [{"バージョン": [], "name": "テスト"}, {"TEST": [], "name": "request"}], "title": "WebAPIテスト"}
post
[root@localhost falcon]# curl -d "kkk=value1" http://localhost:8008/test_api 127.0.0.1 - - [14/Sep/2016 22:57:48] "POST /test_api HTTP/1.1" 200 120 {"tags": [{"name": "テスト", "バージョン": []}, {"name": "request", "kkk=value1": []}], "title": "WebAPI(POST)"}
出来た。
すごい簡単、30分位で出来た。