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

Suno Music API Tutorial: Generate AI Music Programmatically in 2026Tutorial

Suno Music API Tutorial: Generate AI Music Programmatically in 2026

"Learn how to use the Suno Music API to generate songs, lyrics, and instrumentals with code. Includes Python examples, pricing, and integration tips."

Feb 21
Claude Code in CI/CD: Automate Code Reviews, Tests, and Deployments in 2026Tutorial

Claude Code in CI/CD: Automate Code Reviews, Tests, and Deployments in 2026

"Learn how to integrate Claude Code into your CI/CD pipelines for automated code reviews, test generation, and deployment validation. Complete guide with GitHub Actions, GitLab CI, and Jenkins examples."

Apr 13
AI Structured Output Guide 2026: JSON Mode Across OpenAI, Claude, and GeminiTutorial

AI Structured Output Guide 2026: JSON Mode Across OpenAI, Claude, and Gemini

Complete developer guide to structured outputs and JSON mode across OpenAI, Claude, and Gemini APIs — with code examples, schema design tips, and a comparison of reliability across providers.

Apr 8
AI Video Generation APIs Guide 2026 - Sora 2, Veo3, Kling, Luma, and Runway ComparedTutorial

AI Video Generation APIs Guide 2026 - Sora 2, Veo3, Kling, Luma, and Runway Compared

Complete guide to AI video generation APIs including OpenAI Sora 2, Google Veo3, Kling 2.5, Luma Dream Machine, and Runway Gen-4. Code examples and pricing included.

Jan 22
How to Access GPT-5 and GPT-5.2 via API - Complete Developer GuideTutorial

How to Access GPT-5 and GPT-5.2 via API - Complete Developer Guide

Learn how to access OpenAI's latest GPT-5, GPT-5.2, and o3-pro models through a unified API. Step-by-step guide with Python, Node.js, and curl examples.

Jan 22
"How to Get a Claude API Key in 2026: Secure Setup for Local Development and CI"Tutorial

"How to Get a Claude API Key in 2026: Secure Setup for Local Development and CI"

"Learn how to get a Claude API key, configure it safely, rotate credentials, and use an OpenAI-compatible router for team deployments."

Aug 22