1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FastAPI: 簡単な WebAPI を作成

Last updated at Posted at 2021-06-08

こちらと同様の機能を 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'
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?