documents/dev/FastAPI.md
Table of Contents
Python FastAPI Server
Watch
sudo nodemon --ext 'py' --exec python3 fast-server.py
sudo nodemon --watch fast-server.py --ext 'py' --exec python3 fast-server.py
Start/stop
pid = str(os.getpid())
print('PID', pid)
with open('server.pid', 'w', encoding='utf-8') as f:
f.write(pid)
#!/bin/zsh
kill -9 `cat ./server.pid`
Example
from typing import List
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
# https://fastapi.tiangolo.com/tutorial/static-files/
app.mount("/static", StaticFiles(directory="Work"), name="static")
# https://fastapi.tiangolo.com/advanced/templates/
#templates = Jinja2Templates(directory="templates")
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = 0.0
# Database mockup
items_db = []
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
items_db.append(item)
return item
@app.get("/")
async def read_root():
html_content = """
<html>
<head>
<title>Some HTML in here</title>
</head>
<body>
<h1>Look ma! HTML!</h1>
</body>
</html>
"""
return HTMLResponse(content=html_content, status_code=200)
@app.get("/test/")
async def test_path():
return {"message": "Welcome to FastAPI"}
@app.get("/items/", response_model=List[Item])
async def read_items():
return items_db
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=80)