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?

[Python]FastAPIの基本構造とひな形

Last updated at Posted at 2025-04-15

はじめに

 Pythonを用いた簡易的な画面表示として、別アプリとも連携可能なFastAPIが一般的に利用されているらしく、GPT4oを用いてFastAPIプログラムを作成した。
 今回その内容をもとに、基本的な構造やファイルの役割、型を備忘録としてまとめていく。FastAPIについて詳細説明をしているサイトは多々あるが、細かすぎて実際に構築するにあたり情報整理に労力がとられてしまうため、構築するにあたっての最低限度の内容を記載する。

FASTAPIの基本

基本構造

image.png

.app
├─.api
|  └─XX.py ← APIルーター(POST/GETなどの入口)
├─.services
|  └─YY.py ← 処理ロジック(サービス層)
├─.db
|  └─zz.py(必要に応じて)
└main.py

役割

①main.py
他のアプリから呼び出しを受ける玄関口。
ルーターとしてグループ分けされた各機能を呼び出すためのもの。

②.api
実際にAPIが呼びだれたとき、GET,POSTのレスポンスを定めている。

③.services
GET,POSTのレスポンスをするにあたり、レスポンスするための具体的な処理(裏方の実装)を行っている。

④.db
.servicesの機能と、必要に応じてやり取りをするDB。

ひな型

main.py
from fastapi import FastAPI
from app.api import XX  

app = FastAPI()

# ルーターをFastAPI本体に登録
app.include_router(XX.router)

.api
from fastapi import APIRouter
from app.services.YY import 関数名

router = APIRouter(tags=["タグ名"])

@router.post(
    "/URLの末尾",
    summary="概要説明",
    description="詳細説明"
)
async def 関数名(代数):
    result = await 関数名(引数)  # ← services層の関数呼び出し
    return result


@router.get(
    "/URLの末尾",
    summary="概要説明",
    description="詳細説明"
)
async def 関数名(引数):
    result = await 関数名(引数)  # ← 同上
    return result
.services
async def 関数名(引数):
    # ここでデータベースアクセス・前処理・変換などを実施
    result = ... 
    return result

参考資料

[1]iharu , 『Pythonのasync/awaitを理解したい【asyncio】』, https://zenn.dev/iharuoru/articles/45dedf1a1b8352
[2]徳田 啓 , 『GET/POSTの違い&実際の使い分け方』, https://blog.senseshare.jp/get-post-method.html
[3]tiangolo, 『FastAPI』, https://fastapi.tiangolo.com/

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?