$ pipenv shell
$ pipenv install fastapi uvicorn
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]
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
http://localhost:8080/docs
http://localhost:8080/redoc
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