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

FastAPI の使い方

Last updated at Posted at 2021-06-04

FastAPI の使い方です。

参考ページ
FastAPI

インストール

Arch Linux でのインストール

sudo pacman -S python-fastapi
sudo pacman -S uvicorn

Ubuntu でのインストール

sudo apt install python3-fastapi
sudo apt install uvicorn

サンプル その1

main.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

サーバーの実行

uvicorn main:app --reload

クライアントでアクセス

$ http http://127.0.0.1:8000
HTTP/1.1 200 OK
content-length: 17
content-type: application/json
date: Fri, 04 Jun 2021 07:29:36 GMT
server: uvicorn

{
    "Hello": "World"
}

サンプル その2

ex01.py
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
	rvalue = {"morning": "おはよう","afternoon": "こんにちは"}
	return rvalue


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
	return {"item_id": item_id, "q": q}

サーバーの実行

uvicorn ex01:app --reload

クライアントでアクセス

$ http http://127.0.0.1:8000
HTTP/1.1 200 OK
content-length: 56
content-type: application/json
date: Fri, 04 Jun 2021 07:31:18 GMT
server: uvicorn

{
    "afternoon": "こんにちは",
    "morning": "おはよう"
}

確認したバージョン

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

関連ページ

FastAPI: GET の引数の処理
FastAPI: POST の引数の処理

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