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 / 883 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 Batch Processing API Guide 2026: Process Millions of Requests EfficientlyTutorial

AI Batch Processing API Guide 2026: Process Millions of Requests Efficiently

"Complete guide to AI batch processing APIs in 2026. Learn how to process millions of AI requests efficiently using OpenAI Batch API, async patterns, and cost optimization."

Mar 1
Whisper API Guide 2026: Speech-to-Text for DevelopersTutorial

Whisper API Guide 2026: Speech-to-Text for Developers

"Complete guide to OpenAI Whisper API for speech-to-text in 2026. Learn transcription, translation, and integration with code examples in Python and Node.js."

Mar 1
Sora API: The Complete Guide to Building with OpenAI Video GenerationTutorial

Sora API: The Complete Guide to Building with OpenAI Video Generation

OpenAI's current Sora API is asynchronous and tier-based, not a fire-and-forget video button. The official guide recommends polling every 10 to 20 seconds, and Sora access is not available on the F...

Mar 26
AI Content Creation Tools 2026: Complete Guide for CreatorsTutorial

AI Content Creation Tools 2026: Complete Guide for Creators

AI has revolutionized content creation. From writing blog posts to generating images, music, and videos, creators now have powerful tools at their fingertips. This guide covers the best AI content cre...

Jan 26
Kimi K2 Thinking Model: Complete Developer Guide for Reasoning WorkflowsTutorial

Kimi K2 Thinking Model: Complete Developer Guide for Reasoning Workflows

"Complete guide to Moonshot's Kimi K2 Thinking model. Learn chain-of-thought reasoning, benchmark comparisons, API integration, and cost optimization for production."

May 5
GLM 4.6 API Guide 2026: Tool Calling, RAG, and Bilingual AgentsTutorial

GLM 4.6 API Guide 2026: Tool Calling, RAG, and Bilingual Agents

A developer-focused June 2026 guide to GLM 4.6 API, alternatives, implementation patterns, pricing tradeoffs, and when to use Crazyrouter for unified AI API access.

Jun 4