API Documentation Supplement
For complete interactive API documentation with request/response schemas, visit /docs when the backend is running. This document provides supplementary information about authentication, conventions, and module-specific details.
This document complements the autogenerated FastAPI docs at /docs by describing authentication, pagination, standard errors, rate limiting guidance, idempotency expectations, and module-specific notes. All endpoints are prefixed according to module names as implemented in the backend.
Base URLs​
- Local Development:
http://localhost:8000 - Production:
https://your-host:8000(behind reverse proxy) - API Documentation:
http://localhost:8000/docs(Swagger UI)
Authentication​
JWT Bearer Token Authentication​
All protected endpoints require JWT Bearer token authentication.
Obtain Token:
POST /api/auth/token
Content-Type: application/json
{
"username": "user@example.com",
"password": "password"
}
Response:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"token_type": "bearer",
"user": {
"id": 1,
"username": "user@example.com",
"email": "user@example.com",
"role": "QA"
}
}
Using the Token:
Include the token in the Authorization header for all subsequent requests:
Authorization: Bearer <access_token>
Current User Info:
GET /api/auth/me
Authorization: Bearer <token>
Token Considerations:
SECRET_KEYmust be set via environment variable- Token lifetimes: Standard access tokens (refresh strategy can be added post-pilot)
- Tokens are stateless and validated on each request
CORS Configuration​
- Production: Set
BACKEND_CORS_ORIGINSto your frontend domain(s) - Development: Default allows
http://localhost:3000 - Format: Comma-separated list of allowed origins
Common Conventions​
Content Types​
- JSON APIs:
application/json(default) - File Uploads:
multipart/form-data - File Downloads: Appropriate content-type based on file type
Data Formats​
- Timestamps: ISO 8601 format in UTC (e.g.,
2025-01-15T10:30:00Z) - IDs: Integers for primary resources (unless otherwise specified)
- Pagination: Page-based with
pageandpage_sizeparameters
Error Response Format​
Standard FastAPI error format:
{
"detail": "Error message"
}
Validation errors:
{
"detail": [
{
"loc": ["body", "field_name"],
"msg": "Validation error message",
"type": "value_error"
}
]
}
Pagination​
For list endpoints, use optional query parameters:
page: Integer, default 1page_size: Integer, default 20, max 100sort: Optional field name with direction (e.g.,created_at desc)
Response Format:
{
"items": [...],
"page": 1,
"page_size": 20,
"total": 123,
"pages": 7
}
Some endpoints may currently return plain arrays. Pagination is forward-compatible and can be added without breaking existing requests by using defaults.
Rate Limiting​
MVP does not enforce rate limiting. When deployed behind a reverse proxy or API gateway, configure:
429 Too Many RequestswithRetry-Afterheader- Separate limits for authenticated vs. anonymous endpoints
Idempotency​
- Reads: All GET endpoints are idempotent
- Writes: For create endpoints, clients should guard against unintended retries
- Future Enhancement: Idempotency-Key header support for write operations
API Modules​
Authentication​
Endpoints:
POST /api/auth/register- Register new user (if enabled)POST /api/auth/token- Login and obtain JWT tokenGET /api/auth/me- Get current user information
Notes:
- RBAC role attached to user determines access permissions
- Role names are returned (e.g., "QA", "User", "Admin") instead of role IDs
Documents​
Endpoints:
POST /api/documents/upload- Upload new document (multipart/form-data)GET /api/documents/- List documents (with pagination)GET /api/documents/{id}- Get document detailsGET /api/documents/{id}/download- Download document filePUT /api/documents/{id}- Update document metadataPOST /api/documents/{id}/approve- Approve document (workflow-aware)POST /api/documents/{id}/configure-approval- Configure approval workflow
Workflow System:
- Documents can use configurable workflow templates
- Workflow states and transitions are managed automatically
- State-based approvals with role and user-specific rules
- Auto-transitions when approval requirements are met
File Storage:
- Default: Local file system (
backend/uploads/) - Configurable: S3 or GCP via
STORAGE_TYPEenvironment variable
Document Types & Workflows​
Endpoints:
GET /api/document-types/- List all document typesPOST /api/document-types/- Create new document typeGET /api/document-types/{id}- Get document type detailsPUT /api/document-types/{id}- Update document typeGET /api/workflow-templates/- List workflow templatesPOST /api/workflow-templates/- Create workflow templateGET /api/workflow-templates/{id}- Get workflow template details
Features:
- Admin-configurable document types with default workflow templates
- Customizable workflow templates with states, transitions, and approval rules
- Complete workflow history and audit trail
Search​
Endpoints:
GET /api/search/?q=...&filters=...- Semantic search
Features:
- Semantic search backed by ChromaDB vector store
- Full-text search across document content
- Filter by type, category, status, date range
- Pagination support
AI Assistant​
Endpoints:
POST /api/ai/chat- Chat with AI assistantPOST /api/ai/generate- Generate content (reports, summaries, SOPs)POST /api/ai/analyze- Analyze document content
Request Examples:
// Chat
{
"message": "Summarize this document",
"context_documents": [1, 2, 3]
}
// Generate
{
"prompt": "Create a quality report",
"document_type": "report"
}
// Analyze
{
"document_id": 123,
"instructions": "Identify compliance issues"
}
Notes:
- Requires
OPENAI_API_KEYenvironment variable - Can be disabled by omitting the API key
- AI features are optional and don't block core functionality
Templates​
Endpoints:
GET /api/templates/- List available templatesPOST /api/templates/use- Use template with variables
Template Usage:
{
"template_id": 1,
"variables": {
"title": "Quality Manual",
"version": "1.0",
"author": "John Doe"
}
}
Training​
Endpoints:
POST /api/training/assign- Assign training to users or groupsPOST /api/training/bulk-assign- Bulk assign training to multiple usersGET /api/training/my-training- Get current user's training assignmentsGET /api/training/{id}- Get training program detailsPOST /api/training/{id}/complete- Complete training assignment
Features:
- Group-based training assignments
- Individual and bulk assignment support
- Completion tracking with electronic signatures
- Training gate enforcement for documents
Deviations​
Endpoints:
POST /api/deviations/- Report new deviationGET /api/deviations/- List deviationsGET /api/deviations/{id}- Get deviation detailsPUT /api/deviations/{id}- Update deviationPOST /api/deviations/suggest-severity- AI-powered severity classificationGET /api/deviations/similar- Find similar historical deviations
Dynamic Form Builder:
- Configurable form templates with sections and fields
- Field types: text, textarea, select, document_picker, capa_picker, image, file
- AI-powered field suggestions (e.g., severity classification)
- Related items linking (documents, CAPAs)
AI Severity Classification:
POST /api/deviations/suggest-severity
{
"description": "Batch contamination detected in production line"
}
Response:
{
"severity": "High",
"confidence": 0.87,
"rationale": "Contamination in production indicates potential quality impact"
}
CAPA Management​
Endpoints:
POST /api/capa/- Create new CAPAGET /api/capa/- List CAPAsGET /api/capa/{id}- Get CAPA detailsPUT /api/capa/{id}- Update CAPAPOST /api/capa/{id}/approve-draft- Approve draft CAPA (QA/Admin only)POST /api/capa/{id}/effectiveness- Create effectiveness reviewGET /api/capa/{id}/effectiveness- Get effectiveness reviewsPUT /api/capa/{id}/effectiveness/{review_id}- Update effectiveness review
Draft Approval Workflow:
- CAPAs without linked documents start as 'draft' status
- Draft CAPAs require QA Manager or Admin approval
- Many-to-many deviation associations supported
- Auto-activation after approval
Dashboard​
Endpoints:
GET /api/dashboard/assigned-items- Get items assigned to current userGET /api/dashboard/pending-approvals- Get pending approvals (documents, deviations, CAPAs)GET /api/dashboard/overdue-items- Get overdue itemsGET /api/dashboard/approaching-deadlines- Get items with deadlines within 24 hoursGET /api/dashboard/stats- Get comprehensive KPI metrics
Dashboard Features:
- Real-time updates from dedicated endpoints
- Assigned items: Training, deviations, CAPAs
- Pending approvals: Documents, deviations, draft CAPAs
- KPI metrics: Document versions, creation trends, deviation KPIs, CAPA metrics, training metrics
Audit Trail​
Endpoints:
GET /api/audit/- Get audit trail entries- Query parameters:
user_id,action,resource_type,date_from,date_to
- Query parameters:
GET /api/audit/export- Export audit trail (CSV/PDF)
Features:
- Comprehensive logging of all system activities
- Immutable audit records
- User attribution and timestamp tracking
- Workflow state transition history
- Filtering and search capabilities
Electronic Signatures​
Endpoints:
POST /api/signatures/- Create electronic signatureGET /api/signatures/- List signaturesGET /api/signatures/{id}- Get signature details with verification
Signature Process:
POST /api/signatures/
{
"document_id": 123,
"signature_type": "approval",
"intent": "I approve this document for release"
}
Features:
- GMP-compliant electronic signatures
- Identity verification and intent capture
- Complete audit trail
- Signature verification and integrity checks
Groups​
Endpoints:
GET /api/groups/- List groupsPOST /api/groups/- Create new groupGET /api/groups/{id}- Get group detailsPUT /api/groups/{id}- Update groupDELETE /api/groups/{id}- Delete groupPOST /api/groups/{id}/add-member- Add user to groupDELETE /api/groups/{id}/remove-member/{user_id}- Remove user from group
Notes:
- Groups organize users for training assignments and reporting
- Admins manage groups; users can view their groups
- Group-based training assignments supported
Notifications​
Endpoints:
GET /api/notifications/- Get user notificationsPOST /api/notifications/{id}/mark-read- Mark notification as readPOST /api/notifications/mark-all-read- Mark all notifications as read
Notes:
- Notifications created for events: document approvals, training assignments, deviations, CAPAs
- In-app notifications with optional email delivery
- Priority-based notification system
Roles and RBAC​
Endpoints:
GET /api/roles/- List all rolesGET /api/roles/{id}- Get role details with permissions- Admin-only endpoints for role assignment and permissions management
Permission System:
- 30+ granular permissions
- Role-based access control (RBAC)
- Permission inheritance and overrides
- User-specific permission assignments
File Upload and Download​
Upload​
Endpoint: POST /api/documents/upload
Form Fields:
file: Binary file data (required)title: Document title (required)document_type: Document type ID (required for workflow system)category: Document categorydescription: Document descriptionkeywords: Comma-separated keywords
Response:
{
"id": 123,
"title": "Quality Manual",
"version": "1.0",
"status": "draft",
"file_path": "/uploads/documents/123/quality-manual-v1.0.pdf"
}
Download​
Endpoint: GET /api/documents/{id}/download
- Returns file stream with appropriate content-type
- Sets
Content-Dispositionheader for file download - Supports version-specific downloads
Health and Readiness​
Endpoint: GET /api/health
Response:
{
"status": "healthy",
"database": "connected",
"version": "1.0.0"
}
Used by Docker healthcheck in production deployments.
Standard Error Codes​
| Code | Description | Common Causes |
|---|---|---|
400 | Bad Request | Validation errors, malformed requests |
401 | Unauthorized | Missing or invalid JWT token |
403 | Forbidden | Insufficient permissions (RBAC) |
404 | Not Found | Resource doesn't exist |
409 | Conflict | Versioning or state conflicts |
422 | Unprocessable Entity | Validation details from FastAPI |
500 | Internal Server Error | Unhandled exceptions |
Security and Privacy​
- Use HTTPS in production behind a reverse proxy
- Restrict CORS to known origins (
BACKEND_CORS_ORIGINS) - Never include secrets in logs or error messages
- If handling PHI, ensure HIPAA controls and BAAs are in place
Examples​
Login and List Documents​
# 1. Login
curl -X POST http://localhost:8000/api/auth/token \
-H "Content-Type: application/json" \
-d '{"username": "user@example.com", "password": "password"}'
# 2. Use token to list documents
curl -X GET http://localhost:8000/api/documents/ \
-H "Authorization: Bearer <token>"
Upload Document​
curl -X POST http://localhost:8000/api/documents/upload \
-H "Authorization: Bearer <token>" \
-F "file=@/path/to/file.pdf" \
-F "title=Quality Manual" \
-F "document_type=1" \
-F "category=Quality"
AI Severity Classification​
curl -X POST http://localhost:8000/api/deviations/suggest-severity \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"description": "Batch contamination detected in production line"
}'
Versioning​
- Current API Version: 1.0.0
- Breaking Changes: Will be announced with route path versioning (e.g.,
/v2/) - Change Log: Tracked via Git commit history and release notes
Related Documentation​
- Developer Onboarding - Setup and development guide
- Testing Guide - API testing strategies
- Troubleshooting - Common issues and solutions
- Implementation Status - Current system status