Aniworld/docs/api_reference.md
2025-10-22 11:30:04 +02:00

944 lines
17 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)
## 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
#### List Anime with Missing Episodes
Lists all anime series with missing episodes.
```http
GET /api/v1/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
[
{
"id": "aniworld_123",
"title": "Attack on Titan",
"missing_episodes": 5
},
{
"id": "aniworld_456",
"title": "Demon Slayer",
"missing_episodes": 2
}
]
```
---
#### Get Anime Details
Retrieves detailed information for a specific anime series.
```http
GET /api/v1/anime/{anime_id}
Authorization: Bearer <token>
```
**Response (200 OK)**:
```json
{
"id": "aniworld_123",
"title": "Attack on Titan",
"episodes": ["Season 1 Episode 1", "Season 1 Episode 2"],
"description": "Anime description...",
"total_episodes": 100,
"downloaded_episodes": 95
}
```
**Errors**:
- `404 Not Found`: Anime not found
---
#### Trigger Local Rescan
Rescans the local anime directory for new series and episodes.
```http
POST /api/v1/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
#### 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
{
"anime_id": "aniworld_123",
"episodes": ["S01E01", "S01E02"],
"priority": "normal"
}
```
**Priority Values**: `low`, `normal`, `high`
**Response (201 Created)**:
```json
{
"success": true,
"data": {
"queue_item_id": "queue_456",
"anime_id": "aniworld_123",
"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
#### Real-Time Progress Updates
Establishes WebSocket connection for real-time download progress updates.
```
WS /ws/downloads
```
**Connection**:
```javascript
const ws = new WebSocket("ws://localhost:8000/ws/downloads");
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log(message);
};
```
**Message Types**:
**Download Started**:
```json
{
"type": "download_started",
"timestamp": "2025-10-22T12:00:00Z",
"data": {
"queue_item_id": "queue_456",
"anime_title": "Attack on Titan",
"episode": "S01E01"
}
}
```
**Download Progress**:
```json
{
"type": "download_progress",
"timestamp": "2025-10-22T12:00:05Z",
"data": {
"queue_item_id": "queue_456",
"progress_percent": 45,
"downloaded_bytes": 500000000,
"total_bytes": 1100000000,
"speed_mbps": 5.5
}
}
```
**Download Completed**:
```json
{
"type": "download_completed",
"timestamp": "2025-10-22T12:05:00Z",
"data": {
"queue_item_id": "queue_456",
"total_time_seconds": 300,
"file_path": "/path/to/anime/file.mkv"
}
}
```
**Download Error**:
```json
{
"type": "download_error",
"timestamp": "2025-10-22T12:05:00Z",
"data": {
"queue_item_id": "queue_456",
"error_message": "Connection timeout",
"error_code": "PROVIDER_ERROR"
}
}
```
---
### 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"
}
}
```
---
## 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)