0
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 3 years have passed since last update.

FastAPI使ってみた

0
Posted at

はじめに

PythonのフレームワークのFastAPIを使って
簡単なWEBアプリを作成してみました

環境

Python:3.10
pip:22.3.1
pipenv:version 2022.12.19
flake8:6.0.0 ←任意

環境構築

今回はpipenvを使用して仮想環境で構築していきます

pipenvをインストールしていない方はインストールしてください

pip install pipenv

ワークディレクトリを作成して初期化を実行します

pipenv --python 3

パッケージをインストールしていきます

pipenv install fastapi starlette uvicorn

仮想環境に入ります

pipenv shell

コード

main.pyを作成し、下記のコードを打ち込みます

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

下記が出力されれば成功です

$ uvicorn main:app --reload
INFO:     Will watch for changes in these directories: ['/Users/div/fastapi-sample']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [20485] using StatReload
INFO:     Started server process [20488]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

http://127.0.0.1:8000 にアクセスし(@app.get("/"))、
画面に{"Hello": "World"}が表示されます

http://127.0.0.1:8000/items/5?q=somequery にアクセスすると(@app.get("/items/{item_id}"))
以下のレスポンスが表示されます
{"item_id": 5, "q": "somequery"}

備考

コードやコマンドは下記より引用しています。
FastAPIの詳しい内容は公式Docをご確認ください。

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