# API Reference Complete REST API reference for Changemaker Lite V2. This section documents all API endpoints, request/response formats, authentication, and error handling. ## Overview Changemaker Lite V2 provides two REST APIs: - **Express API** (Port 4000) - Main application API - **Fastify Media API** (Port 4100) - Media library operations Both APIs use JSON for request/response bodies and follow RESTful conventions. ## API Documentation API reference documentation will be added as the API stabilizes. Planned documentation includes: ### Authentication Endpoints - `POST /api/auth/register` - User registration - `POST /api/auth/login` - User login - `POST /api/auth/refresh` - Refresh access token - `POST /api/auth/logout` - User logout - `GET /api/auth/me` - Get current user ### User Endpoints - `GET /api/users` - List users - `POST /api/users` - Create user - `GET /api/users/:id` - Get user - `PATCH /api/users/:id` - Update user - `DELETE /api/users/:id` - Delete user ### Campaign Endpoints - `GET /api/campaigns` - List campaigns - `POST /api/campaigns` - Create campaign - `GET /api/campaigns/:id` - Get campaign - `PATCH /api/campaigns/:id` - Update campaign - `DELETE /api/campaigns/:id` - Delete campaign - `GET /api/campaigns/public` - List public campaigns - `POST /api/campaigns/:id/send-email` - Send campaign email ### Location Endpoints - `GET /api/locations` - List locations - `POST /api/locations` - Create location - `GET /api/locations/:id` - Get location - `PATCH /api/locations/:id` - Update location - `DELETE /api/locations/:id` - Delete location - `POST /api/locations/import` - CSV import - `GET /api/locations/export` - CSV export - `POST /api/locations/geocode` - Bulk geocode ### Map Endpoints - `GET /api/cuts` - List cuts - `POST /api/cuts` - Create cut - `GET /api/shifts` - List shifts - `POST /api/shifts` - Create shift - `GET /api/canvass/session` - Get active session - `POST /api/canvass/session/start` - Start session - `POST /api/canvass/visit` - Record visit ### Content Endpoints - `GET /api/pages` - List pages - `POST /api/pages` - Create page - `GET /api/pages/public/:slug` - Get published page - `GET /api/email-templates` - List templates - `POST /api/email-templates` - Create template ### Media Endpoints (Port 4100) - `GET /media-api/videos` - List videos - `POST /media-api/upload` - Upload video - `GET /media-api/public/videos` - List public videos - `POST /media-api/reactions` - Add reaction ## Authentication All authenticated endpoints require a valid JWT access token in the Authorization header: ``` Authorization: Bearer ``` ### Token Lifecycle 1. **Login** - POST `/api/auth/login` - Returns: `accessToken` (15min) + `refreshToken` (7 days) 2. **Access Protected Resource** - Include token in header - Token verified by `authenticate` middleware 3. **Refresh Token** - POST `/api/auth/refresh` - Provide: `refreshToken` - Returns: New `accessToken` + `refreshToken` 4. **Logout** - POST `/api/auth/logout` - Invalidates refresh token ### Role-Based Access Endpoints are protected by role requirements: - **Public** - No authentication required - **Authenticated** - Any logged-in user - **Admin** - SUPER_ADMIN, INFLUENCE_ADMIN, or MAP_ADMIN - **Role-Specific** - Specific role required ## Request Format ### JSON Body ```json POST /api/campaigns Content-Type: application/json Authorization: Bearer { "name": "Save the Parks", "description": "Campaign description", "published": true } ``` ### Query Parameters ``` GET /api/campaigns?page=1&limit=20&search=parks ``` ### Path Parameters ``` GET /api/campaigns/:id ``` ## Response Format ### Success Response ```json { "id": 1, "name": "Save the Parks", "description": "Campaign description", "published": true, "createdAt": "2026-01-01T00:00:00.000Z", "updatedAt": "2026-01-01T00:00:00.000Z" } ``` ### Paginated Response ```json { "data": [...], "pagination": { "page": 1, "limit": 20, "total": 100, "totalPages": 5 } } ``` ### Error Response ```json { "error": "Validation error", "details": "Invalid email format", "statusCode": 400 } ``` ## Status Codes - **200 OK** - Success - **201 Created** - Resource created - **204 No Content** - Success with no body - **400 Bad Request** - Validation error - **401 Unauthorized** - Authentication required - **403 Forbidden** - Insufficient permissions - **404 Not Found** - Resource not found - **429 Too Many Requests** - Rate limit exceeded - **500 Internal Server Error** - Server error ## Rate Limiting Rate limits vary by endpoint: - **Auth endpoints** - 10 requests/minute per IP - **Canvass visits** - 30 requests/minute per IP - **Public endpoints** - 60 requests/minute per IP - **Authenticated endpoints** - 120 requests/minute per user Rate limit headers: ``` X-RateLimit-Limit: 60 X-RateLimit-Remaining: 59 X-RateLimit-Reset: 1640995200 ``` ## CORS CORS is enabled for all origins in development: ```javascript app.use(cors({ origin: '*', credentials: true, })); ``` Production should restrict to known domains. ## Validation Request bodies are validated using Zod schemas. Validation errors return 400 with details: ```json { "error": "Validation error", "details": { "email": "Invalid email format", "password": "Password must be at least 12 characters" }, "statusCode": 400 } ``` ## Pagination List endpoints support pagination: - **page** - Page number (default: 1) - **limit** - Items per page (default: 20, max: 100) Example: ``` GET /api/campaigns?page=2&limit=50 ``` ## Search & Filtering List endpoints support search and filtering: - **search** - Text search (varies by endpoint) - **filter** - Field-specific filters Example: ``` GET /api/campaigns?search=parks&published=true ``` ## Sorting List endpoints support sorting: - **sort** - Field to sort by - **order** - Sort direction (asc/desc) Example: ``` GET /api/campaigns?sort=createdAt&order=desc ``` ## API Endpoints by Module ### Authentication - Login, register, refresh, logout, current user ### Users - CRUD operations, pagination, search, role management ### Settings - Site settings singleton ### Campaigns - CRUD, public listing, email sending ### Representatives - Postal code lookup, cache management ### Responses - CRUD, verification, upvoting, moderation ### Postal Codes - Cache service ### Campaign Emails - Email tracking, statistics ### Email Queue - Queue monitoring, pause/resume, cleanup ### Locations - CRUD, CSV import/export, geocoding, NAR import ### Cuts - CRUD, spatial queries, location assignment ### Shifts - CRUD, signups, email notifications ### Canvass - Sessions, visits, routes, dashboard ### Tracking - GPS tracking (future) ### Map Settings - Map configuration ### Pages - CRUD, block library, MkDocs export, public rendering ### Email Templates - CRUD, versioning (future) ### Media (Port 4100) - Videos, upload, shared media, reactions, jobs ### Listmonk - Status, sync, test connection ### Pangolin - Tunnel management, setup, configuration ### Docs - MkDocs/Code Server status ### QR - QR code generation ### Observability - Prometheus/Grafana/Alertmanager integration ### Services - Health checks ## OpenAPI Specification OpenAPI/Swagger documentation is planned for future releases. This will provide: - Interactive API explorer - Auto-generated client libraries - Comprehensive endpoint documentation - Request/response examples ## Testing Test API endpoints using: - **curl** - Command-line HTTP client - **Postman** - GUI API client - **HTTPie** - User-friendly CLI - **Insomnia** - API design/testing tool Example with curl: ```bash # Login curl -X POST http://localhost:4000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"admin@example.com","password":"Admin123!"}' # Get campaigns (with token) curl http://localhost:4000/api/campaigns \ -H "Authorization: Bearer " ``` ## Related Documentation - [Backend Modules](../backend/modules/index.md) - [Authentication](../backend/modules/auth.md) - [Middleware](../backend/middleware/index.md) - [Development Guide](../development/index.md) - [Troubleshooting](../troubleshooting/index.md)