3
2

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

Posted at

環境準備

$ pipenv shell
$ pipenv install fastapi uvicorn

ソースコード

ポイントは、

  • GET
    • パスパラメーター
  • POST
    • ボディの受け取り方
main.py
from fastapi import FastAPI
from pydantic import BaseModel
import dataclasses
import uuid

class UserInput(BaseModel):
    name: str

@dataclasses.dataclass
class User:
    id: str
    name: str

data = dict()

app = FastAPI()

@app.post("/users/")
async def create_user(user_input: UserInput) -> User:
    user_id = str(uuid.uuid4())
    user = User(user_id,user_input.name)
    global data
    data[user_id] = user
    print(user_id)
    return user

@app.get("/users/{user_id}")
async def read_user(user_id: str) -> User:
    return data[user_id]

@app.delete("/users/{user_id}")
async def delete_user(user_id: str) -> None:
    del data[user_id]

起動の仕方

ポイントは

  • ポート番号の指定
  • ホスト名の指定

ホスト名の指定をしないとドメイン指定等、公開するときにハマる。

$ uvicorn main:app --port=8080 --host=0.0.0.0

開発用はreloadをつける。

$ uvicorn main:app --reload --port=8080 --host=0.0.0.0

動作確認

image.png

image.png

コンテナ化

Dockerfile
FROM python:3.6-slim

COPY Pipfile .
COPY Pipfile.lock .

RUN pip install pipenv --no-cache-dir
RUN pipenv sync --system  

COPY main.py .
CMD pipenv run uvicorn main:app --port=8080 --host=0.0.0.0
$ docker build -t fastapi_test .
$ docker run --rm -p 8080:8080 fastapi_test
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?