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 / 1717 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

Topics

Tutorial

Related Posts

Streaming API Implementation Guide: Real-Time AI Responses with SSETutorial

Streaming API Implementation Guide: Real-Time AI Responses with SSE

Learn how to implement streaming responses from AI APIs using Server-Sent Events (SSE). Complete guide with Python, Node.js, and cURL examples for OpenAI, Claude, and Gemini.

Feb 20
How to Reduce AI API Costs by 80% - Complete Developer Guide 2026Tutorial

How to Reduce AI API Costs by 80% - Complete Developer Guide 2026

Learn proven strategies to reduce AI API costs by up to 80%. Includes model selection, caching, prompt optimization, and batch processing techniques.

Jan 22
Agentic RAG: Build Smarter AI Agents with Retrieval-Augmented Generation in 2026Tutorial

Agentic RAG: Build Smarter AI Agents with Retrieval-Augmented Generation in 2026

Learn how to build Agentic RAG systems that combine autonomous AI agents with retrieval-augmented generation for dynamic, multi-step reasoning over your own data.

Apr 15
Model Distillation Explained: How Small AI Models Learn from GiantsTutorial

Model Distillation Explained: How Small AI Models Learn from Giants

"A complete guide to knowledge distillation in AI. Learn how DeepSeek, GPT-4o-mini, Gemini Flash, and Claude Haiku were built by distilling larger models, and how developers can use distillation to cut costs."

Mar 30
WAN 2.2 Animate API Tutorial for Developers in 2026Tutorial

WAN 2.2 Animate API Tutorial for Developers in 2026

Learn what WAN 2.2 Animate is, how it compares with other video models, and how developers can build text-to-video workflows using API-based routing.

Mar 17
OpenClaw Tutorial: Complete Getting Started Guide in 2026Tutorial

OpenClaw Tutorial: Complete Getting Started Guide in 2026

A comprehensive OpenClaw tutorial for beginners covering installation, configuration, and deploying your first AI assistant across WhatsApp, Telegram, and Discord in under 20 minutes with step-by-step instructions.

Mar 7