LoginSignup
43

More than 3 years have passed since last update.

python製の最新APIフレームワーク FastAPI を触ってみた

Last updated at Posted at 2019-03-31

FastAPIとは

FastAPIの公式ページには次のように書かれています。

FastAPIは、標準のPythonタイプヒントに基づいてPython 3.6+でAPIを構築するための最新の高速(高性能)Webフレームワークです。

主な機能は次のとおりです。

Fast:NodeJSやGoと同等の非常に高いパフォーマンス(StarletteとPydanticのおかげで)。利用可能な最速のPythonフレームワークの1つ。

速いコーディング:機能を開発する速度を約200%から300%*向上させます。

バグを減らす:人間(開発者)が引き起こすエラーの約40%を減らします。*
直感的:優れたエディターサポート。至る所で完成。短時間でデバッグできます。
簡単:使いやすく学べるように設計されています。ドキュメントを読む時間が短くなります。
短:コードの重複を最小限に抑えます。各パラメータ宣言からの複数の機能。バグが少ない
堅牢:本番用のコードを入手してください。自動インタラクティブドキュメント付き。
標準ベース:APIのオープン標準に基づいており(そして完全に互換性があります)、OpenAPI(以前はSwaggerとして知られていました)とJSONスキーマ。

Nodejsやgo言語に匹敵するパフォーマンスらしい。
Python3.6以降が必須

FastAPIの導入

自分はmac環境で導入しました。

必要条件

  • Python 3.6以降

インストール

pip install fastapi
pip install uvicorn

ファイルの作成

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

サーバー起動

uvicorn main:app --reload

アクセスしてみる

{ Hello: "World" }

{"item_id": 5, "q": "somequery"}

apiドキュメントも自動で生成される

alt

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
43