# 高木研 勉強会資料 ~API開発~ ## APIについて ### API(Application Programming Interface)とは ソフトウェアのインターフェースの1つであり、Web(HTTPプロトコル)を介して、機能実行やデータ処理を行える仕組み。 ### エンドポイントとは APIの1つの機能のことをエンドポイントと言い、RestAPIでは、それぞれRestメソッドを定義する(俗に言うRest設計)。エンドポイントでは、アクセス先のURLやパラメータ、返却値を設定する。 * Rest設計 |メソッド|役割| |---|---| |GET|データの取得| |POST|データの追加| |PUT|データの更新| |DELETE|データの削除| ### パラメータについて パラメータは、APIの入力値のことを指す。FastAPIではパスパラメータとクエリパラメータの2種類存在する。 パスパラメータは、URLのパスに含まれるパラメータであり、IDやNameなどの条件を指定することが多い。クエリパラメータはクエリ(`?q=hoge`など)でパラメータを指定するものであり、検索キーワードの条件等を指定することが多い。 ## プロジェクト作成 * [poetry](https://cocoatomo.github.io/poetry-ja/) * プロジェクト管理を行うためのツール。ライブラリーのバージョン管理や静的解析の設定、プロジェクト実行を行うコトが可能。 * `poetry`のインストール ```shell $ pip install --user poetry ``` * プロジェクト作成 ```shell $ poetry new [プロジェクト名] ``` * 以下のディレクトリー構造に変更 ``` . ├── README.rst ├── app │ ├── __init__.py │ ├── features │ │ └── practic_end_point.py │ ├── main.py │ └── router │ └── functions.py ├── pyproject.toml └── tests ├── __init__.py └── test_practice_api.py ``` * コマンドでディレクトリ構造を作成する場合 ```shell $ mkdir app $ mkdir -p app/features $ mkdir -p app/router $ touch app/main.py $ touch app/features/practic_end_point.py $ touch app/router/function.py ``` ## ライブラリーのインストール * [fastapi](https://fastapi.tiangolo.com/ja/) APIを構築するためのWebフレームワーク。PythonのWebフレームワークの中ではパフォーマンスが高く、Pythonフレームワークの中では最も高速な処理が可能(NodeJS、Go並み)。また、ドキュメントも生成可能。 * インストール ```shell $ poetry add fastapi ``` * [uvicorn](https://www.uvicorn.org/) 非同期Webアプリケーションを実行するためのライブラリー。ASGIサーバーを利用しており。軽量で高速な処理を可能にしている。 * インストール ```shell $ poetry add uvicorn ``` * `pyproject.toml`が以下のようになっていればOK ```toml [tool.poetry] name = "practice_api" version = "0.1.0" description = "" authors = ["IshigamiRyoichi <ryoichi20001118@gmail.com>"] [tool.poetry.dependencies] python = "^3.10" fastapi = "^0.115.4" uvicorn = "^0.32.0" [tool.poetry.dev-dependencies] pytest = "^5.2" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" ``` ## APIの実装 & 起動 ### 実装 * app/main.py APIを起動するコードになります。エンドポイントを読み込み、サーバーを起動する役割を担っています。 ```python= from fastapi import FastAPI from router import functions app = FastAPI() app.include_router(functions.router, prefix="/v1") ``` * router/functions.py APIのエンドポイントを設定するコードになります。URLと返却値を設定を行っています。高木研の研究では、`features`に処理スキームを記述し、`router/functions.py`から関数やクラスを呼び出す設計にしています。 ```python= from fastapi import APIRouter # ルートの設定 router = APIRouter( prefix="/practice", tags=["practice"] ) # ヘルスチェックのエンドポイント @router.get("/health_check") async def health_check(ここに引き数を指定することでパラーメータ設定可能): return { "check":"health" } ``` ### 起動 * 実行ディレクトリの移動 ```bash $ cd app ``` * APIの起動 ```bash $ poetry run uvicorn main:app --reload ``` * http://127.0.0.1:8000/docs# にアクセス ## オリジナルエンドポイントの実装 * `features/practic_end_point.py`に`search_age`という関数を作成 * 生まれ年を受けたったら、年齢を返す関数を実装しよう * `search_age`の例 ```python from datetime import datetime from typing import Dict async def search_age(year:int) -> Dict[str, int]: current_year = datetime.now().year age = current_year - year return { "age":age } ``` * `router/functions.py`にエンドポイントを設定 * メソッドは`Get`、パラメータを`year`で実装 * 作成したモジュールを取得する。`features/practice_end_point.py`の`search_age`を取得する場合、以下のように記述する。 ```python from features.practic_end_point import search_age ``` * エンドポイントは以下のように記述する。(URL:search_age, Client_pram:yearの場合) ```python @router.get("/search_age") async def get_age(year: int): return await search_age(year) ```