files にある cities.json を読むサンプルです。
ツリー構造
$ tree
.
├── files
│ └── cities.json
└── main.py
main.py
#
# main.py
#
# Jul/26/2022
# ------------------------------------------------------------------
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse
# ------------------------------------------------------------------
app = FastAPI()
@app.get("/")
def read_root():
rvalue = {"morning": "おはよう","afternoon": "こんにちは"}
return rvalue
@app.get("/get_file/{filename:path}")
async def get_file(filename: str):
current = Path()
file_path = current / "files" / filename
response = FileResponse(path=file_path)
return response
# ------------------------------------------------------------------
サーバーの起動
uvicorn main:app --reload
クライアントでアクセス
http http://localhost:8000/get_file/cities.json