Python web framework https://falconframework.org/
I had to create a simple API server in Python at work, so I chose Falcon, which is fast and has no extra features.
Install
Premise that Python and PyPy are installed
pip install falcon
Easy. Currently (2016/12) v1.1
Is it a little different when you put it on your Mac? Details are official. https://falcon.readthedocs.io/en/stable/user/install.html
Below is a sample API that returns json when accessing / hoge / {id} with get
# api.py
import falcon
import json
class HogeResource(object):
def on_get(self, req, resp, id):
"""Handles GET requests"""
resp.status = falcon.HTTP_200
resp.body = json.dumps({
"result": true,
"message": "success!",
})
api = falcon.API()
hoge = HogeResource()
api.add_route('/hoge/{id}', hoge)
All you have to do is pass an instance of the class that defines url and on_get (or on_post, on_put, etc.) to the instance of falcon.API () with add_route. Easy!
You can also validate using @ falcon.before
def validate(req, resp, resource, params):
try:
params['id'] = int(params['id'])
except ValueError:
raise falcon.HTTPBadRequest('Invalid ID',
'ID was not valid.')
class HogeResource(object):
@falcon.before(validate)
def on_get(self, req, resp, id):
#..Abbreviation..
This time we use gunicorn as the WSGI server
When I wrote the above code with the file name api.py
pip install gunicorn
gunicorn api:main
curl localhost:8000/hoge/12345
Tests are also supported so I wrote it http://falcon.readthedocs.io/en/stable/api/testing.html
#api_test.py
import falcon
import falcon.testing as testing
from api import api
class TestHogeResource(testing.TestCase):
def setUp(self):
super(testing.TestCase, self).setUp()
self.api = api
def test_hoge(self):
result = self.simulate_get("/hoge/12345")
self.assertEqual(result.status, falcon.HTTP_200)
def test_hoge_error(self):
result = self.simulate_get("/hoge/moge")
self.assertEqual(result.status, falcon.HTTP_400)
Install and use testtools
pip install testtools
python -m testtools.run api_test.py
> Ran 2 tests in 0.001s
> OK
Recommended Posts