FastAPIのAPIを徹底解析!静的解析&動的解析で品質を強化する方法

[:contents] この記事は広告を含みます。

パリパリキュー

FastAPIで作成したAPIに対して、静的解析(コードの構造や品質を評価)と動的解析(実行時の挙動を分析)を実施する方法を紹介します。

kunio-ud-all.com


🔍 静的解析(Static Analysis)

静的解析では、コードの品質チェックや脆弱性診断を行います。

コード品質のチェック

コードのフォーマットや構造が適切かどうかを解析します。

🔹 lint(PEP8準拠チェック)

pip install flake8
flake8  ./app/

Flake8は、PEP8に基づくコード品質チェックを行うツールです。

お問い合わせAPIに対してやりました。以下が出ました。いいですね。pushする前とかに簡単にチェックできますね。

./app/main.py:10:1: E302 expected 2 blank lines, found 1 #改行2行必要
./app/main.py:15:1: E302 expected 2 blank lines, found 1 #改行2行必要
./app/main.py:43:5: F841 local variable 'e' is assigned to but never used #eを使え
./app/main.py:46:41: W292 no newline at end of file # 最後に改行を

🔹 型チェック(mypy)

FastAPIは型ヒントを多用するので、mypy を活用すると型の誤りを検出できます。

pip install mypy
mypy ./app/
app\main.py:3: error: Skipping analyzing "boto3": module is installed, but missing library stubs or py.typed marker  [import-untyped]
app\main.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 1 error in 1 file (checked 2 source files)

boto3のワーニングですね。

# mypy.ini
[mypy]
ignore_missing_imports = True

今回は、これで回避してゆきます。

🔹 自動フォーマット(black, isort)

フォーマットの統一にはblackisortを使うと便利です。

pip install black isort
black ./app/
isort ./app/

ほぼ、大丈夫だったのかな?

(venv) C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi>black ./app/
reformatted C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi\app\main.py

All done! ✨ 🍰 ✨
1 file reformatted, 1 file left unchanged.

(venv) C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi>isort ./app/
Fixing C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi\app\main.py

セキュリティ脆弱性の検査

APIのコードに脆弱性がないかを確認します。

🔹 bandit(Pythonの脆弱性スキャン)

pip install bandit
bandit -r ./app/

bandit は、セキュリティリスクの高いコードパターンをスキャンするツールです。

今回は大丈夫でした。

🔹 safety(依存関係の脆弱性チェック)

pip install safety
safety check

safety は、依存ライブラリにCVE(既知の脆弱性)がないかチェックします。

-> Vulnerability found in pip version 24.3.1
   Vulnerability ID: 75180
   Affected spec: <25.0
   ADVISORY: Pip solves a security vulnerability that previously allowed maliciously crafted wheel files to
   execute unauthorized code during installation.
   PVE-2025-75180
   For more information about this vulnerability, visit https://data.safetycli.com/v/75180/97c
   To ignore this vulnerability, use PyUp vulnerability id 75180 in safety’s ignore command-line argument or add the   
   ignore to your safety policy file.

pipをアップグレードしました。

🔹 Semgrep(カスタマイズ可能な静的解析)

pip install semgrep
semgrep scan --config=auto

semgrep は、SQLインジェクションやXSSの脆弱性を含むコードを検出可能な強力なツールです。

┌──────────────┐
│ Scan Summary │
└──────────────┘
✅ Scan completed successfully.
 • Findings: 0 (0 blocking)
 • Rules run: 290
 • Targets scanned: 5
 • Parsed lines: ~100.0%
 • Scan was limited to files tracked by git
 • For a detailed list of skipped files and lines, run semgrep with the --verbose flag
Ran 290 rules on 5 files: 0 findings.
💎 Missed out on 1382 pro rules since you aren't logged in!
⚡ Supercharge Semgrep OSS when you create a free account at https://sg.run/rules.
(need more rules? `semgrep login` for additional free Semgrep Registry rules)


✨ If Semgrep missed a finding, please send us feedback to let us know!
   See https://semgrep.dev/docs/reporting-false-negatives/

🚀 動的解析(Dynamic Analysis)

動的解析では、APIを実行しながらパフォーマンス測定やセキュリティ診断を行います。

ユニットテスト & APIテスト

FastAPIでのテストには、pytest を活用できます。

🔹 ユニットテスト

pip install pytest httpx

テストスクリプト test_main.py の例:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_read_root():
    response = client.post(
        "/contact",
        json={
            "name": "test",
            "email": "test@test.test",
            "message": "test-test-test",
        }
    )
    assert response.status_code == 200
    assert response.json() == {"message": "お問い合わせを受け付けました"}

テスト実行:

pytest
(venv) C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi>pytest
================================================ test session starts =================================================
platform win32 -- Python 3.13.1, pytest-8.3.5, pluggy-1.5.0
rootdir: C:\Users\user\Documents\python\my-contact-form-fastapi\fastapi
plugins: anyio-4.9.0
collected 0 items                                                                                                     

=============================================== no tests ran in 0.03s ================================================ 

大丈夫そうです!!!


まとめ

解析タイプ 目的 ツール
静的解析 コード品質チェック flake8, mypy, black
依存関係の脆弱性検査 safety
コードのセキュリティ検査 bandit, semgrep
動的解析 ユニットテスト pytest

この流れでチェックを行えば、FastAPIのAPIをセキュアで高品質に保つことができるのでは💡💡💡