Adding Routes
Learn how to add new API routes to your existing FastAPI project.
Choose the route layout
addroute accepts --layout=classic-layer or --layout=domain. When omitted,
it reads [tool.fastapi-fastkit].preset: domain-starter selects domain;
classic-layered, minimal, and single-module select classic-layer.
If preset is missing, it infers the preset from template, so projects created
with startdemo or interactive init also select domain for
fastapi-domain-starter. Without either value, it selects classic-layer. An unknown preset falls back to classic-layer with
a warning. An explicit option overrides this selection without changing the
project's metadata.
$ cd my-api
$ fastkit addroute users . --layout=domain
$ fastkit addroute products . --layout=classic-layer
The selected layout is displayed before confirmation. Files are placed under
the application's actual package (src/ or src/app/), using its recorded
entrypoint when available.
Generate a domain CRUD
For a domain-starter project, simply run:
This creates the following files and registers the domain router automatically:
src/app/domains/users/
├── __init__.py
├── models.py # Users(id: int, name: str)
├── schemas.py # UsersCreate for POST/PUT, UsersRead for responses
├── repository.py # typed CRUD operations and in-memory storage
├── service.py # business logic and UsersNotFoundError
└── router.py # HTTP endpoints and overridable service dependency
The classes are named Users, UsersCreate, UsersRead, UsersRepository,
and UsersService within each domain; class names use PascalCase (health_checks becomes HealthChecks), without singularization.
The repository assigns IDs starting at 1. POST and PUT require a name between
1 and 120 characters; PUT preserves the existing ID.
| Method | Domain path | Result |
|---|---|---|
| GET | /users |
List entities, 200 |
| GET | /users/{entity_id} |
Read entity, 200 or 404 |
| POST | /users |
Create entity, 201 |
| PUT | /users/{entity_id} |
Replace entity, 200 or 404 |
| DELETE | /users/{entity_id} |
Delete entity, empty 204 or 404 |
The domain prefix and tags are set in the shared API router when it calls
include_router, as in the classic layout.
The application's existing API prefix remains in effect (for example,
/api/v1/users). Domain routes do not include PATCH.
The generated repository is self-contained and locks its CRUD operations. Its
default instance is shared between requests within this domain and process.
Data is lost on restart and is not shared between worker processes. Adapt the
repository for durable persistence; it has no dependency on the starter's
db.memory, ORM, or database configuration.
For isolated tests, inject a fresh UsersRepository into UsersService,
then override the router's get_users_service FastAPI dependency.
UsersRepository.reset() clears that repository and restarts IDs at 1.
service.reset_store() resets the default repository shared between requests.
Explicitly created repository instances have independent storage.
Re-running the command
Existing module files are preserved; missing files are created. Imports and
router registrations are not duplicated. Same-named modules in different layouts
can coexist; import aliases avoid Python name collisions. HTTP method/path
conflicts are not checked by the generator. --layout does not migrate existing
modules.
Basic Route Addition
The following examples describe the classic-layer layout. Pass
--layout=classic-layer explicitly when using a domain-starter project.
Using the addroute Command
FastAPI-fastkit's addroute command makes it easy to add new routes:
$ fastkit addroute users my-awesome-api
Adding New Route
┌──────────────────┬──────────────────────────────────────────┐
│ Project │ my-awesome-api │
│ Route Name │ users │
│ Target Directory │ ~/my-awesome-api │
└──────────────────┴──────────────────────────────────────────┘
Do you want to add route 'users' to project 'my-awesome-api'? [Y/n]: y
╭──────────────────────── Info ────────────────────────╮
│ ℹ Updated main.py to include the API router │
╰──────────────────────────────────────────────────────╯
╭─────────────────────── Success ───────────────────────╮
│ ✨ Successfully added new route 'users' to project │
│ `my-awesome-api` │
╰───────────────────────────────────────────────────────╯
What Gets Created
When you add a route, FastAPI-fastkit automatically creates:
1. Route File: src/api/routes/users.py
from typing import List
from fastapi import APIRouter, HTTPException, status
from src.schemas.users import User, UserCreate, UserUpdate
from src.crud.users import users_crud
router = APIRouter()
@router.get("/", response_model=List[User])
def read_users():
"""Get all users"""
return users_crud.get_all()
@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate):
"""Create a new user"""
return users_crud.create(user)
@router.get("/{user_id}", response_model=User)
def read_user(user_id: int):
"""Get a specific user"""
user = users_crud.get_by_id(user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
@router.put("/{user_id}", response_model=User)
def update_user(user_id: int, user: UserUpdate):
"""Update a user"""
updated_user = users_crud.update(user_id, user)
if updated_user is None:
raise HTTPException(status_code=404, detail="User not found")
return updated_user
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
"""Delete a user"""
success = users_crud.delete(user_id)
if not success:
raise HTTPException(status_code=404, detail="User not found")
2. CRUD Operations: src/crud/users.py
from typing import List, Optional
from src.schemas.users import User, UserCreate, UserUpdate
class UsersCRUD:
def __init__(self):
self._users: List[User] = []
self._next_id = 1
def get_all(self) -> List[User]:
"""Get all users"""
return self._users
def get_by_id(self, user_id: int) -> Optional[User]:
"""Get user by ID"""
return next((user for user in self._users if user.id == user_id), None)
def create(self, user: UserCreate) -> User:
"""Create a new user"""
new_user = User(
id=self._next_id,
title=user.title,
description=user.description
)
self._next_id += 1
self._users.append(new_user)
return new_user
def update(self, user_id: int, user: UserUpdate) -> Optional[User]:
"""Update an existing user"""
existing_user = self.get_by_id(user_id)
if existing_user:
update_data = user.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(existing_user, field, value)
return existing_user
return None
def delete(self, user_id: int) -> bool:
"""Delete a user"""
user = self.get_by_id(user_id)
if user:
self._users.remove(user)
return True
return False
users_crud = UsersCRUD()
3. Pydantic Schemas: src/schemas/users.py
from typing import Optional
from pydantic import BaseModel
class UserBase(BaseModel):
title: str
description: Optional[str] = None
class UserCreate(UserBase):
pass
class UserUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
class User(UserBase):
id: int
class Config:
from_attributes = True
4. Router Registration
The command automatically updates src/api/api.py to include the new router:
from fastapi import APIRouter
from src.api.routes import items, users
api_router = APIRouter()
api_router.include_router(items.router, prefix="/items", tags=["items"])
api_router.include_router(users.router, prefix="/users", tags=["users"])
Generated API Endpoints
After adding the users route, you'll have these endpoints:
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/v1/users/ |
Get all users |
POST |
/api/v1/users/ |
Create a new user |
GET |
/api/v1/users/{user_id} |
Get a specific user |
PUT |
/api/v1/users/{user_id} |
Update a user |
DELETE |
/api/v1/users/{user_id} |
Delete a user |
Testing Your New Routes
1. Start the Server
2. Check API Documentation
Visit http://127.0.0.1:8000/docs to see your new endpoints in the interactive documentation.
3. Test with curl
Create a user:
Get all users:
Get a specific user:
Customizing Generated Code
The generated code is fully customizable. Here are common modifications:
1. Enhanced User Schema
Modify src/schemas/users.py for more realistic user data:
from typing import Optional
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field
class UserBase(BaseModel):
email: EmailStr
username: str = Field(..., min_length=3, max_length=50)
full_name: Optional[str] = None
is_active: bool = True
class UserCreate(UserBase):
password: str = Field(..., min_length=8)
class UserUpdate(BaseModel):
email: Optional[EmailStr] = None
username: Optional[str] = Field(None, min_length=3, max_length=50)
full_name: Optional[str] = None
is_active: Optional[bool] = None
class User(UserBase):
id: int
created_at: datetime
class Config:
from_attributes = True
class UserInDB(User):
hashed_password: str
2. Enhanced CRUD with Validation
Update src/crud/users.py with better validation:
from typing import List, Optional
from datetime import datetime
import hashlib
from src.schemas.users import UserCreate, UserUpdate, UserInDB
class UsersCRUD:
def __init__(self):
self._users: List[UserInDB] = []
self._next_id = 1
def _hash_password(self, password: str) -> str:
"""Simple password hashing (use bcrypt in production)"""
return hashlib.sha256(password.encode()).hexdigest()
def get_by_email(self, email: str) -> Optional[UserInDB]:
"""Get user by email"""
return next((user for user in self._users if user.email == email), None)
def get_by_username(self, username: str) -> Optional[UserInDB]:
"""Get user by username"""
return next((user for user in self._users if user.username == username), None)
def create(self, user: UserCreate) -> UserInDB:
"""Create a new user with validation"""
# Check for duplicates
if self.get_by_email(user.email):
raise ValueError("Email already registered")
if self.get_by_username(user.username):
raise ValueError("Username already taken")
new_user = UserInDB(
id=self._next_id,
email=user.email,
username=user.username,
full_name=user.full_name,
is_active=user.is_active,
created_at=datetime.now(),
hashed_password=self._hash_password(user.password)
)
self._next_id += 1
self._users.append(new_user)
return new_user
users_crud = UsersCRUD()
3. Enhanced Route with Error Handling
Update src/api/routes/users.py with better error handling:
from typing import List
from fastapi import APIRouter, HTTPException, status
from src.schemas.users import User, UserCreate, UserUpdate
from src.crud.users import users_crud
router = APIRouter()
@router.post("/", response_model=User, status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate):
"""Create a new user"""
try:
new_user = users_crud.create(user)
# Return user without password hash
return User(**new_user.dict())
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e)
)
@router.get("/{user_id}", response_model=User)
def read_user(user_id: int):
"""Get a specific user"""
user = users_crud.get_by_id(user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with id {user_id} not found"
)
return User(**user.dict())
Adding Multiple Routes
You can add multiple routes to build a complete API:
This creates a comprehensive API with:
/api/v1/users/- User management/api/v1/products/- Product catalog/api/v1/orders/- Order processing/api/v1/categories/- Category management
Route Organization
Grouping Related Endpoints
You can organize routes by domain:
# src/api/api.py
from fastapi import APIRouter
from src.api.routes import users, products, orders, categories
api_router = APIRouter()
# User management
api_router.include_router(
users.router,
prefix="/users",
tags=["User Management"]
)
# E-commerce
api_router.include_router(
products.router,
prefix="/products",
tags=["E-commerce"]
)
api_router.include_router(
orders.router,
prefix="/orders",
tags=["E-commerce"]
)
api_router.include_router(
categories.router,
prefix="/categories",
tags=["E-commerce"]
)
Adding Route Dependencies
Add authentication or other dependencies:
from fastapi import APIRouter, Depends
from src.core.auth import get_current_user
router = APIRouter()
@router.get("/profile", response_model=User)
def get_user_profile(current_user: User = Depends(get_current_user)):
"""Get current user's profile"""
return current_user
@router.post("/", response_model=User)
def create_user(
user: UserCreate,
current_user: User = Depends(get_current_user)
):
"""Create a new user (admin only)"""
if not current_user.is_admin:
raise HTTPException(status_code=403, detail="Admin access required")
return users_crud.create(user)
Best Practices
1. Consistent Naming
Follow consistent naming conventions:
- Route names: Use plural nouns (
users,products,orders) - Schema names: Use singular (
User,Product,Order) - CRUD classes: End with
CRUD(UsersCRUD,ProductsCRUD)
2. Error Handling
Always handle errors gracefully:
@router.post("/", response_model=User)
def create_user(user: UserCreate):
try:
return users_crud.create(user)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail="Internal server error")
3. Documentation
Add comprehensive docstrings:
@router.get("/{user_id}", response_model=User)
def read_user(user_id: int):
"""
Get a specific user by ID.
Args:
user_id: The unique identifier for the user
Returns:
User: The user object with all details
Raises:
HTTPException: 404 if user not found
"""
user = users_crud.get_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
4. Testing
Always test your new routes:
# tests/test_users.py
from fastapi.testclient import TestClient
from src.main import app
client = TestClient(app)
def test_create_user():
user_data = {
"email": "test@example.com",
"username": "testuser",
"password": "securepassword123"
}
response = client.post("/api/v1/users/", json=user_data)
assert response.status_code == 201
assert response.json()["email"] == user_data["email"]
def test_get_user():
response = client.get("/api/v1/users/1")
assert response.status_code == 200
Troubleshooting
Route Not Appearing
If your route doesn't appear in the API documentation:
- Check router registration in
src/api/api.py - Restart the server after adding routes
- Check for import errors in the route file
Import Errors
If you get import errors:
- Check file structure matches the expected layout
- Verify schema imports in route and CRUD files
- Ensure all
__init__.pyfiles exist
Server Won't Start
If the server fails to start after adding routes:
- Check syntax errors in generated files
- Verify schema compatibility between files
- Check logs for specific error messages
Next Steps
Now that you know how to add routes:
- Your First Project: Build a complete blog API
- CLI Reference: Learn all available commands
- Using Templates: Explore pre-built project templates
Route Development Tips
- Always test new routes in the interactive docs (
/docs) - Use meaningful HTTP status codes
- Implement proper error handling for all endpoints
- Keep route handlers simple and delegate business logic to CRUD classes