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?

FastAPI: JSON ファイルを読む

Last updated at Posted at 2022-07-26

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

確認したバージョン

$ python
Python 3.12.7 (main, Feb  4 2025, 14:46:03) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fastapi
>>> fastapi.__version__
'0.110.3'
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?