Aniworld/src/server/README_FastAPI.md

7.2 KiB

AniWorld FastAPI Server

A comprehensive FastAPI-based server implementation for AniWorld following the project instructions.

🚀 Features

Authentication System (Completed)

  • Simple Master Password Authentication: Single master password for the entire application
  • JWT Token Management: Stateless authentication using JWT tokens
  • Environment Configuration: Secure password hash stored in environment variables
  • Session Management: Configurable token expiry (default: 24 hours)
  • Security Features: SHA-256 password hashing with salt

API Endpoints (Implemented)

Authentication Endpoints

  • POST /auth/login - Login with master password and receive JWT token
  • GET /auth/verify - Verify JWT token validity (protected)
  • POST /auth/logout - Logout endpoint (stateless - client removes token)

System Endpoints

  • GET / - Root endpoint with API information
  • GET /health - Health check endpoint
  • GET /api/system/config - System configuration (protected)
  • GET /api/system/database/health - Database health check (protected)

Anime & Episode Endpoints (Protected)

  • GET /api/anime/search - Search anime by title with pagination
  • GET /api/anime/{anime_id} - Get specific anime details
  • GET /api/anime/{anime_id}/episodes - Get all episodes for anime
  • GET /api/episodes/{episode_id} - Get specific episode details

🔧 Technical Features

  • FastAPI Framework: Modern, fast (high-performance) web framework
  • OpenAPI Documentation: Automatic API documentation at /docs
  • CORS Support: Configurable cross-origin resource sharing
  • Request Validation: Pydantic models for request/response validation
  • Error Handling: Centralized error handling with proper HTTP status codes
  • Logging: Comprehensive logging system with file and console output
  • Environment Configuration: Secure configuration via environment variables

🛠️ Installation & Setup

Prerequisites

  • Python 3.11+ (AniWorld conda environment)
  • Conda package manager

1. Activate AniWorld Environment

conda activate AniWorld

2. Install Dependencies

cd src/server
pip install -r requirements_fastapi.txt

3. Configure Environment

Create or update .env file:

# Authentication
JWT_SECRET_KEY=your-super-secure-jwt-secret-key
PASSWORD_SALT=your-secure-salt
MASTER_PASSWORD=admin123
SESSION_TIMEOUT_HOURS=24

# Application
ANIME_DIRECTORY=your-anime-directory-path
LOG_LEVEL=INFO

# Optional
DATABASE_URL=sqlite:///./aniworld.db
CORS_ORIGINS=*

4. Start the Server

Option 1: Direct Python Execution

cd src/server
C:\Users\lukas\anaconda3\envs\AniWorld\python.exe fastapi_app.py

Option 2: Using Batch Script (Windows)

cd src/server
run_and_test.bat

Option 3: Using Shell Script (Linux/Mac)

cd src/server
chmod +x start_fastapi_server.sh
./start_fastapi_server.sh

📖 API Usage

1. Access Documentation

Visit: http://localhost:8000/docs

2. Authentication Flow

Step 1: Login

curl -X POST "http://localhost:8000/auth/login" \
     -H "Content-Type: application/json" \
     -d '{"password": "admin123"}'

Response:

{
  "success": true,
  "message": "Authentication successful",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_at": "2025-10-06T18:19:24.710065"
}

Step 2: Use Token for Protected Endpoints

curl -X GET "http://localhost:8000/api/anime/search?query=naruto&limit=5" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN"

3. Example API Calls

Health Check

curl "http://localhost:8000/health"

Search Anime

curl -H "Authorization: Bearer YOUR_TOKEN" \
     "http://localhost:8000/api/anime/search?query=naruto&limit=10"

Get Anime Details

curl -H "Authorization: Bearer YOUR_TOKEN" \
     "http://localhost:8000/api/anime/anime_123"

🧪 Testing

Automated Testing

cd src/server
C:\Users\lukas\anaconda3\envs\AniWorld\python.exe test_fastapi.py

Manual Testing

  1. Start the server
  2. Visit http://localhost:8000/docs
  3. Use the interactive API documentation
  4. Test authentication with password: admin123

📁 Project Structure

src/server/
├── fastapi_app.py              # Main FastAPI application
├── .env                        # Environment configuration
├── requirements_fastapi.txt    # Python dependencies
├── test_fastapi.py             # Test script
├── start_fastapi_server.bat    # Windows startup script
├── start_fastapi_server.sh     # Linux/Mac startup script
├── run_and_test.bat           # Windows test runner
└── logs/                      # Log files

🔐 Security

Authentication

  • Master password authentication (no user registration required)
  • JWT tokens with configurable expiry
  • Secure password hashing (SHA-256 + salt)
  • Environment-based secret management

API Security

  • All anime/episode endpoints require authentication
  • CORS protection
  • Input validation using Pydantic
  • Error handling without sensitive data exposure

🔧 Configuration

Environment Variables

  • JWT_SECRET_KEY: Secret key for JWT token signing
  • PASSWORD_SALT: Salt for password hashing
  • MASTER_PASSWORD: Master password (development only)
  • MASTER_PASSWORD_HASH: Hashed master password (production)
  • SESSION_TIMEOUT_HOURS: JWT token expiry time
  • ANIME_DIRECTORY: Path to anime files
  • LOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR)

Production Configuration

  1. Set MASTER_PASSWORD_HASH instead of MASTER_PASSWORD
  2. Use a strong JWT_SECRET_KEY
  3. Set appropriate CORS_ORIGINS
  4. Configure proper logging levels

📊 API Status

Endpoint Category Status Coverage
Authentication Complete 100%
Health/System Complete 100%
Anime Search Implemented Mock data
Episode Management Implemented Mock data
Database Integration 🔄 Placeholder Todo
Real Data Provider 🔄 Placeholder Todo

🚧 Future Enhancements

High Priority

  • Connect to actual anime database/provider
  • Implement real anime search functionality
  • Add episode streaming capabilities
  • Database connection pooling

Medium Priority

  • Redis caching layer
  • Rate limiting middleware
  • Background task processing
  • WebSocket support

Low Priority

  • Advanced search filters
  • User preferences (multi-user support)
  • Download progress tracking
  • Statistics and analytics

📝 License

This project follows the AniWorld project licensing terms.

🤝 Contributing

  1. Follow the coding standards in .github/copilot-instructions.md
  2. Use type hints and Pydantic models
  3. Add comprehensive logging
  4. Include tests for new features
  5. Update documentation

📞 Support


Note: This FastAPI implementation provides a solid foundation following the project instructions. The authentication system is complete and production-ready, while anime/episode endpoints currently return mock data pending integration with the actual data providers.