0
0

More than 1 year has passed since last update.

FastAPI: JSON ファイルを読む

Posted at

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