This guide explains how to add new API endpoints to SnackBase, following the established patterns and architecture.
Overview
SnackBase uses FastAPI for REST API endpoints. All endpoints are organized in the src/snackbase/infrastructure/api/routes/ directory.
Existing API Routers
Architecture Review
Layer Structure
Clean Architecture Principles
- Routers handle HTTP concerns (status codes, headers, parsing)
- Services contain business logic
- Repositories abstract database access
- Models (Pydantic) define request/response schemas
Where to Add Endpoints
Decision Tree
When to Create a New Router
Create a new router when:
- Adding a new major feature area
- Existing routers don’t match the domain concept
- The feature has 3+ related endpoints
Examples of when to create new routers:
/api/v1/webhooks/* - Webhook management
/api/v1/scheduled-tasks/* - Task scheduling
/api/v1/integrations/* - Third-party integrations
Step-by-Step Guide
Let’s add a new feature: Tags for organizing records.
Step 1: Define Pydantic Schemas
Create request/response models in infrastructure/api/schemas/:
Step 2: Create Database Model
Add SQLAlchemy model in infrastructure/persistence/models/:
Step 3: Create Repository
Add repository in infrastructure/persistence/repositories/:
Step 4: Create API Router
Create router in infrastructure/api/routes/:
Step 5: Register Router
Add the router to app.py:
The records_router must be registered LAST because it uses dynamic route matching (/) that will catch any unmatched paths.
Step 6: Create Migration
Generate and apply database migration:
Step 7: Add Permissions (Optional)
If your feature needs authorization, add permissions:
Request/Response Patterns
Request Body Validation
Use Pydantic for automatic validation:
Use consistent response formats:
For list endpoints, support pagination:
Authentication & Authorization
Require Authentication
All endpoints automatically require authentication via get_context():
Require Permissions
Use require_permission() for authorization:
Superadmin-Only Endpoints
For superadmin-only endpoints:
Testing Endpoints
Unit Tests
Test router logic:
Integration Tests
Test full flow with database:
Manual Testing with Swagger UI
Visit http://localhost:8000/docs to test endpoints interactively.
Best Practices
1. Use Appropriate Status Codes
2. Account Isolation
Always filter by account_id in repositories:
3. Use Dependency Injection
Inject dependencies via FastAPI’s Depends():
4. Handle Errors Gracefully
5. Document Endpoints
Use FastAPI’s docstring support:
Summary