LoginSignup
64
57

More than 5 years have passed since last update.

hugを使って爆速でWeb APIサーバーを構築する

Last updated at Posted at 2016-08-02

はじめに

hugは、Web APIサーバーの構築に特化したWebアプリケーションフレームワークです。
他のフレームワークがテンプレートエンジンやORマッパなどのリッチな機能を詰め込んでいるのに対して、hugはWeb APIサーバーに必要な機能だけに特化したフレームワークになっています。

hug Official Site

特筆すべきは、そのシンプルさと速度です。
以下は公式ページに掲載のベンチマークです(Pycnicによるベンチマーク)。
スクリーンショット 2016-08-02 11.33.56.png
速度ではわずかにFalconには及びませんが、それでも非常に高速であり、またFalconより実装するのがはるかに簡単です。

さっそくインストールして触ってみましょう。

インストール

hugはPython3系のみに対応しています。インストールは以下で行います。

pip install hug

はじめてのhug

では、APIを作ってみましょう。
実装は非常に簡単です。以下は、シンプルなレスポンスを返すサーバーの実装例です。

hello_hug.py
import hug


@hug.get('/hello')
def hello(name):
    """Says Hello to a user"""
    return "Hello {}!".format(name)

@hug.get()という部分がHTTP methodのデコレータです。get以外にもpostやupdateなどなどがあります。

では実行してみましょう。以下で実行できます。実行すると8000番ポートでサーバーが立ち上がり、アクセスするとレスポンスが返ってきます。

hug -f hello_hug.py

ブラウザでhttp://localhost:8000/hello?name=hugにアクセスしてみてください。レスポンスが見れるはずです。

またhttp://localhost:8000/documentationにアクセスすることで簡単なドキュメントを見ることができます。

{
    "404": "The API call you tried to make was not defined. Here's a definition of the API to help you get going :)",
    "documentation": {
        "handlers": {
            "/hello": {
                "GET": {
                    "usage": "Says Hello to a user",
                    "outputs": {
                        "format": "JSON (Javascript Serialized Object Notation)",
                        "content_type": "application/json"
                    },
                    "inputs": {
                        "name": {
                            "type": "Basic text / string value"
                        }
                    }
                }
            }
        }
    }
}

バージョニング

hugを使えばAPIのバージョニングも簡単にできます。バージョニングの実装も非常に簡単です。以下のコードをみてみましょう。

versioning_example.py
# filename: versioning_example.py
"""A simple example of a hug API call with versioning"""
import hug

@hug.get('/echo', versions=1)
def echo(text):
    return text


@hug.get('/echo', versions=range(2, 5))
def echo(text):
    return "Echo: {text}".format(**locals())

バージョニングを行うにはversionsに数字か範囲を指定するだけです。

以下で実行します。

hug -f versioning_example.py

http://localhost:8000/v1/echo?text=Hihttp://localhost:8000/v2/echo?text=Hiにアクセスして違いを比べてみてください。簡単にバージョニングできていることがわかると思います。

まとめ

以上で挙げたバージョニング以外にもAPIを作る上で便利な機能があります。特に非同期処理が簡単にできるのはうれしいです。

用途としては、以下のようなシチュエーションに向いていると思います。

  • センサーデータのような、トラフィックの多いデータを高速にさばきたい
  • 学習コストの高いフレームワークは嫌だ
  • シンプルなAPIサーバーを作りたい

ぜひ、使ってみてその速度と手軽さを体感してもらえればと思います。

64
57
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
57