Skip to content

nexlified/recaller-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Recaller API

A comprehensive multi-tenant personal information management system API built with FastAPI and PostgreSQL.

Features

  • FastAPI-based REST API with comprehensive documentation
  • Multi-tenant Architecture with role-based access control
  • User Authentication & Authorization with JWT tokens
  • Personal Daily Journaling with mood tracking, tags, and search
  • PostgreSQL database integration with UUID primary keys
  • Alembic database migrations for schema management
  • Docker containerization for easy deployment
  • CLI tools for database and user management
  • Invitation System for team collaboration
  • Subscription Management with member limits
  • Comprehensive Validation with Pydantic schemas

Journal Features

The Recaller API includes a comprehensive daily journaling system with the following features:

Core Journaling

  • Daily Entries: Create one journal entry per day per tenancy
  • Rich Content: Support for titles, detailed content, and metadata
  • Word Count Tracking: Automatic word count calculation for entries

Mood & Context Tracking

  • Mood Tracking: Record daily mood with predefined options (happy, sad, anxious, etc.)
  • Weather Logging: Track weather conditions for each entry
  • Location Support: Record where the journal entry was written

Organization & Discovery

  • Tagging System: Add multiple tags to categorize entries
  • Full-Text Search: Search through entry titles and content
  • Advanced Filtering: Filter by date range, mood, tags, and favorites
  • Favorites: Mark important entries as favorites

Privacy & Personalization

  • Privacy Controls: Mark entries as private (default) or shareable
  • Personal Prompts: Get daily writing prompts for inspiration
  • Multiple Categories: Prompts organized by categories (gratitude, reflection, goals, etc.)

Analytics & Insights

  • Writing Streaks: Track current and longest writing streaks
  • Statistics Dashboard: View total entries, monthly/yearly counts, and word counts
  • Mood Analysis: See most common moods over time
  • Progress Tracking: Monitor journaling habits and consistency

Setup

Prerequisites

  • Python 3.13+
  • PostgreSQL (or use Docker)
  • Docker and Docker Compose (optional)

Installation

  1. Clone the repository:
git clone <repository-url>
cd recaller-api
  1. Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt

Database Setup

Using Docker (Recommended)

  1. Start the PostgreSQL database:
docker-compose up -d db
  1. Initialize the database with migrations:
python cli.py db init

Manual PostgreSQL Setup

  1. Create a PostgreSQL database named recaller
  2. Update the DATABASE_URL environment variable or modify alembic.ini
  3. Initialize the database:
python cli.py db init

Database Management

The project includes a CLI tool for managing database migrations:

Available Commands

  • Initialize database: python cli.py db init
  • Create new migration: python cli.py db migrate -m "Migration message"
  • Apply migrations: python cli.py db upgrade
  • Rollback migrations: python cli.py db downgrade
  • Check migration status: python cli.py db status
  • View migration history: python cli.py db history

Alembic Commands (Alternative)

You can also use Alembic directly:

# Create a new migration
alembic revision --autogenerate -m "Add new table"

# Apply migrations
alembic upgrade head

# Rollback one migration
alembic downgrade -1

# Check current revision
alembic current

# View migration history
alembic history

Running the Application

Using Docker Compose

docker-compose up

The API will be available at http://localhost:8000

Manual Run

  1. Ensure PostgreSQL is running and database is initialized
  2. Start the FastAPI server:
uvicorn api:app --reload

API Documentation

Once the server is running, visit:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

Project Structure

recaller-api/
├── app/                    # Main application package
│   ├── __init__.py
│   ├── core/              # Core functionality
│   │   ├── __init__.py
│   │   ├── auth.py        # Authentication and authorization
│   │   └── database.py    # Database configuration
│   ├── models/            # SQLAlchemy models
│   │   ├── __init__.py
│   │   ├── base.py        # Base model class
│   │   ├── enums.py       # Enum definitions
│   │   ├── user.py        # User models
│   │   ├── tenancy.py     # Tenancy models
│   │   ├── journal.py     # Journal models
│   │   └── item.py        # Item models
│   ├── routers/           # API route handlers
│   │   ├── __init__.py
│   │   └── journal.py     # Journal endpoints
│   ├── schemas/           # Pydantic schemas
│   │   ├── __init__.py
│   │   └── journal.py     # Journal schemas
│   ├── services/          # Business logic layer
│   │   ├── __init__.py
│   │   ├── base.py        # Base service class
│   │   ├── user_service.py
│   │   ├── session_service.py
│   │   └── tenancy_service.py
│   └── utils/             # Utility functions
│       └── __init__.py
├── alembic/               # Database migrations
│   ├── versions/          # Migration scripts
│   └── env.py            # Alembic environment configuration
├── alembic.ini           # Alembic configuration
├── main.py               # FastAPI application entry point
├── docker-compose.yml    # Docker services
├── Dockerfile            # API container
└── requirements.txt      # Python dependencies

API Architecture

Header-Based Tenancy

The API uses header-based tenancy instead of URL path parameters. Include the X-Tenancy-ID header in requests that require tenancy context:

curl -H "X-Tenancy-ID: your-tenancy-uuid" \
     -H "Authorization: Bearer your-token" \
     http://localhost:8000/journal/entries

Service Layer

The application follows a layered architecture:

  • Routers: Handle HTTP requests and responses
  • Services: Contain business logic and data validation
  • Models: Define database schema and relationships
  • Schemas: Handle request/response serialization

API Endpoints

Authentication

  • POST /auth/register - Register new user (optionally with tenancy)
  • POST /auth/login - User login
  • POST /auth/logout - User logout

User Management

  • GET /users/me - Get current user info
  • PUT /users/me - Update current user
  • GET /users/me/tenancies - Get user's tenancies
  • GET /users/me/invites - Get pending invites

Tenancy Management

  • POST /tenancies - Create new tenancy
  • GET /tenancies/{id} - Get tenancy details
  • PUT /tenancies/{id} - Update tenancy (admin/owner)
  • PUT /tenancies/{id}/subscription - Update subscription (owner)

Member Management

Requires X-Tenancy-ID header

  • POST /invites - Invite user (admin/owner)
  • POST /invites/accept - Accept invitation
  • PUT /members/{user_id} - Update member role (admin/owner)
  • DELETE /members/{user_id} - Remove member (admin/owner)

Item Management

Requires X-Tenancy-ID header

  • POST /items - Create item
  • GET /items - List items
  • GET /items/{item_id} - Get item
  • PUT /items/{item_id} - Update item
  • DELETE /items/{item_id} - Delete item

Journal Management

  • POST /journal/entries - Create daily journal entry
  • GET /journal/entries - List journal entries with filtering
  • GET /journal/entries/{entry_id} - Get specific journal entry
  • PUT /journal/entries/{entry_id} - Update journal entry
  • DELETE /journal/entries/{entry_id} - Delete journal entry
  • GET /journal/stats - Get journaling statistics and streaks
  • GET /journal/prompts - Get random journal prompts
  • GET /journal/prompts/daily - Get daily journal prompt

Note: All journal endpoints require the X-Tenancy-ID header to specify the tenancy context.

Example API Usage

Authentication Flow

# Register a new user
curl -X POST "http://localhost:8000/auth/register" \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com",
       "username": "johndoe",
       "password": "securepass123",
       "first_name": "John",
       "last_name": "Doe"
     }'

# Login to get token
curl -X POST "http://localhost:8000/auth/login" \
     -H "Content-Type: application/json" \
     -d '{
       "email": "user@example.com",
       "password": "securepass123"
     }'

Journal API Examples

# Create a journal entry (requires X-Tenancy-ID header)
curl -X POST "http://localhost:8000/journal/entries" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "X-Tenancy-ID: YOUR_TENANCY_UUID" \
     -d '{
       "title": "My Daily Reflection",
       "content": "Today was a productive day. I learned about FastAPI and made great progress on my project.",
       "mood": "happy",
       "weather": "sunny",
       "tags": ["work", "learning", "productivity"]
     }'

# Get journal entries with filtering
curl -X GET "http://localhost:8000/journal/entries?mood=happy&limit=10" \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "X-Tenancy-ID: YOUR_TENANCY_UUID"

# Get journaling statistics
curl -X GET "http://localhost:8000/journal/stats" \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "X-Tenancy-ID: YOUR_TENANCY_UUID"

# Get daily journal prompt
curl -X GET "http://localhost:8000/journal/prompts/daily" \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "X-Tenancy-ID: YOUR_TENANCY_UUID"

CLI Management Tool

The API includes a comprehensive CLI tool built with Typer for managing database operations and user management.

CLI Commands

Database Operations

# Show available database commands
python cli.py db --help

# Create database tables
python cli.py db create

# Create a new migration
python cli.py db migrate --message "Description of changes"

# Apply migrations
python cli.py db upgrade

# Show current migration status
python cli.py db current

# Show migration history
python cli.py db history

# Downgrade migrations (use with caution)
python cli.py db downgrade

# Drop all tables (requires confirmation)
python cli.py db drop --confirm

User Management

# Show available user commands
python cli.py user --help

# Create a new user
python cli.py user create \
  --email user@example.com \
  --username johndoe \
  --first-name John \
  --last-name Doe \
  --password securepass123 \
  --verified  # Optional: mark as verified

# Verify a user's email
python cli.py user verify --email user@example.com

# Activate/deactivate user accounts
python cli.py user activate --email user@example.com
python cli.py user deactivate --email user@example.com

# List users
python cli.py user list --active-only --limit 20

# Get detailed user information
python cli.py user info --email user@example.com

Tenancy Management

# Show available tenancy commands
python cli.py tenancy --help

# Create a new tenancy
python cli.py tenancy create \
  --name "My Company" \
  --slug my-company \
  --owner-email owner@example.com \
  --plan premium \
  --description "Company tenancy"

# List tenancies
python cli.py tenancy list --limit 10

# Get detailed tenancy information
python cli.py tenancy info --slug my-company

Database Schema

Users Table

Column Type Description
id UUID Primary key
email String User email (unique)
username String Username (unique)
first_name String First name
last_name String Last name
hashed_password String Hashed password
is_active Boolean Account active status
is_verified Boolean Email verification status
created_at DateTime Creation timestamp
updated_at DateTime Last update timestamp
last_login DateTime Last login timestamp

Tenancies Table

Column Type Description
id UUID Primary key
name String Tenancy name
slug String URL-friendly identifier
description Text Tenancy description
owner_id UUID Foreign key to users
subscription_plan String Subscription plan
max_members Integer Maximum allowed members
is_active Boolean Tenancy active status
created_at DateTime Creation timestamp
updated_at DateTime Last update timestamp

Tenancy Members Table

Column Type Description
id UUID Primary key
user_id UUID Foreign key to users
tenancy_id UUID Foreign key to tenancies
role String User role (owner/admin/member)
is_active Boolean Membership active status
joined_at DateTime Join timestamp
updated_at DateTime Last update timestamp

Tenancy Invites Table

Column Type Description
id UUID Primary key
tenancy_id UUID Foreign key to tenancies
invited_by_id UUID Foreign key to users
invited_user_id UUID Foreign key to users (nullable)
email String Invited email address
role String Assigned role
invite_token String Unique invitation token
status String Invite status
expires_at DateTime Expiration timestamp
created_at DateTime Creation timestamp
accepted_at DateTime Acceptance timestamp

User Sessions Table

Column Type Description
id UUID Primary key
user_id UUID Foreign key to users
access_token String JWT access token
refresh_token String Refresh token
expires_at DateTime Token expiration
created_at DateTime Creation timestamp
is_active Boolean Session active status

Multi-Tenancy & Roles

User Roles

  • Owner: Full control over tenancy, can manage subscription, add/remove admins
  • Admin: Can manage members, invite users, manage tenancy settings
  • Member: Can access tenancy resources, create/manage items

Subscription Plans

  • Free: Up to 5 members
  • Basic: Up to 15 members
  • Premium: Up to 50 members
  • Enterprise: Up to 200 members

Invitation System

  1. Admin/Owner invites user by email
  2. System generates unique invitation token
  3. Invited user receives invitation (token valid for 7 days)
  4. User accepts invitation to join tenancy
  5. User becomes active member with assigned role

API Usage Examples

Register and Create Tenancy

curl -X POST "http://localhost:8000/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "owner@example.com",
    "username": "owner",
    "first_name": "John",
    "last_name": "Doe",
    "password": "securepass123",
    "tenancy_name": "My Company"
  }'

Login

curl -X POST "http://localhost:8000/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "owner@example.com",
    "password": "securepass123"
  }'

Invite User to Tenancy

curl -X POST "http://localhost:8000/tenancies/{tenancy_id}/invites" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "member@example.com",
    "role": "member"
  }'

Running the Application

Development Server

Start the FastAPI development server:

uvicorn main:app --reload --host 0.0.0.0 --port 8000

The API will be available at:

Production Deployment

For production, use a production ASGI server like Gunicorn with Uvicorn workers:

gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

Docker Deployment

Build and run with Docker Compose:

docker-compose up --build

This will start:

  • PostgreSQL database on port 5432
  • API server on port 8000

Environment Variables

  • DATABASE_URL: PostgreSQL connection string (default: postgresql://recaller:recaller@localhost:5432/recaller)
  • SECRET_KEY: JWT secret key (change in production)

Development

Project Structure

The application follows a modular architecture:

  • app/models/: SQLAlchemy database models
  • app/schemas/: Pydantic schemas for API validation
  • app/routers/: FastAPI route handlers
  • app/services/: Business logic layer
  • app/core/: Core functionality (auth, database)

Creating New Migrations

When you modify models in app/models/, create a new migration:

alembic revision --autogenerate -m "Describe your changes"

Then apply the migration:

alembic upgrade head

Adding New Models

  1. Define your model in the appropriate app/models/ file inheriting from Base
  2. Import the model in app/models/__init__.py
  3. Create a migration: alembic revision --autogenerate -m "Add new model"
  4. Apply the migration: alembic upgrade head

Adding New Endpoints

  1. Create schemas in app/schemas/
  2. Add business logic to app/services/
  3. Create router in app/routers/
  4. Include router in main.py

Troubleshooting

Database Connection Issues

  1. Ensure PostgreSQL is running
  2. Check the DATABASE_URL in your environment or alembic.ini
  3. Verify database credentials and permissions

Migration Issues

  1. Check current migration status: alembic current
  2. View migration history: alembic history
  3. If needed, rollback and reapply: alembic downgrade then alembic upgrade head

License

MIT License

About

Recaller API

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages