Create an API server quickly with Python + Falcon

I think you often use a web application framework to create an API server, but you don't need something so versatile, isn't it? This Falcon can be used in such a case. Falcon The minimum requirement is one file. Feel free to get started.

Installation

Use pip. Easy. If it doesn't work, try adding sudo.

$ pip install falcon

Try using

All you need is one file. Let's say sample.py.

Write resources

A resource is a class that handles requests. If you write ʻon_get or ʻon_post, it will handle the request of the corresponding method.

sample.py


...
class SampleResource:
    def on_get(self, req, resp):
        obj = {
            "header": "Hello!",
            "body": {
                "a": "hoge",
                "b": "fuga",
            }
        }
        resp.body = json.dumps(obj, ensure_ascii=False)
...

Write the routing

ʻAdd_route` connects the path with the class that handles the request.

sample.py


...
app = falcon.API()
app.add_route('/sample', SampleResource())
...

to start

Please change the address and port as appropriate. This part is not necessary when using gunicorn etc.

sample.py


...
if __name__ == "__main__":
    from wsgiref import simple_server

    httpd = simple_server.make_server("127.0.0.1", 8000, app)
    httpd.serve_forever()
...

test

It works normally with python.

$ python sample.py

When I try to access it, it seems to work. http://localhost:8000/sample

{"body": {"a": "hoge", "b": "fuga"}, "header": "Hello!"}

Use a little more

Use gunicorn

Install with pip.

$ pip install gunicorn

It seems to use 8000 ports by default.

$ gunicorn sample:app
[2016-12-15 20:37:20 +0900] [34136] [INFO] Starting gunicorn 19.6.0
[2016-12-15 20:37:20 +0900] [34136] [INFO] Listening at: http://127.0.0.1:8000 (34136)
...

Use -b to change the port (address).

$ gunicorn -b 127.0.0.1:8888 sample:app
[2016-12-15 20:41:29 +0900] [34225] [INFO] Starting gunicorn 19.6.0
[2016-12-15 20:41:29 +0900] [34225] [INFO] Listening at: http://127.0.0.1:8888 (34225)
...

Get request parameters

It is in the req in the arguments such as ʻon_get`.

sample.py


class ParamsResource:
    def on_get(self, req, resp):
        params = req.params
        resp.body = json.dumps(params, ensure_ascii=False)

app = falcon.API()
app.add_route('/params', ParamsResource())

/params => {} /params?a=hoge&b=fuga => {"a": "hoge", "b": "fuga"}

I got it. It's a good idea to read the request and response here. req/resp

Access the DB

There is no specific means in the standard. I will prepare it myself. I'm using MySQL in my environment, so I'll try to access it. First, install MySQL-Python. Introducing the familiar pip.

$ pip install MySQL-Python

And write. Please change the DB information as appropriate.

sample.py


...
class BusinnesTermResource:
    def on_get(self, req, resp):

        connection = MySQLdb.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='password',
            db='sample',
            charset='utf8',
            cursorclass=MySQLdb.cursors.DictCursor
        )
        cursor = connection.cursor()

        sql = "select * from business_term"
        cursor.execute(sql)
        term = cursor.fetchone()

        cursor.close()
        connection.close()

        resp.body = json.dumps(term, ensure_ascii=False)

app = falcon.API()
app.add_route('/businnes_term', BusinnesTermResource())
...

I got it.

{"term": "Hoge", "meening": "Fuga", "example": "sample", "id": 1}

Full code this time

sample.py


# -*- coding: utf-8 -*-
# sample.py
import falcon
import json
import MySQLdb
from MySQLdb.cursors import DictCursor

class BusinnesTermResource:
    def on_get(self, req, resp):

        connection = MySQLdb.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='password',
            db='sample',
            charset='utf8',
            cursorclass=MySQLdb.cursors.DictCursor
        )
        cursor = connection.cursor()

        sql = "select * from business_term"
        cursor.execute(sql)
        term = cursor.fetchone()

        cursor.close()
        connection.close()

        resp.body = json.dumps(term, ensure_ascii=False)

class SampleResource:
    def on_get(self, req, resp):
        obj = {
            "header": "Hello!",
            "body": {
                "a": "hoge",
                "b": "fuga",
            }
        }
        resp.body = json.dumps(obj, ensure_ascii=False)

class ParamsResource:
    def on_get(self, req, resp):
        params = req.params
        resp.body = json.dumps(params, ensure_ascii=False)

app = falcon.API()
app.add_route('/businnes_term', BusinnesTermResource())
app.add_route('/sample', SampleResource())
app.add_route('/params', ParamsResource())

if __name__ == "__main__":
    from wsgiref import simple_server

    httpd = simple_server.make_server("127.0.0.1", 8000, app)
    httpd.serve_forever()

in conclusion

It was very easy to make and it felt good. It's quick to write and start up, so it's crisp. I would like to use it for testing once, or with a suitable and good application that does not have such a large number of users.

Recommended Posts

Create an API server quickly with Python + Falcon
Quickly create an excel file with Python #python
Create an API with Django
Web API with Python + Falcon
Create an animated GIF local server with Python + Flask
Create Awaitable with Python / C API
Create an Excel file with Python3
Create API with Python, lambda, API Gateway quickly using AWS SAM
Create an English word app with python
Create an app that guesses students with python
Create an image with characters in python (Japanese)
Local server with python
Create a fake Minecraft server in Python with Quarry
[Vagrant] Set up a simple API server with python
[LINE Messaging API] Create parrot return BOT with Python
Use Trello API with python
Create an environment with virtualenv
Use Twitter API with Python
Create 3d gif with python3
Creating an egg with python
Easy HTTP server with Python
Call the API with python3.
Use subsonic API with python3
Try hitting the Twitter API quickly and easily with Python
Quickly take a query string with API Gateway-> Lambda (Python)
Build a speed of light web API server with Falcon
[Python Kivy] How to create an exe file with pyinstaller
Cut out an image with python
[AWS] Create API with API Gateway + Lambda
Create folders from '01' to '12' with python
Write an HTTP / 2 server in Python
Persist Flask API server with forever
Quine Post with Qiita API (Python)
Create a virtual environment with Python!
I sent an SMS with Python
Create Gmail in Python without API
[python] Read information with Redmine API
Create API using hug with mod_wsgi
Create an age group with pandas
Quickly implement REST API in Python
Draw an illustration with Python + OpenCV
[Python] Send an email with outlook
[Python] Create API to send Gmail
Create an alias for Route53 to CloudFront with the AWS API
How to create a heatmap with an arbitrary domain in Python
[LINE Messaging API] Create a BOT that connects with someone with Python
[For Python] Quickly create an upload file to AWS Lambda Layer
Create an application that just searches using the Google Custom Search API with Python 3.3.1 in Bottle
Collecting information from Twitter with Python (Twitter API)
Create an application by classifying with Pygame
[Python] Building an environment with Anaconda [Mac]
Create a Python function decorator with Class
Create wordcloud from your tweet with python3
[In-Database Python Analysis Tutorial with SQL Server 2017]
Build a blockchain with Python ① Create a class
Challenge to create time axis list report with Toggl API and Python
Create an image processing viewer with PySimpleGUI
Create a dummy image with Python + PIL.
Retrieving food data with Amazon API (Python)
Create your own DNS server with Twisted
[Python] Create a virtual environment with Anaconda