Skip to main content

API Documentation Supplement

Interactive API Docs

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_KEY must 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_ORIGINS to 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 page and page_size parameters

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 1
  • page_size: Integer, default 20, max 100
  • sort: Optional field name with direction (e.g., created_at desc)

Response Format:

{
"items": [...],
"page": 1,
"page_size": 20,
"total": 123,
"pages": 7
}
Pagination Note

Some endpoints may currently return plain arrays. Pagination is forward-compatible and can be added without breaking existing requests by using defaults.

Rate Limiting​

Rate Limiting

MVP does not enforce rate limiting. When deployed behind a reverse proxy or API gateway, configure:

  • 429 Too Many Requests with Retry-After header
  • 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 token
  • GET /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 details
  • GET /api/documents/{id}/download - Download document file
  • PUT /api/documents/{id} - Update document metadata
  • POST /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_TYPE environment variable

Document Types & Workflows​

Endpoints:

  • GET /api/document-types/ - List all document types
  • POST /api/document-types/ - Create new document type
  • GET /api/document-types/{id} - Get document type details
  • PUT /api/document-types/{id} - Update document type
  • GET /api/workflow-templates/ - List workflow templates
  • POST /api/workflow-templates/ - Create workflow template
  • GET /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

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 assistant
  • POST /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_KEY environment 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 templates
  • POST /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 groups
  • POST /api/training/bulk-assign - Bulk assign training to multiple users
  • GET /api/training/my-training - Get current user's training assignments
  • GET /api/training/{id} - Get training program details
  • POST /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 deviation
  • GET /api/deviations/ - List deviations
  • GET /api/deviations/{id} - Get deviation details
  • PUT /api/deviations/{id} - Update deviation
  • POST /api/deviations/suggest-severity - AI-powered severity classification
  • GET /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 CAPA
  • GET /api/capa/ - List CAPAs
  • GET /api/capa/{id} - Get CAPA details
  • PUT /api/capa/{id} - Update CAPA
  • POST /api/capa/{id}/approve-draft - Approve draft CAPA (QA/Admin only)
  • POST /api/capa/{id}/effectiveness - Create effectiveness review
  • GET /api/capa/{id}/effectiveness - Get effectiveness reviews
  • PUT /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 user
  • GET /api/dashboard/pending-approvals - Get pending approvals (documents, deviations, CAPAs)
  • GET /api/dashboard/overdue-items - Get overdue items
  • GET /api/dashboard/approaching-deadlines - Get items with deadlines within 24 hours
  • GET /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
  • 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 signature
  • GET /api/signatures/ - List signatures
  • GET /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 groups
  • POST /api/groups/ - Create new group
  • GET /api/groups/{id} - Get group details
  • PUT /api/groups/{id} - Update group
  • DELETE /api/groups/{id} - Delete group
  • POST /api/groups/{id}/add-member - Add user to group
  • DELETE /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 notifications
  • POST /api/notifications/{id}/mark-read - Mark notification as read
  • POST /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 roles
  • GET /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 category
  • description: Document description
  • keywords: 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-Disposition header 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​

CodeDescriptionCommon Causes
400Bad RequestValidation errors, malformed requests
401UnauthorizedMissing or invalid JWT token
403ForbiddenInsufficient permissions (RBAC)
404Not FoundResource doesn't exist
409ConflictVersioning or state conflicts
422Unprocessable EntityValidation details from FastAPI
500Internal Server ErrorUnhandled exceptions

Security and Privacy​

Security Best Practices
  • 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