こちらと同様の機能を FastAPI で実装します。
Nest.js で簡単な WebAPI を作成
サーバープログラム
get02.py
# ------------------------------------------------------------------
# get02.py
#
# Jun/08/2021
# ------------------------------------------------------------------
from fastapi import FastAPI
data = [
{'id': 't101', 'name': '草枕', 'author': '夏目漱石' },
{'id': 't102', 'name': '走れメロス', 'author': '太宰治' },
{'id': 't103', 'name': '千曲川のスケッチ', 'author': '島崎藤村' },
{'id': 't104', 'name': '高瀬舟', 'author': '森鴎外' }
]
app = FastAPI()
@app.get("/")
def say_hello():
return {"Hello": "World"}
@app.get("/test/")
def read_all():
return data
@app.get("/test/{item_id}")
def read_item(item_id: str):
unit_aa = [ss for ss in data if ss['id'] == item_id]
return unit_aa
# ------------------------------------------------------------------
サーバーの実行
uvicorn get02:app --reload
クライアントからアクセス
$ http http://127.0.0.1:8000
HTTP/1.1 200 OK
content-length: 17
content-type: application/json
date: Tue, 08 Jun 2021 05:01:39 GMT
server: uvicorn
{
"Hello": "World"
}
全件取得
$ http http://127.0.0.1:8000/test/
HTTP/1.1 200 OK
content-length: 241
content-type: application/json
date: Tue, 08 Jun 2021 05:02:05 GMT
server: uvicorn
[
{
"author": "夏目漱石",
"id": "t101",
"name": "草枕"
},
{
"author": "太宰治",
"id": "t102",
"name": "走れメロス"
},
{
"author": "島崎藤村",
"id": "t103",
"name": "千曲川のスケッチ"
},
{
"author": "森鴎外",
"id": "t104",
"name": "高瀬舟"
}
]
id を指定して取得
$ http http://127.0.0.1:8000/test/t102
HTTP/1.1 200 OK
content-length: 61
content-type: application/json
date: Tue, 08 Jun 2021 05:02:37 GMT
server: uvicorn
[
{
"author": "太宰治",
"id": "t102",
"name": "走れメロス"
}
]
確認したバージョン
$ python
Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fastapi
>>> fastapi.__version__
'0.91.0'