Extend the app
On this page you add a /users resource to shop: first by hand in the single main.py, then in a layered project with fastkit addroute. You learn how FastAPI splits an application into routers (APIRouter and include_router), how dependencies (Depends) hand objects to endpoints, how settings come from environment variables and .env, and what the CORS middleware does.
Add /users by hand
The quickest way to add an endpoint is to copy one that works. In the hello project from Generate, copy the Item models and the two item endpoints to the end of main.py, and rename them for users:
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str = Field(min_length=3, max_length=254)
class StoredUser(User):
id: int
users: dict[int, StoredUser] = {}
@app.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(user: User) -> StoredUser:
stored = StoredUser(id=len(users) + 1, **user.model_dump())
users[stored.id] = stored
return stored
@app.get("/users/{user_id}")
async def read_user(user_id: int) -> StoredUser:
if user_id not in users:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="User not found")
return users[user_id]
In tests/test_main.py, change the import to from main import app, items, users, add users.clear() after each items.clear() in the empty_store fixture, and add two tests at the end:
ADA = {"name": "Ada", "email": "ada@example.com"}
def test_create_user_returns_it_with_a_new_id() -> None:
response = client.post("/users", json=ADA)
assert response.status_code == 201
assert response.json() == {**ADA, "id": 1}
def test_read_user_that_does_not_exist() -> None:
response = client.get("/users/42")
assert response.status_code == 404
assert response.json() == {"detail": "User not found"}
When one file is not enough
fastkit addroute adds a resource for you, but it needs packages to put the new modules in. In the hello project it refuses and tells you why:
$ fastkit addroute users .
╭───────────────────────────────── Error ──────────────────────────────────╮
│ ❌ This project keeps its whole application in main.py, so there is no │
│ package to add route modules to. Add the endpoint to main.py by hand, │
│ next to the existing ones (copy one endpoint and its test), or create a │
│ project at a later level with `fastkit init --level layered` (`fastkit │
│ list-templates` lists the templates). │
╰──────────────────────────────────────────────────────────────────────────╯
The layered level splits the application into packages: routes, data access (crud), schemas and core settings. fastkit does not convert a project to another level, so create a new one outside the hello project's folder (a shop folder must not exist yet). -y accepts every default without asking:
$ fastkit init --level layered --name shop -y
...
$ cd shop
$ find src -name '*.py' -not -name '__init__.py' | sort
src/api/api.py
src/api/deps.py
src/api/routes/items.py
src/core/config.py
src/core/pagination.py
src/core/responses.py
src/crud/items.py
src/main.py
src/schemas/items.py
The items now live in the file src/mocks/mock_items.json, so they survive a restart, and every endpoint is under /api/v1, as in /api/v1/items.
Routers and dependencies
An APIRouter is a group of path operations that you write in its own module, with @router.get(...) instead of @app.get(...). src/api/routes/items.py creates one with APIRouter(prefix="/items", tags=["items"]); the prefix and the tag apply to each of its endpoints. include_router adds a router's endpoints to another router or to the app. src/api/api.py collects the router of every resource:
# One APIRouter collects the routers of every module; main.py mounts it once.
# https://fastapi.tiangolo.com/tutorial/bigger-applications/
api_router = APIRouter()
api_router.include_router(items.router)
# fastkit:routes
src/main.py then mounts it once with app.include_router(api_router, prefix=settings.API_V1_PREFIX). The # fastkit:imports and # fastkit:routes comments in both files mark where fastkit addroute adds its lines; keep them.
A dependency is a function that FastAPI calls before your endpoint; the endpoint receives what it returns. You declare it with Depends(...), and an Annotated alias lets every endpoint reuse it:
def get_item_store() -> ItemStore:
"""Return the item store (tests override this dependency)."""
return item_store
# ...
ItemStoreDep = Annotated[ItemStore, Depends(get_item_store)]
Each item endpoint declares store: ItemStoreDep, as in def get_item(item_id: int, store: ItemStoreDep) -> ItemRead. Because no endpoint creates the store itself, the tests can replace get_item_store with a store of their own (Test the app shows how).
Settings and CORS
Settings are values that change between machines, such as a secret key or the allowed origins. A pydantic-settings BaseSettings class reads each field from an environment variable of the same name or from the .env file, and falls back to the default:
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_ignore_empty=True,
extra="ignore",
)
fastkit wrote .env with a unique SECRET_KEY. Git ignores .env; .env.example lists every setting for the next person. One of them is BACKEND_CORS_ORIGINS. When a web page from another origin (scheme, host and port) calls the API, the browser reads the API's CORS headers and decides whether the page may read the response. The CORS middleware sends those headers for the origins you list, for example BACKEND_CORS_ORIGINS=http://localhost:3000 in .env; src/main.py installs it only when the list is not empty. CORS is not authentication: it does not stop other clients, such as curl or another server, from calling the API.
Add users with fastkit
--dry-run lists what fastkit addroute would write; --diff also prints each change:
$ fastkit addroute users . --dry-run
...
Files to create (4):
+ src/api/routes/users.py
+ src/crud/users.py
+ src/schemas/users.py
+ tests/test_users.py
Files to modify (2):
~ src/api/deps.py
~ src/api/api.py
...
Run it again without --dry-run and confirm. The new resource has a paginated list, create (201), get, replace (PUT), update (PATCH) and delete (204) under /api/v1/users, and tests for each. Its schemas start with a name and a description; edit src/schemas/users.py for your own fields. src/api/api.py gets the router's import and include_router line below the two markers, and src/api/deps.py gets the new dependency alias, which src/api/routes/users.py imports:
from src.crud.users import UserRepository, get_user_repository
# ...
UserRepositoryDep = Annotated[UserRepository, Depends(get_user_repository)]
uv run pytest -q now reports 91 passed: the 74 tests the project shipped with and 17 new ones in tests/test_users.py.
Between hello and layered there is the single-file level: the whole application in one src/main.py with settings and tests. There, fastkit addroute adds the api, crud, schemas and core packages around src/main.py the first time you use it.
FastAPI documentation
Next
Test the app reads the tests of the layered project and writes a new one.