0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FastAPI勉強用(Router編)

0
Last updated at Posted at 2023-02-19

目的

FastAPIのRouter機能の勉強用

サンプルソース

初期設定のサンプルソースを以下のように追加

main.py
from fastapi import FastAPI
+from routers import user
+from routers import priv

app = FastAPI()
+app.include_router(user.router)
+app.include_router(priv.router)

@app.get("/")
async def root():
    return {"message": "Hello World2"}
$ mdkir routers
$ cd routers
$ touch __init__.py
$ vi users.py
$ vi priv.py
routers/user.py
from fastapi import APIRouter

router=APIRouter()

@router.get("/user/", tags=["user"])
async def user_list():
    return [{"account": "user1", "name_sei": "山田", "name_mei":"太郎"},
            {"account": "user2", "name_sei": "海野", "name_mei":"次郎"},
            {"account": "user3", "name_sei": "空野", "name_mei":"三郎"}]

@router.get("/user/{userid}", tags=["user"])
async def user_info(userid):
    return {"username": userid}
routers/priv.py
from fastapi import APIRouter

router=APIRouter()

@router.get("/priv/", tags=["priv"])
async def priv_list():
    return ["adviser", "student"]

確認

uvicornを再起動してブラウザで確認
https://IPアドレス/api/user/
https://IPアドレス/api/priv/

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?