Aniworld/docs/api_reference.md
Lukas 85a6b053eb Phase 8: Documentation and deprecation warnings for identifier standardization
- Enhanced infrastructure.md with identifier convention table, format requirements, migration notes
- Updated docs/README.md with series identifier convention section
- Updated docs/api_reference.md with key-based API examples and notes
- Added deprecation warnings to SerieList.get_by_folder()
- Added deprecation warnings to anime.py folder fallback lookup
- Added deprecation warnings to validate_series_key_or_folder()
- All warnings include v3.0.0 removal timeline
- All 1006 tests pass
2025-11-28 18:06:04 +01:00

1425 lines
25 KiB
Markdown

# Aniworld API Reference
Complete API reference documentation for the Aniworld Download Manager Web Application.
## Table of Contents
1. [API Overview](#api-overview)
2. [Authentication](#authentication)
3. [Error Handling](#error-handling)
4. [API Endpoints](#api-endpoints)
- [Authentication Endpoints](#authentication-endpoints)
- [Configuration Endpoints](#configuration-endpoints)
- [Anime Endpoints](#anime-endpoints)
- [Download Queue Endpoints](#download-queue-endpoints)
- [WebSocket Endpoints](#websocket-endpoints)
- [Health Check Endpoints](#health-check-endpoints)
- [Scheduler Endpoints](#scheduler-endpoints)
- [Logging Endpoints](#logging-endpoints)
- [Diagnostics Endpoints](#diagnostics-endpoints)
- [Extended Configuration Endpoints](#extended-configuration-endpoints)
## API Overview
The Aniworld API is a RESTful API built with FastAPI that provides programmatic access to the anime download manager functionality.
**Base URL**: `http://localhost:8000/api`
**API Documentation**: Available at `http://localhost:8000/api/docs` (Swagger UI) and `http://localhost:8000/api/redoc` (ReDoc)
**API Version**: 1.0.0
**Response Format**: All responses are JSON-formatted unless otherwise specified.
## Authentication
### Master Password Authentication
The API uses JWT (JSON Web Tokens) for stateless authentication. All protected endpoints require a valid JWT token in the Authorization header.
### Authentication Flow
1. **Setup** (one-time): POST to `/api/auth/setup` with master password
2. **Login**: POST to `/api/auth/login` with master password to receive JWT token
3. **Request**: Include token in `Authorization: Bearer <token>` header
### Token Details
- **Token Type**: JWT (JSON Web Token)
- **Expires In**: Configurable (default: 24 hours)
- **Algorithm**: HS256
- **Scope**: All resources accessible with single token
### Example Authentication
```bash
# Login
curl -X POST http://localhost:8000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"password": "your_master_password"}'
# Response
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}
# Use token in subsequent requests
curl -X GET http://localhost:8000/api/anime \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
## Error Handling
### Error Response Format
All errors follow a consistent JSON format:
```json
{
"success": false,
"error": "ERROR_CODE",
"message": "Human-readable error message",
"details": {
"additional": "context"
},
"request_id": "unique-request-identifier"
}
```
### HTTP Status Codes
| Code | Meaning | Description |
| ---- | --------------------- | ---------------------------------------- |
| 200 | OK | Successful request |
| 201 | Created | Resource created successfully |
| 204 | No Content | Successful request with no response body |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Authentication required or failed |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 409 | Conflict | Resource conflict |
| 422 | Unprocessable Entity | Validation error |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server error |
### Error Codes
| Error Code | HTTP Status | Description |
| --------------------- | ----------- | ------------------------- |
| AUTHENTICATION_ERROR | 401 | Authentication failed |
| AUTHORIZATION_ERROR | 403 | Insufficient permissions |
| VALIDATION_ERROR | 422 | Request validation failed |
| NOT_FOUND | 404 | Resource not found |
| CONFLICT | 409 | Resource conflict |
| RATE_LIMIT_EXCEEDED | 429 | Rate limit exceeded |
| INTERNAL_SERVER_ERROR | 500 | Internal server error |
| DOWNLOAD_ERROR | 500 | Download operation failed |
| CONFIGURATION_ERROR | 500 | Configuration error |
| PROVIDER_ERROR | 500 | Provider error |
| DATABASE_ERROR | 500 | Database operation failed |
### Example Error Response
```json
{
"success": false,
"error": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": {
"field": "anime_id",
"issue": "Invalid anime ID format"
},
"request_id": "550e8400-e29b-41d4-a716-446655440000"
}
```
## API Endpoints
### Authentication Endpoints
#### Setup Master Password
Configures the master password for the application (one-time only).
```http
POST /api/auth/setup
Content-Type: application/json
{
"master_password": "your_secure_password"
}
```
**Response (201 Created)**:
```json
{
"status": "ok"
}
```
**Errors**:
- `400 Bad Request`: Master password already configured
- `422 Validation Error`: Invalid password format
---
#### Login
Authenticates with master password and returns JWT token.
```http
POST /api/auth/login
Content-Type: application/json
{
"password": "your_master_password"
}
```
**Response (200 OK)**:
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer"
}
```
**Errors**:
- `401 Unauthorized`: Invalid password
- `429 Too Many Requests`: Too many failed attempts
---
#### Logout
Invalidates the current session.
```http
POST /api/auth/logout
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Logged out successfully"
}
```
---
#### Check Authentication Status
Verifies current authentication status.
```http
GET /api/auth/status
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"authenticated": true,
"token_valid": true
}
```
**Errors**:
- `401 Unauthorized`: Token invalid or expired
---
### Configuration Endpoints
#### Get Configuration
Retrieves the current application configuration.
```http
GET /api/config
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"data": {
"anime_directory": "/path/to/anime",
"download_directory": "/path/to/downloads",
"session_timeout_hours": 24,
"log_level": "info"
}
}
```
---
#### Update Configuration
Updates application configuration (creates backup automatically).
```http
PUT /api/config
Authorization: Bearer <token>
Content-Type: application/json
{
"anime_directory": "/new/anime/path",
"download_directory": "/new/download/path"
}
```
**Response (200 OK)**:
```json
{
"success": true,
"data": {
"anime_directory": "/new/anime/path",
"download_directory": "/new/download/path"
}
}
```
**Errors**:
- `400 Bad Request`: Invalid configuration
- `422 Validation Error`: Validation failed
---
#### Validate Configuration
Validates configuration without applying changes.
```http
POST /api/config/validate
Authorization: Bearer <token>
Content-Type: application/json
{
"anime_directory": "/path/to/validate"
}
```
**Response (200 OK)**:
```json
{
"success": true,
"valid": true,
"message": "Configuration is valid"
}
```
---
#### List Configuration Backups
Lists all configuration backups.
```http
GET /api/config/backups
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"data": [
{
"name": "backup_2025-10-22_12-30-45",
"created_at": "2025-10-22T12:30:45Z",
"size_bytes": 1024
}
]
}
```
---
#### Create Configuration Backup
Creates a manual backup of current configuration.
```http
POST /api/config/backups
Authorization: Bearer <token>
```
**Response (201 Created)**:
```json
{
"success": true,
"data": {
"name": "backup_2025-10-22_12-35-20",
"created_at": "2025-10-22T12:35:20Z"
}
}
```
---
#### Restore Configuration from Backup
Restores configuration from a specific backup.
```http
POST /api/config/backups/{backup_name}/restore
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Configuration restored successfully"
}
```
**Errors**:
- `404 Not Found`: Backup not found
---
#### Delete Configuration Backup
Deletes a specific configuration backup.
```http
DELETE /api/config/backups/{backup_name}
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Backup deleted successfully"
}
```
---
### Anime Endpoints
> **Note on Identifiers**: All anime endpoints use `key` as the primary series identifier (e.g., `"attack-on-titan"`).
> The `folder` field is metadata only and should not be used for lookups.
> For backward compatibility, folder-based lookups are supported but deprecated.
#### List Anime with Missing Episodes
Lists all anime series with missing episodes.
```http
GET /api/anime
Authorization: Bearer <token>
```
**Query Parameters**:
- `page` (integer, optional): Page number for pagination (default: 1)
- `per_page` (integer, optional): Items per page (default: 20)
- `sort_by` (string, optional): Sort field (name, updated_at)
- `sort_order` (string, optional): Sort order (asc, desc)
**Response (200 OK)**:
```json
[
{
"key": "attack-on-titan",
"name": "Attack on Titan",
"folder": "Attack on Titan (2013)",
"missing_episodes": 5,
"link": "https://aniworld.to/anime/stream/attack-on-titan"
},
{
"key": "demon-slayer",
"name": "Demon Slayer",
"folder": "Demon Slayer (2019)",
"missing_episodes": 2,
"link": "https://aniworld.to/anime/stream/demon-slayer"
}
]
```
---
#### Get Anime Details
Retrieves detailed information for a specific anime series.
```http
GET /api/anime/{anime_id}
Authorization: Bearer <token>
```
**Path Parameters**:
- `anime_id` (string): Series `key` (preferred) or `folder` (deprecated)
**Response (200 OK)**:
```json
{
"key": "attack-on-titan",
"title": "Attack on Titan",
"folder": "Attack on Titan (2013)",
"episodes": ["S01-E01", "S01-E02", "S02-E01"],
"description": "Anime description..."
}
```
**Errors**:
- `404 Not Found`: Anime not found
---
#### Trigger Local Rescan
Rescans the local anime directory for new series and episodes.
```http
POST /api/anime/rescan
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Rescan started",
"new_series": 2,
"new_episodes": 15
}
```
---
#### Search Anime on Provider
Searches for anime on the configured provider.
```http
GET /api/v1/anime/search?q={query}
Authorization: Bearer <token>
```
**Query Parameters**:
- `q` (string, required): Search query
- `limit` (integer, optional): Maximum results (default: 20)
**Response (200 OK)**:
```json
{
"success": true,
"data": [
{
"key": "aniworld_789",
"name": "Search Result 1",
"site": "https://provider.com/anime/1"
}
]
}
```
---
### Download Queue Endpoints
> **Note on Identifiers**: Download queue operations use `serie_id` which should be the series `key` (e.g., `"attack-on-titan"`).
> The `serie_folder` field is filesystem metadata and should not be used for identification.
#### Get Queue Status
Retrieves download queue status and statistics.
```http
GET /api/queue/status
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"data": {
"total_items": 15,
"pending": 5,
"downloading": 2,
"completed": 8,
"failed": 0,
"total_size_bytes": 1073741824,
"download_speed_mbps": 5.5
}
}
```
---
#### Add to Download Queue
Adds episodes to the download queue.
```http
POST /api/queue/add
Authorization: Bearer <token>
Content-Type: application/json
{
"serie_id": "attack-on-titan",
"serie_folder": "Attack on Titan (2013)",
"serie_name": "Attack on Titan",
"episodes": ["S01E01", "S01E02"],
"priority": 1
}
```
**Request Fields**:
- `serie_id` (string, required): Series `key` - primary identifier
- `serie_folder` (string, optional): Filesystem folder name (metadata)
- `serie_name` (string, required): Display name
- `episodes` (array, required): List of episodes to download
- `priority` (integer, optional): Priority level (default: 0)
**Response (201 Created)**:
```json
{
"success": true,
"data": {
"queue_item_id": "queue_456",
"serie_id": "attack-on-titan",
"status": "pending"
}
}
```
---
#### Remove from Queue
Removes a specific item from the download queue.
```http
DELETE /api/queue/{queue_item_id}
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Item removed from queue"
}
```
---
#### Start Download Queue
Starts processing the download queue.
```http
POST /api/queue/start
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Queue processing started"
}
```
---
#### Stop Download Queue
Stops download queue processing.
```http
POST /api/queue/stop
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Queue processing stopped"
}
```
---
#### Pause/Resume Queue
Pauses or resumes queue processing.
```http
POST /api/queue/pause
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"success": true,
"message": "Queue paused"
}
```
---
### WebSocket Endpoints
> **Note on Identifiers**: All WebSocket events include `key` as the primary series identifier.
> The `folder` field is included as metadata but should not be used for identification.
#### Real-Time Progress Updates
Establishes WebSocket connection for real-time download progress updates.
```
WS /ws/connect
```
**Connection**:
```javascript
const ws = new WebSocket("ws://localhost:8000/ws/connect");
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log(message);
};
```
**Rooms**: `downloads`, `download_progress`, `scan_progress`
**Message Types**:
**Download Started**:
```json
{
"type": "download_started",
"timestamp": "2025-10-22T12:00:00Z",
"data": {
"download_id": "dl_456",
"key": "attack-on-titan",
"folder": "Attack on Titan (2013)",
"episode": "S01E01"
}
}
```
**Download Progress**:
```json
{
"type": "download_progress",
"timestamp": "2025-10-22T12:00:05Z",
"data": {
"download_id": "dl_456",
"key": "attack-on-titan",
"folder": "Attack on Titan (2013)",
"percent": 45.2,
"speed_mbps": 5.5,
"eta_seconds": 180
}
}
```
**Download Completed**:
```json
{
"type": "download_complete",
"timestamp": "2025-10-22T12:05:00Z",
"data": {
"download_id": "dl_456",
"key": "attack-on-titan",
"folder": "Attack on Titan (2013)",
"file_path": "/path/to/anime/file.mkv"
}
}
```
**Download Error**:
```json
{
"type": "download_failed",
"timestamp": "2025-10-22T12:05:00Z",
"data": {
"download_id": "dl_456",
"key": "attack-on-titan",
"folder": "Attack on Titan (2013)",
"error": "Connection timeout"
}
}
```
```
---
### Health Check Endpoints
#### Basic Health Check
Checks if the application is running.
```http
GET /health
```
**Response (200 OK)**:
```json
{
"status": "healthy",
"version": "1.0.0"
}
```
---
#### Detailed Health Check
Returns comprehensive system health status.
```http
GET /health/detailed
```
**Response (200 OK)**:
```json
{
"status": "healthy",
"version": "1.0.0",
"uptime_seconds": 3600,
"database": {
"status": "connected",
"response_time_ms": 2
},
"filesystem": {
"status": "accessible",
"disk_free_gb": 500
},
"services": {
"anime_service": "ready",
"download_service": "ready"
}
}
```
---
### Scheduler Endpoints
#### Get Scheduler Configuration
Retrieves the current scheduler configuration.
```http
GET /api/scheduler/config
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
{
"enabled": true,
"interval_minutes": 60
}
```
---
#### Update Scheduler Configuration
Updates the scheduler configuration.
```http
POST /api/scheduler/config
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"enabled": true,
"interval_minutes": 120
}
```
**Response (200 OK)**:
```json
{
"enabled": true,
"interval_minutes": 120
}
```
---
#### Trigger Manual Rescan
Manually triggers a library rescan, bypassing the scheduler interval.
```http
POST /api/scheduler/trigger-rescan
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"status": "success",
"message": "Rescan triggered successfully"
}
```
**Errors**:
- `503 Service Unavailable`: SeriesApp not initialized
---
### Logging Endpoints
#### Get Logging Configuration
Retrieves the current logging configuration.
```http
GET /api/logging/config
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
{
"level": "INFO",
"file": null,
"max_bytes": null,
"backup_count": 3
}
```
---
#### Update Logging Configuration
Updates the logging configuration.
```http
POST /api/logging/config
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"level": "DEBUG",
"file": "logs/app.log",
"max_bytes": 10485760,
"backup_count": 5
}
```
**Response (200 OK)**:
```json
{
"level": "DEBUG",
"file": "logs/app.log",
"max_bytes": 10485760,
"backup_count": 5
}
```
---
#### List Log Files
Lists all available log files.
```http
GET /api/logging/files
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
[
{
"name": "app.log",
"size": 1048576,
"modified": 1729612800.0,
"path": "app.log"
},
{
"name": "error.log",
"size": 524288,
"modified": 1729609200.0,
"path": "error.log"
}
]
```
---
#### Download Log File
Downloads a specific log file.
```http
GET /api/logging/files/{filename}/download
Authorization: Bearer <token>
```
**Response (200 OK)**: File download
**Errors**:
- `403 Forbidden`: Access denied to file outside logs directory
- `404 Not Found`: Log file not found
---
#### Tail Log File
Gets the last N lines of a log file.
```http
GET /api/logging/files/{filename}/tail?lines=100
Authorization: Bearer <token> (optional)
```
**Query Parameters**:
- `lines` (integer): Number of lines to retrieve (default: 100)
**Response (200 OK)**: Plain text content with log file tail
---
#### Test Logging
Writes test messages at all log levels.
```http
POST /api/logging/test
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"status": "success",
"message": "Test messages logged at all levels"
}
```
---
#### Cleanup Old Logs
Cleans up old log files.
```http
POST /api/logging/cleanup?max_age_days=30
Authorization: Bearer <token>
Content-Type: application/json
```
**Query Parameters**:
- `max_age_days` (integer): Maximum age in days (default: 30)
**Response (200 OK)**:
```json
{
"files_deleted": 5,
"space_freed": 5242880,
"errors": []
}
```
---
### Diagnostics Endpoints
#### Network Diagnostics
Runs network connectivity diagnostics.
```http
GET /api/diagnostics/network
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
{
"internet_connected": true,
"dns_working": true,
"tests": [
{
"host": "google.com",
"reachable": true,
"response_time_ms": 45.23,
"error": null
},
{
"host": "cloudflare.com",
"reachable": true,
"response_time_ms": 32.1,
"error": null
},
{
"host": "github.com",
"reachable": true,
"response_time_ms": 120.45,
"error": null
}
]
}
```
---
#### System Information
Gets basic system information.
```http
GET /api/diagnostics/system
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
{
"platform": "Linux-5.15.0-generic-x86_64",
"python_version": "3.13.7",
"architecture": "x86_64",
"processor": "x86_64",
"hostname": "aniworld-server"
}
```
---
### Extended Configuration Endpoints
#### Get Advanced Configuration
Retrieves advanced configuration settings.
```http
GET /api/config/section/advanced
Authorization: Bearer <token> (optional)
```
**Response (200 OK)**:
```json
{
"max_concurrent_downloads": 3,
"provider_timeout": 30,
"enable_debug_mode": false
}
```
---
#### Update Advanced Configuration
Updates advanced configuration settings.
```http
POST /api/config/section/advanced
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"max_concurrent_downloads": 5,
"provider_timeout": 60,
"enable_debug_mode": true
}
```
**Response (200 OK)**:
```json
{
"message": "Advanced configuration updated successfully"
}
```
---
#### Update Directory Configuration
Updates the anime directory path.
```http
POST /api/config/directory
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"directory": "/path/to/anime"
}
```
**Response (200 OK)**:
```json
{
"message": "Anime directory updated successfully"
}
```
**Errors**:
- `400 Bad Request`: Directory path is required
---
#### Export Configuration
Exports configuration to a JSON file.
```http
POST /api/config/export
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"include_sensitive": false
}
```
**Response (200 OK)**: JSON file download
---
#### Reset Configuration
Resets configuration to defaults.
```http
POST /api/config/reset
Authorization: Bearer <token>
Content-Type: application/json
```
**Request Body**:
```json
{
"preserve_security": true
}
```
**Response (200 OK)**:
```json
{
"message": "Configuration reset to defaults successfully"
}
```
---
## Rate Limiting
API endpoints are rate-limited to prevent abuse:
- **Default Limit**: 60 requests per minute
- **Response Header**: `X-RateLimit-Remaining` indicates remaining requests
**Rate Limit Error** (429):
```json
{
"success": false,
"error": "RATE_LIMIT_EXCEEDED",
"message": "Rate limit exceeded",
"details": {
"retry_after": 60
}
}
```
---
## Pagination
List endpoints support pagination:
**Query Parameters**:
- `page` (integer): Page number (starts at 1)
- `per_page` (integer): Items per page (default: 20, max: 100)
**Response Format**:
```json
{
"success": true,
"data": [...],
"pagination": {
"total": 150,
"page": 1,
"per_page": 20,
"pages": 8
}
}
```
---
## Request ID Tracking
All requests receive a unique `request_id` for tracking and debugging:
- **Header**: `X-Request-ID`
- **Error Response**: Included in error details
- **Logging**: Tracked in application logs
---
## Timestamps
All timestamps are in ISO 8601 format with UTC timezone:
```
2025-10-22T12:34:56Z
```
---
## Examples
### Complete Download Workflow
```bash
# 1. Setup (one-time)
curl -X POST http://localhost:8000/api/auth/setup \
-H "Content-Type: application/json" \
-d '{"master_password": "secure_pass"}'
# 2. Login
TOKEN=$(curl -X POST http://localhost:8000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"password": "secure_pass"}' | jq -r '.token')
# 3. List anime
curl -X GET http://localhost:8000/api/v1/anime \
-H "Authorization: Bearer $TOKEN"
# 4. Add to queue
curl -X POST http://localhost:8000/api/queue/add \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"anime_id": "aniworld_123", "episodes": ["S01E01"]}'
# 5. Get queue status
curl -X GET http://localhost:8000/api/queue/status \
-H "Authorization: Bearer $TOKEN"
# 6. Start downloads
curl -X POST http://localhost:8000/api/queue/start \
-H "Authorization: Bearer $TOKEN"
# 7. Connect to WebSocket for real-time updates
wscat -c ws://localhost:8000/ws/downloads
```
---
## API Changelog
### Version 1.0.0 (October 22, 2025)
- Initial release
- Authentication system with JWT tokens
- Configuration management with backup/restore
- Anime management endpoints
- Download queue management
- WebSocket real-time updates
- Health check endpoints
- Comprehensive error handling
---
## Support
For additional support, documentation, and examples, see:
- [User Guide](./user_guide.md)
- [Deployment Guide](./deployment.md)
- [Interactive API Docs](http://localhost:8000/api/docs)