python fastapi - ghdrako/doc_snipets GitHub Wiki

FastAPI login in json: https://www.sheshbabu.com/posts/fastapi-structured-json-logging/

  • The FastAPI framework: pip install fastapi
  • The Uvicorn web server: pip install uvicorn
  • The HTTPie text web client: pip install httpie
  • The Requests synchronous web client package: pip install requests
  • The HTTPX synchronous/asynchronous web client package: pip install httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/hi")
def greet():
  return "Hello? World?"

FastAPI itself does not include a web server but recommends Uvicorn. You can start Uvicorn and the FastAPI web application in two ways: externally or internally.

 uvicorn hello:app --reload

Start Uvicorn internally

from fastapi import FastAPI
app = FastAPI()
@app.get("/hi")
def greet():
  return "Hello? World?"
if __name__ == "__main__":
  import uvicorn
  uvicorn.run("hello:app", reload=True)

Test /hi in the browser

http://localhost:8000/hi

Test /hi with Requests

>>> import requests
>>> r = requests.get("http://localhost:8000/hi")
>>> r.json()

Test /hi with HTTPX, which is almost identical to Requests

>>> import httpx
>>> r = httpx.get("http://localhost:8000/hi")
>>> r.json()

Automatic reload

version: "3.9"

services:
  people:
    container_name: people
    build: .
    working_dir: /code/app
    command: uvicorn main:app --host 0.0.0.0 --reload
    environment:
      DEBUG: 1
    volumes:
      - ./app:/code/app
    ports:
      - 8008:8000
    restart: on-failure

directory structure

.
├── Dockerfile
├── Makefile
├── app
│   └── main.py
├── docker-compose.yml
└── requirements.txt
docker-compose up --build