[PYTHON] Fast API that stands up quickly

Environmental preparation

$ pipenv shell
$ pipenv install fastapi uvicorn

Source code

The point is

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]

How to start

The point is

--Specify port number --Specify host name

If you do not specify the host name, you will be addicted to publishing, such as specifying the domain.

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

Add reload for development.

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

Operation check

http://localhost:8080/docs

image.png

http://localhost:8080/redoc

image.png

Containerization

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

Recommended Posts

Fast API that stands up quickly
Zabbix API this and that