0
0

A summary of the basic usage of FastAPI [Super beginner]

Last updated at Posted at 2024-02-02

FastAPI とは?

  • Python 3.6以降でAPIを構築するための、モダンで高速なWebフレームワーク
  • 使いやすい: Pythonの標準である型ヒントに基づいており、コードが読みやすく、理解しやすい
  • 開発時間の短縮: FastAPIは使いやすく、コード量も少ないため、開発時間を短縮できる

型ヒント(type hints)

type_hints.py
# Nomal
price = 100
tax = 1.1

def calc_price_including_tax(price, tax):
    return int(price*tax)

if __name__=='__main__':
    print(f'{calc_price_including_tax(price=price, tax=tax)}')

# type hints 型ヒントは、変数や関数の引数、戻り値の型を宣言するための機能

price: int = 100
tax: float = 1.1

def calc_price_including_tax(price: int, tax: float) -> int:
    return int(price*tax)

if __name__=='__main__':
    print(f'{calc_price_including_tax(price=price, tax=tax)}')

# from typing は、Python のコードで型ヒントを使用するために必要なモジュール
from typing import List, Dirt

sample_list: List[int] = [1, 2, 3, 4]
sample_dict: Dict[string, string] = ['username': 'abcd']

必要なライブラリをインストール

pip3 install fastapi
pip3 install uvicorn

FastAPIを起動する

uvicorn main:app --reload
main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def index():
    return {"message": "Hello World"}

APIドキュメントの自動生成

Swagger UI

  • Swagger UI とは、Swagger Specification(OpenAPI Specification) で記述された API のドキュメントを視覚的に表示・検証できるオープンソースツールのこと

パスパラメータ

type_hints.py
# パスパラメータ 1
from fastapi import FastAPI

app = FastAPI()

@app.get("/contries/{country_name}")
async def country(contry_name: int):
    return {"contry_name": contry_name}

# パスパラメータ 2
from fastapi import FastAPI

app = FastAPI()

@app.get("/contries/japan}")
async def japan():
    return {"message": 'This is Japan!'}

@app.get("/contries/{country_name}")
async def country(country_name: str):
    return {"country_name": country_name}

クエリパラメータ

type_hints.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/contries/")
async def country(country_name: str, country_no: int):
    return {
        "country_name": country_name,
        "country_no": country_no
        }

パスパラメータ + エリパラメーター

type_hints.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/contries/{country_name}")
async def country(country_name: str='japan', city_name: str='tokyo'):
    return {
        "country_name": country_name,
        "city_no": city_name
        }

Reference site

【FastAPI超入門】直感的にWeb API開発ができるモダンなPython WebフレームワークFastAPIの基礎を80分でマスター

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