Core API Service
A FastAPI-based backend service providing authentication, authorization, and business logic for the Cosailor Template application.
Quick Start
# 1. Set up environment
cd apps/core-api
cp .env.example .env # Edit with your DATABASE_URL and CORE_API_JWT_SECRET
# 2. Install dependencies
python -m venv src/venv
source src/venv/bin/activate
pip install -r apps/core-api/requirements.txt
# 4. Start the server
python src/main.py
Server runs on http://localhost:8000
Overview
The Core API provides:
- RBAC (Role-Based Access Control): Multi-tenant user management with roles and assignments
- Business Logic: Dashboard metrics, customer data, action items
- OpenAPI Integration: Auto-generated SDK for type-safe client consumption
Tech Stack: FastAPI, SQLAlchemy, Alembic, PostgreSQL, PyJWT
Authentication
All requests require a JWT token in the Authorization: Bearer <token> header.
Token Structure
{
"email": "user@example.com",
"roles": ["admin", "manager"],
"managedUserIds": ["uuid-1", "uuid-2"],
"tenantId": "uuid-tenant"
}
Using Authentication in Endpoints
from fastapi import APIRouter, Depends
from security import ServiceAuthContext, get_auth_context, check_can_read_user
@router.get("/dashboard/{user_id}")
def get_dashboard(
user_id: str,
auth: ServiceAuthContext = Depends(get_auth_context)
):
check_can_read_user(user_id, auth) # Verify access
return build_dashboard(conn, user_id)
Authorization Helpers
get_auth_context()- Validates JWT, returns user contextcheck_can_read_user(user_id, auth)- Admins/managers can read their reps, users read themselvescheck_can_write_user(user_id, auth)- Users can only write their own data
For detailed authentication documentation, see Authentication & Security Overview
Project Structure
apps/core-api/
├── src/
│ ├── db/
│ │ ├── alembic.ini
│ │ └── migrations/versions/
│ ├── routes/ # API endpoints
│ ├── scripts/ # Seed scripts, OpenAPI generation
│ ├── deps.py # Dependency injection
│ ├── dto.py # Response models
│ ├── main.py # App entry point
│ ├── models.py # SQLAlchemy models
│ ├── repo.py # Database queries
│ ├── security.py # JWT auth & authorization
│ └── services.py # Business logic
├── requirements.txt
└── README.md
Development
Environment Variables
Create .env:
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
DB_SCHEMA=public
CORE_API_JWT_SECRET=your-secret-key-here
Running the Server
cd apps/core-api
source src/venv/bin/activate
python src/main.py
Seeding Test Data
The seed script creates:
- Default tenant: "Instalily"
- Roles:
admin,manager,rep - Sample users from your team
- Sample manager-rep assignments
cd apps/core-api
source src/venv/bin/activate
DATABASE_URL="postgresql://..." python src/scripts/seed_auth_data.py
Edit apps/core-api/src/scripts/seed_auth_data.py to customize seed data.
Resources
- FastAPI Docs: https://fastapi.tiangolo.com/
- SQLAlchemy ORM: https://docs.sqlalchemy.org/
- Alembic Migrations: https://alembic.sqlalchemy.org/
- PyJWT: https://pyjwt.readthedocs.io/