# Co-Prod AI - REST API Documentation

## Overview

The Co-Prod AI platform provides a comprehensive REST API for AI music generation, user management, and all platform features.

**Base URL:** `https://api.coprod.ai` (or your domain)

**Authentication:** Bearer Token (JWT) or Session-based

**Content-Type:** `application/json`

---

## Authentication

### Register User

**POST** `/api/auth/register`

Register a new user account.

**Request Body:**
```json
{
  "email": "user@example.com",
  "username": "producer123",
  "password": "SecurePass123!",
  "first_name": "John",
  "last_name": "Doe"
}
```

**Response (201):**
```json
{
  "success": true,
  "message": "Registration successful. Please check your email to verify your account.",
  "user_id": 123
}
```

### Login

**POST** `/api/auth/login`

Authenticate a user and receive an access token.

**Request Body:**
```json
{
  "email": "user@example.com",
  "password": "SecurePass123!"
}
```

**Response (200):**
```json
{
  "success": true,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": 123,
    "email": "user@example.com",
    "username": "producer123",
    "subscription_tier": "pro"
  }
}
```

### Logout

**POST** `/api/auth/logout`

Invalidate the current session.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "success": true,
  "message": "Logged out successfully"
}
```

---

## User Management

### Get Current User

**GET** `/api/user`

Get the current authenticated user's profile.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "success": true,
  "data": {
    "id": 123,
    "email": "user@example.com",
    "username": "producer123",
    "first_name": "John",
    "last_name": "Doe",
    "avatar": "https://...",
    "bio": "Music producer",
    "subscription_tier": "pro",
    "xp_points": 1500,
    "creativity_score": 75.5,
    "total_generations": 50,
    "total_projects": 10
  }
}
```

### Update User Profile

**PUT** `/api/user`

Update the current user's profile.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "first_name": "John",
  "last_name": "Smith",
  "bio": "Updated bio"
}
```

**Response (200):**
```json
{
  "success": true,
  "message": "Profile updated successfully"
}
```

### Get Producer DNA

**GET** `/api/user/producer-dna`

Get the user's Producer DNA analysis.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "success": true,
  "data": {
    "favorite_genres": ["trap", "drill", "lofi"],
    "favorite_bpms": [140, 145, 85],
    "favorite_scales": ["minor", "harmonic_minor"],
    "favorite_keys": ["C", "F", "G"],
    "favorite_chords": ["i", "VI", "III", "VII"],
    "melodic_tendencies": {
      "preferred_intervals": ["stepwise", "leap"],
      "contour_preference": "ascending"
    }
  }
}
```

### Get Creativity Score

**GET** `/api/user/creativity-score`

Get the user's creativity index and breakdown.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "success": true,
  "data": {
    "overall_score": 75.5,
    "breakdown": {
      "harmonic_diversity": 75,
      "rhythmic_diversity": 68,
      "melodic_diversity": 82,
      "genre_diversity": 60,
      "scale_diversity": 55,
      "arrangement_diversity": 70
    },
    "growth_trend": "improving",
    "creative_block_risk": "low"
  }
}
```

---

## AI Generation

### Generate Melody

**POST** `/api/generate/melody`

Generate a melody using AI.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "genre": "trap",
  "bpm": 140,
  "key": "C",
  "scale": "minor",
  "mood": "dark",
  "energy": "high",
  "complexity": 0.7,
  "humanization": 0.3,
  "note_density": 0.6,
  "melody_length": 8,
  "octave_range": 2
}
```

**Response (200):**
```json
{
  "success": true,
  "generation_id": 456,
  "data": {
    "type": "melody",
    "bpm": 140,
    "key": "C",
    "scale": "minor",
    "genre": "trap",
    "notes": [
      {
        "note": 60,
        "velocity": 100,
        "start_time": 0,
        "duration": 0.5,
        "octave": 4
      }
    ],
    "metadata": {
      "mood": "dark",
      "energy": "high",
      "complexity": 0.7
    }
  }
}
```

### Generate Chord Progression

**POST** `/api/generate/chords`

Generate a chord progression.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "key": "C",
  "scale": "major",
  "genre": "pop",
  "mood": "emotional",
  "complexity": 0.5,
  "length": 4,
  "use_inversions": true,
  "voice_leading": true
}
```

**Response (200):**
```json
{
  "success": true,
  "generation_id": 457,
  "data": {
    "type": "chord_progression",
    "key": "C",
    "scale": "major",
    "progression": [
      {
        "chord": [60, 64, 67],
        "roman_numeral": "I",
        "start_bar": 0,
        "duration_bars": 4
      }
    ]
  }
}
```

### Generate Bassline

**POST** `/api/generate/bassline`

Generate a bassline pattern.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "bpm": 140,
  "key": "C",
  "scale": "minor",
  "genre": "trap",
  "style": "808",
  "energy": "high",
  "length": 8
}
```

### Generate Drum Pattern

**POST** `/api/generate/drums`

Generate a drum pattern.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "bpm": 140,
  "genre": "trap",
  "energy": "high",
  "complexity": 0.7,
  "length": 4,
  "swing": 0.0
}
```

### Generate Arpeggiator

**POST** `/api/generate/arpeggiator`

Generate an arpeggiator pattern.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "bpm": 140,
  "key": "C",
  "scale": "minor",
  "pattern": "up",
  "chord": [0, 4, 7],
  "length": 4,
  "octave_range": 2
}
```

### Generate Counter Melody

**POST** `/api/generate/counter-melody`

Generate a counter melody for an existing melody.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "main_melody": [...],
  "key": "C",
  "scale": "minor",
  "style": "harmony"
}
```

### Generate Song Arrangement

**POST** `/api/generate/arrangement`

Generate a complete song arrangement structure.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "genre": "pop",
  "mood": "emotional",
  "energy": "medium",
  "length": 180
}
```

### Generate Genre Fusion

**POST** `/api/generate/genre-fusion`

Generate a hybrid of two genres.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "genre1": "trap",
  "genre2": "amapiano"
}
```

### Generate Emotion-Based Music

**POST** `/api/generate/emotion`

Generate music based on an emotion.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "emotion": "hope",
  "intensity": 0.7
}
```

### Surprise Me

**POST** `/api/generate/surprise-me`

Generate a complete beat starter pack with random parameters.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Response (200):**
```json
{
  "success": true,
  "generation_id": 458,
  "data": {
    "type": "surprise_me",
    "melody": {...},
    "chords": {...},
    "bassline": {...},
    "drums": {...},
    "metadata": {
      "genre": "afrobeat",
      "key": "F",
      "scale": "dorian",
      "bpm": 115
    }
  }
}
```

### Extreme Inspiration

**POST** `/api/generate/extreme-inspiration`

Generate completely unexpected ideas based on Producer DNA analysis.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Generate Variations

**POST** `/api/generate/variations`

Generate variations of an existing generation.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "original": {...},
  "variation_type": "darker"
}
```

**Variation Types:**
- `darker` - Make the music darker
- `happier` - Make the music happier
- `more_emotional` - Increase emotional depth
- `more_energetic` - Increase energy
- `more_commercial` - Make more radio-friendly
- `more_experimental` - Make more experimental

### Get Generation Status

**GET** `/api/generate/{id}/status`

Check the status of a generation.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (200):**
```json
{
  "success": true,
  "status": "completed",
  "error_message": null
}
```

**Status Values:**
- `pending` - Queued for processing
- `processing` - Currently being generated
- `completed` - Generation finished successfully
- `failed` - Generation failed

### Cancel Generation

**POST** `/api/generate/{id}/cancel`

Cancel a pending or processing generation.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

---

## Projects

### Get Projects

**GET** `/api/projects`

Get all projects for the current user.

**Headers:**
```
Authorization: Bearer {token}
```

**Query Parameters:**
- `page` (optional) - Page number (default: 1)
- `per_page` (optional) - Items per page (default: 20)
- `genre` (optional) - Filter by genre
- `status` (optional) - Filter by status

**Response (200):**
```json
{
  "success": true,
  "data": [...],
  "pagination": {
    "total": 100,
    "per_page": 20,
    "current_page": 1,
    "last_page": 5
  }
}
```

### Create Project

**POST** `/api/projects`

Create a new project.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "name": "My New Track",
  "description": "A trap beat",
  "bpm": 140,
  "key_signature": "Cm",
  "scale": "minor",
  "genre": "trap",
  "mood": "dark"
}
```

### Get Project

**GET** `/api/projects/{id}`

Get a specific project.

**Headers:**
```
Authorization: Bearer {token}
```

### Update Project

**PUT** `/api/projects/{id}`

Update a project.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Delete Project

**DELETE** `/api/projects/{id}`

Delete a project.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

---

## MIDI Files

### Get MIDI Files

**GET** `/api/midi`

Get all MIDI files for the current user.

**Headers:**
```
Authorization: Bearer {token}
```

### Create MIDI File

**POST** `/api/midi`

Save a new MIDI file.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Download MIDI File

**GET** `/api/midi/{id}/download`

Download a MIDI file.

**Headers:**
```
Authorization: Bearer {token}
```

---

## Idea Vault

### Get Ideas

**GET** `/api/vault`

Get all saved ideas from the Idea Vault.

**Headers:**
```
Authorization: Bearer {token}
```

### Create Idea

**POST** `/api/vault`

Save a new idea to the vault.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Favorite Idea

**POST** `/api/vault/{id}/favorite`

Toggle favorite status for an idea.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Merge Ideas

**POST** `/api/vault/{id}/merge`

Merge multiple ideas into a new concept.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

---

## Challenges

### Get Challenges

**GET** `/api/challenges`

Get available challenges.

**Headers:**
```
Authorization: Bearer {token}
```

### Join Challenge

**POST** `/api/challenges/{id}/join`

Join a challenge.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Submit Challenge

**POST** `/api/challenges/{id}/submit`

Submit a challenge entry.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Get Challenge Progress

**GET** `/api/challenges/{id}/progress`

Get progress for a specific challenge.

**Headers:**
```
Authorization: Bearer {token}
```

---

## Marketplace

### Get Marketplace Items

**GET** `/api/marketplace`

Browse marketplace items.

**Headers:**
```
Authorization: Bearer {token}
```

### Create Marketplace Listing

**POST** `/api/marketplace`

Create a new marketplace listing.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Purchase Item

**POST** `/api/marketplace/{id}/purchase`

Purchase a marketplace item.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Add Review

**POST** `/api/marketplace/{id}/review`

Add a review to a marketplace item.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

---

## Subscription

### Get Subscription

**GET** `/api/subscription`

Get current subscription details.

**Headers:**
```
Authorization: Bearer {token}
```

### Checkout

**POST** `/api/subscription/checkout`

Initiate subscription checkout.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "plan": "pro",
  "interval": "monthly"
}
```

### Cancel Subscription

**POST** `/api/subscription/cancel`

Cancel current subscription.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Webhook

**POST** `/api/subscription/webhook`

Handle Stripe webhook events.

---

## Export

### Export

**POST** `/api/export`

Export a generation or project.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

**Request Body:**
```json
{
  "type": "midi",
  "generation_id": 456,
  "format": "standard"
}
```

**Export Types:**
- `midi` - MIDI file
- `wav` - WAV audio file
- `mp3` - MP3 audio file
- `zip_project` - Complete project as ZIP

### Download Export

**GET** `/api/export/{id}/download`

Download an exported file.

**Headers:**
```
Authorization: Bearer {token}
```

---

## Analytics

### Track Event

**POST** `/api/analytics`

Track an analytics event.

**Headers:**
```
Authorization: Bearer {token}
```

**Request Body:**
```json
{
  "event_type": "generation_complete",
  "event_data": {
    "generation_type": "melody",
    "genre": "trap"
  }
}
```

### Get User Analytics

**GET** `/api/analytics/user`

Get analytics data for the current user.

**Headers:**
```
Authorization: Bearer {token}
```

---

## Notifications

### Get Notifications

**GET** `/api/notifications`

Get user notifications.

**Headers:**
```
Authorization: Bearer {token}
```

### Mark as Read

**PUT** `/api/notifications/{id}/read`

Mark a notification as read.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

### Mark All as Read

**PUT** `/api/notifications/read-all`

Mark all notifications as read.

**Headers:**
```
Authorization: Bearer {token}
X-CSRF-Token: {csrf_token}
```

---

## Error Responses

All endpoints may return error responses in the following format:

**400 Bad Request:**
```json
{
  "error": "Invalid request data",
  "details": "..."
}
```

**401 Unauthorized:**
```json
{
  "error": "Authentication required"
}
```

**403 Forbidden:**
```json
{
  "error": "Access denied",
  "reason": "Subscription upgrade required"
}
```

**404 Not Found:**
```json
{
  "error": "Resource not found"
}
```

**429 Too Many Requests:**
```json
{
  "error": "Rate limit exceeded",
  "retry_after": 60
}
```

**500 Internal Server Error:**
```json
{
  "error": "Internal server error"
}
```

---

## Rate Limiting

API requests are rate limited to prevent abuse:

- **Free Plan:** 100 requests per minute
- **Pro Plan:** 500 requests per minute
- **Producer Plus:** Unlimited

Rate limit headers are included in responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1625097600
```

---

## WebSocket API

For real-time generation updates, use the WebSocket endpoint:

**URL:** `wss://api.coprod.ai/ws`

**Connection:**
```javascript
const ws = new WebSocket('wss://api.coprod.ai/ws?token=YOUR_TOKEN');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch (data.type) {
    case 'generation_progress':
      console.log('Generation progress:', data.progress);
      break;
    case 'generation_complete':
      console.log('Generation complete:', data.result);
      break;
    case 'notification':
      console.log('New notification:', data.notification);
      break;
  }
};
```

---

## SDK Examples

### JavaScript/Node.js

```javascript
const API_BASE = 'https://api.coprod.ai';

async function generateMelody(token, params) {
  const response = await fetch(`${API_BASE}/api/generate/melody`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      'X-CSRF-Token': getCSRFToken()
    },
    body: JSON.stringify(params)
  });
  
  return response.json();
}
```

### Python

```python
import requests

API_BASE = 'https://api.coprod.ai'

def generate_melody(token, params):
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
        'X-CSRF-Token': get_csrf_token()
    }
    
    response = requests.post(
        f'{API_BASE}/api/generate/melody',
        headers=headers,
        json=params
    )
    
    return response.json()
```

---

## Support

For API support, contact: api-support@coprod.ai

Documentation version: 1.0.0
Last updated: June 2026
