0
0

【備忘録 #3】FastAPIの基本

Posted at

■概要

上記動画を学習したので、
備忘録として残します。

■Pythonの型ヒント

下記のように、型情報を記述することができる。

num: int = 3
def add(a: int, b: int) -> int:
    return a+b

リスト、辞書の場合

from typing import List, Dict

sample_list: List[str] = ["helllo world", "hogehoge"]
sample_dic: Dict[str, int] = {"hoge":4}

■FastAPI起動

「/」にアクセスした際にindex関数を実行する。

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/hello{show_str}")
async def hello(show_str: str):
    return {"message": show_str}

上記ファイル作成後、以下コマンド実行でサーバー起動

uvicorn main:app --reload

起動すると、http://+ IPアドレス +:8000 でサーバー起動します。

必須ではないパラメータの場合、
ファイル先頭にfrom typing import Optionalと記述し、
変数をcountry_name: Optional[str] = Noneとすると
そのパラメータは必須ではなくなる。

from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/countries/")
async def country(country_name: Optional[str] = None, country_no: Optional[int] = None):
    return {
        "country_name": country_name,
        "country_no": country_no
    }

ドキュメントの自動生成

起動したサーバーのURL + /docs
もしくはURL + /redocにアクセスすると
ドキュメントが自動生成されています。
凄すぎる!

◯/docs
image.png

◯/redoc
image.png

0
0
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
0
0