When learning FastAPI this is where I started. With this Medium.com post by Douwe van der Meij. I don’t know the guy but I love the guy! Thank you Douwe, I hope I get to buy you a hot cup of coffee soon.

app/main.py

from app.adapter.inmemory_vote_repository import InMemoryVoteRepository
from app.domain.vote import Vote

from fastapi import FastAPI

app = FastAPI()

vote_repository = InMemoryVoteRepository()

@app.post("/vote", response_model=Vote)
def vote() -> Vote:
    return Vote().save(vote_repository)

@app.get("/votes", response_model=int)
def votes() -> int:
    return vote_repository.total()

Source for app/main.py code::

Hexagonal Architecture in Python

app/routers/users.py is a router

See topography of the project first::

├── app                  # "app" is a Python package
│   ├── __init__.py      # this file makes "app" a "Python package"
│   ├── main.py          # "main" module, e.g. import app.main
│   ├── dependencies.py  # "dependencies" module, e.g. import app.dependencies
│   └── routers          # "routers" is a "Python subpackage"
│   │   ├── __init__.py  # makes "routers" a "Python subpackage"
│   │   ├── items.py     # "items" submodule, e.g. import app.routers.items
│   │   └── users.py     # "users" submodule, e.g. import app.routers.users
│   └── internal         # "internal" is a "Python subpackage"
│       ├── __init__.py  # makes "internal" a "Python subpackage"
│       └── admin.py     # "admin" submodule, e.g. import app.internal.admin

Now see app/router/users.py

from fastapi import APIRouter

router = APIRouter()

@router.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "Rick"}, {"username": "Morty"}]

@router.get("/users/me", tags=["users"])
async def read_user_me():
    return {"username": "fakecurrentuser"}

@router.get("/users/{username}", tags=["users"])
async def read_user(username: str):
    return {"username": username}

Source of app/router/users.py::

Bigger Applications - Multiple Files - FastAPI

Adapters

CORS - Cross Origin Resource Sharing

Middleware in WebDev and an example.