Login
Back to Blog
EnglishTutorial

How to Integrate Suno AI Music API: Complete Developer Guide

This tutorial shows you how to integrate Suno AI music generation into your applications using the OpenAI-compatible API format. Generate songs, create lyrics, and build AI-powered music applications.

C
Crazyrouter Team
January 22, 2026 / 1772 views
Share:
How to Integrate Suno AI Music API: Complete Developer Guide

This tutorial shows you how to integrate Suno AI music generation into your applications using the OpenAI-compatible API format. Generate songs, create lyrics, and build AI-powered music applications.

Prerequisites#

  • Python 3.8+ installed
  • An API key from Crazyrouter
  • Basic understanding of REST APIs

Installation#

bash
pip install openai

Quick Start: Your First AI-Generated Song#

Suno uses a dedicated REST API with async task processing:

python
import requests
import time

BASE_URL = "https://crazyrouter.com"
API_KEY = "sk-your-api-key-here"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0"
}

# Submit a music generation task
response = requests.post(
    f"{BASE_URL}/suno/submit/music",
    headers=headers,
    json={
        "gpt_description_prompt": "Create an energetic electronic dance track with a powerful drop",
        "make_instrumental": False
    }
)

result = response.json()
task_id = result["data"]
print(f"Task submitted: {task_id}")

# Poll for results
while True:
    fetch_response = requests.get(
        f"{BASE_URL}/suno/fetch/{task_id}",
        headers=headers
    )
    data = fetch_response.json()["data"]

    if data["status"] == "SUCCESS":
        song = data["data"]
        print(f"Audio URL: {song.get('audio_url')}")
        print(f"Video URL: {song.get('video_url')}")
        break
    elif data["status"] == "FAILED":
        print(f"Failed: {data.get('fail_reason')}")
        break

    print(f"Progress: {data['progress']}")
    time.sleep(5)

API Pricing#

ModelPriceDescription
suno_music$0.55/song*Full AI music generation
suno_lyrics$0.017/request*AI lyrics writing

*Prices shown after 45% discount on Crazyrouter

Advanced: Lyrics Generation#

Generate professional song lyrics before creating music:

python
import requests
import time

BASE_URL = "https://crazyrouter.com"

def generate_lyrics(theme: str, genre: str, mood: str, api_key: str) -> dict:
    """Generate song lyrics with specific parameters."""

    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0"
    }

    prompt = f"""
    Write song lyrics with the following specifications:
    Theme: {theme}
    Genre: {genre}
    Mood: {mood}

    Include verse, chorus, bridge structure.
    """

    # Submit lyrics task
    response = requests.post(
        f"{BASE_URL}/suno/submit/lyrics",
        headers=headers,
        json={"prompt": prompt}
    )
    task_id = response.json()["data"]

    # Poll for results
    while True:
        fetch_response = requests.get(
            f"{BASE_URL}/suno/fetch/{task_id}",
            headers=headers
        )
        data = fetch_response.json()["data"]

        if data["status"] == "SUCCESS":
            return data["data"]
        elif data["status"] == "FAILED":
            raise Exception(data.get("fail_reason"))

        time.sleep(3)

# Example usage
lyrics = generate_lyrics(
    theme="Finding hope after difficult times",
    genre="Pop rock",
    mood="Uplifting and inspirational",
    api_key="sk-your-api-key"
)
print(f"Title: {lyrics['title']}")
print(f"Lyrics:\n{lyrics['text']}")

Genre-Specific Prompts#

Pop Music#

python
pop_prompt = """
Create a catchy pop song with:
- Upbeat tempo around 120 BPM
- Memorable hook in the chorus
- Modern production style
- Theme: celebrating friendship
"""

Hip Hop / Rap#

python
hiphop_prompt = """
Create a hip hop track with:
- Hard-hitting 808 bass
- Trap-style hi-hats
- 90 BPM tempo
- Theme: overcoming obstacles
"""

Ambient / Chill#

python
ambient_prompt = """
Create an ambient chill track with:
- Soft synthesizer pads
- Nature sounds integrated
- Slow tempo around 70 BPM
- Theme: peaceful meditation
"""

Building a Music Generation App#

Here's a complete example of a Flask-based music generation API:

python
from flask import Flask, request, jsonify
from openai import OpenAI

app = Flask(__name__)

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.crazyrouter.com/v1"
)

@app.route('/generate-song', methods=['POST'])
def generate_song():
    data = request.json

    prompt = f"""
    Genre: {data.get('genre', 'pop')}
    Mood: {data.get('mood', 'happy')}
    Theme: {data.get('theme', 'love')}
    Duration: {data.get('duration', '2 minutes')}
    """

    try:
        response = client.chat.completions.create(
            model="suno_music",
            messages=[{"role": "user", "content": prompt}]
        )

        return jsonify({
            "success": True,
            "result": response.choices[0].message.content
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route('/generate-lyrics', methods=['POST'])
def generate_lyrics():
    data = request.json

    prompt = f"Write {data.get('genre', 'pop')} song lyrics about {data.get('theme', 'love')}"

    try:
        response = client.chat.completions.create(
            model="suno_lyrics",
            messages=[{"role": "user", "content": prompt}]
        )

        return jsonify({
            "success": True,
            "lyrics": response.choices[0].message.content
        })
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)

Combining with Other AI Models#

Create a complete music production workflow using multiple AI models:

python
from openai import OpenAI

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.crazyrouter.com/v1"
)

def create_complete_song(concept: str):
    """
    Complete workflow: Concept -> Lyrics -> Music
    """

    # Step 1: Expand the concept using GPT-5
    concept_response = client.chat.completions.create(
        model="gpt-5",
        messages=[{
            "role": "user",
            "content": f"""
            Expand this song concept into detailed specifications:
            Concept: {concept}

            Provide:
            - Genre and sub-genre
            - Tempo (BPM)
            - Key instruments
            - Mood progression
            - Target audience
            """
        }]
    )
    specifications = concept_response.choices[0].message.content

    # Step 2: Generate lyrics using suno_lyrics
    lyrics_response = client.chat.completions.create(
        model="suno_lyrics",
        messages=[{
            "role": "user",
            "content": f"Based on these specifications, write song lyrics:\n{specifications}"
        }]
    )
    lyrics = lyrics_response.choices[0].message.content

    # Step 3: Generate the final song
    music_response = client.chat.completions.create(
        model="suno_music",
        messages=[{
            "role": "user",
            "content": f"""
            Create a song with these specifications:
            {specifications}

            Lyrics:
            {lyrics}
            """
        }]
    )

    return {
        "specifications": specifications,
        "lyrics": lyrics,
        "music": music_response.choices[0].message.content
    }

# Example usage
result = create_complete_song("A nostalgic summer road trip anthem")
print(result)

Error Handling Best Practices#

python
from openai import OpenAI, APIError, RateLimitError
import time

def generate_with_retry(prompt: str, max_retries: int = 3):
    """Generate music with automatic retry on failure."""

    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="suno_music",
                messages=[{"role": "user", "content": prompt}]
            )
            return response.choices[0].message.content

        except RateLimitError:
            wait_time = 2 ** attempt
            print(f"Rate limited. Waiting {wait_time} seconds...")
            time.sleep(wait_time)

        except APIError as e:
            print(f"API error: {e}")
            if attempt == max_retries - 1:
                raise

    return None

Tips for Better Results#

1. Be Specific About Genre#

Instead of just "rock", try "90s alternative rock with grunge influences"

2. Include Technical Details#

Specify BPM, key signature, and instrumentation when possible

3. Describe the Mood Arc#

"Start melancholic, build to hopeful in the chorus"

4. Reference Known Styles#

"Production style similar to The Weeknd's Blinding Lights"

Next Steps#


Need help? Contact support at support@crazyrouter.com

Implementation Guides

Related Posts

AI API Gateway: Architecture, Features, and Vendor Selection GuideTutorial

AI API Gateway: Architecture, Features, and Vendor Selection Guide

Your GenAI feature can hit a wall fast: a free API tier may allow only 60 requests per minute, then return 429 errors during normal team testing. Moving to paid access may raise that to 600 request...

Mar 18
Qwen 2.5 Omni Guide 2026: Building Multimodal Chatbots with Voice and VisionTutorial

Qwen 2.5 Omni Guide 2026: Building Multimodal Chatbots with Voice and Vision

"Build multimodal chatbots with Qwen 2.5 Omni — voice input, image understanding, and text in one model. Includes architecture patterns, code examples, and cost tips."

Apr 18
OpenClaw Applications: 10+ Real-World Use Cases in 2026Tutorial

OpenClaw Applications: 10+ Real-World Use Cases in 2026

Discover 10+ OpenClaw applications from customer support automation to content creation. Learn how businesses use OpenClaw for AI-powered workflows across WhatsApp, Telegram, Discord, and more platforms.

Mar 7
Claude Code Installation and Usage Guide: AI Programming Assistant SetupTutorial

Claude Code Installation and Usage Guide: AI Programming Assistant Setup

Complete guide to installing and configuring Claude Code, the AI programming assistant. Step-by-step instructions for macOS, Linux, and Windows with Crazyrouter API integration.

Feb 23
Function Calling Across AI Providers: A Portable 2026 Implementation GuideTutorial

Function Calling Across AI Providers: A Portable 2026 Implementation Guide

Design portable function calling across OpenAI-compatible, Claude, Gemini, and open-model APIs with schemas, validation, retries, and fallbacks.

Sep 4
How to Get a Claude API Key Safely in 2026Tutorial

How to Get a Claude API Key Safely in 2026

Learn how to get a Claude API key safely, avoid common account and billing mistakes, and start coding with Claude-compatible APIs through Crazyrouter.

Mar 15