0
1

More than 1 year has passed since last update.

40代おっさんFastAPIを勉強する

Last updated at Posted at 2022-11-09

本記事について

この記事はプログラミング初学者の私が学んでいく中でわからない単語や概要を分かりやすくまとめたものです。
もし不正などありましたらコメントにてお知らせいただければ幸いです。

getでFastAPIを動かす

from fastapi import FastAPI

app = FastAPI()

@app.get("/") # getで / にアクセスがあったら下の関数を実行
async def index(): # asyncで非同期処理を実装できる
    return {"message": "利樹大好き"}

サーバー起動(main.py)

uvicorn main:app --reload

{"message":"利樹大好き"}

となっていれば成功

local hostに/docsをつけると
ドキュメントが見られる。
Swagger UIが使われている。
FastAPIはSwagger UIを自動生成している。

local hostに/redocをつけると
redocベースのドキュメントが見られる。

パスパラメーター

from fastapi import FastAPI

app = FastAPI()

@app.get("/name/{name}") # {name}の部分がパスパラメーター
async def name(name): # パスパラメーターの部分が変数として渡される
    return {"name": name}

文字列型で受け取る

from fastapi import FastAPI

app = FastAPI()

@app.get("/name/{name}")
async def name(name: str): # string型で受け取っている。
    return {"name": name}

これが仮に

from fastapi import FastAPI

app = FastAPI()

@app.get("/name/{name}")
async def name(name: int): # int型で受け取っている。
    return {"name": name}

{"detail":[{"loc":["path","name"],"msg":"value is not a valid integer","type":"type_error.integer"}]}

とエラーが出る。

*string型にしていると数字の1を入れても、文字列の1として見てしまう
 また複数@app.get("/name/")があった場合は順番に注意

クエリパラメーター

URLの?以降の物

https://twitter.com/search?q=Python&src=typed_query

&でつなげることができる

from fastapi import FastAPI

app = FastAPI()

@app.get("/name/")
async def name(name: str, number: int): # =''でデフォルトの値
    return {
        "name": name,
        "number": number
    }

http://127.0.0.1:8000/name/?name=あっきー&number=2

にすると

{"name":"あっきー","number":2}

と表示される

*クエリパラメーター設置してもし?name=あっきー&number=2がない場合はエラーになる。

from typing import Optional # インポート
from fastapi import FastAPI

app = FastAPI()

@app.get("/name/")
#  Optional[] = Noneで必須項目でなくなりエラー回避できる。
async def name(name: Optional[str] = None, number: Optional[int] = None): 
    return {
        "name": name,
        "number": number
    }

{"name":null,"number":null}
になる。

参考

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