Skip to content

Use API to call the music generation AI of suno.ai, and easily integrate it into agents like GPTs.

License

Notifications You must be signed in to change notification settings

haithanh079/suno-api

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Suno AI API

Use API to call the music generation AI of Suno.ai and easily integrate it into agents like GPTs.

👉 We update quickly, please star.

🚀 Recent Updates (Fork by haithanh079)

Important: This fork includes significant improvements to the captcha handling flow based on HAR analysis of Suno.com's actual network behavior.

Key Improvements:

  • 🔧 Fixed Captcha Flow: Corrected the captcha handling mechanism - captcha now only appears after clicking the "Create" button, not before
  • 📊 HAR Analysis: Added comprehensive network flow analysis using extract-har-flow.js to understand Suno's actual API behavior
  • 🤖 Enhanced Browser Automation: Updated getCaptcha() method to properly handle the manual browser flow with form auto-fill
  • 📝 Auto-Fill Support: Automatically fills form fields (prompt, title, tags, instrumental, negative_tags) when parameters are provided
  • 🔄 Manual Flow Handling: When captcha is required, opens browser, waits for user input, handles captcha completion, then closes browser
  • 📚 Documentation: Added comprehensive documentation (CAPTCHA_FLOW_UPDATE.md) explaining the changes and new flow
  • 🔐 Authentication Service: Added AuthService.ts for improved authentication handling
  • 🧪 Testing Tools: Added test scripts and utilities for development and debugging

What This Means:

  • More Reliable: Captcha handling now matches Suno.com's actual behavior
  • Better UX: Form auto-fill reduces manual input when possible
  • Clearer Flow: Users get clear instructions when manual intervention is needed
  • Proper Sequencing: Captcha appears at the correct time in the generation process

Files Added/Modified:

  • extract-har-flow.js - HAR analysis script
  • har-analysis.json - Network flow analysis results
  • CAPTCHA_FLOW_UPDATE.md - Detailed documentation of changes
  • src/lib/SunoApi.ts - Updated captcha handling logic
  • src/lib/AuthService.ts - New authentication service
  • src/app/api/auth/ - New authentication endpoints

English | 简体中文 | русский | Demo | Docs | Deploy with Vercel

gcui-art/suno-api:Open-source SunoAI API - Use API to call the music generation AI of suno.ai. | Product Hunt

🔥 Check out my new project: ReadPo - 10x Speed Up Your Reading and Writing

suno-api banner

Introduction

Suno is an amazing AI music service. Although the official API is not yet available, we couldn't wait to integrate its capabilities somewhere.

We discovered that some users have similar needs, so we decided to open-source this project, hoping you'll like it.

This implementation uses the paid 2Captcha service (a.k.a. ruCaptcha) to solve the hCaptcha challenges automatically and does not use any already made closed-source paid Suno API implementations.

Demo

We have deployed an example bound to a free Suno account, so it has daily usage limits, but you can see how it runs: suno.gcui.ai

Features

  • Perfectly implements the creation API from suno.ai.
  • Automatically keep the account active.
  • Solve CAPTCHAs automatically using 2Captcha and Playwright with rebrowser-patches.
  • Compatible with the format of OpenAI’s /v1/chat/completions API.
  • Supports Custom Mode.
  • One-click deployment to Vercel & Docker.
  • In addition to the standard API, it also adapts to the API Schema of Agent platforms like GPTs and Coze, so you can use it as a tool/plugin/Action for LLMs and integrate it into any AI Agent.
  • Permissive open-source license, allowing you to freely integrate and modify.

Getting Started

1. Authentication Setup

Option A: Using JWT Token (Recommended)

Suno.ai now uses JWT-based authentication through Clerk. You can obtain a JWT token by:

  1. Browser Method:

    • Login to Suno.ai in your browser
    • Open Developer Tools (F12)
    • Go to Application/Storage → Cookies → suno.com
    • Copy the __session cookie value (this is your JWT token)
  2. Environment Variable:

    SUNO_JWT_TOKEN=your_jwt_token_here

Option B: Using Cookie (Legacy Support)

For backward compatibility, you can still use the traditional cookie method:

  1. Head over to suno.com/create using your browser.
  2. Open up the browser console: hit F12 or access the Developer Tools.
  3. Navigate to the Network tab.
  4. Give the page a quick refresh.
  5. Look for requests to clerk.suno.com or studio-api.prod.suno.com
  6. Copy the __client cookie value from the request headers
  7. Set the environment variable:
    SUNO_COOKIE=your_cookie_here

Option C: Automated Authentication (New!)

This fork includes an automated authentication system that eliminates manual token management:

  1. Create Account Configuration File: Create an account.env file in the project root:

    microsoft email: [email protected]
    password: your-password
  2. Enable Automated Authentication:

    USE_AUTOMATED_AUTH=true
  3. Initialize Authentication:

    npm run init-auth
  4. Use in API Requests:

    # Via request body
    curl -X POST "https://your-domain.com/api/generate" \
      -H "Content-Type: application/json" \
      -d '{
        "prompt": "A cheerful pop song about summer vacation",
        "use_automated_auth": true
      }'
    
    # Via header
    curl -X POST "https://your-domain.com/api/generate" \
      -H "Content-Type: application/json" \
      -H "X-Use-Automated-Auth: true" \
      -d '{"prompt": "A cheerful pop song about summer vacation"}'

Benefits of Automated Authentication:

  • ✅ No manual token extraction needed
  • ✅ Automatic session refresh and renewal
  • ✅ Handles Microsoft OAuth flow automatically
  • ✅ Error handling with retry logic
  • ✅ Edge case handling (verification codes, "Stay signed in" dialogs)
  • ✅ Secure credential storage in account.env (not committed to git)

For detailed information, see AUTHENTICATION.md.

2. API Usage Examples

Using JWT Token (Recommended)

# Set JWT token
export SUNO_JWT_TOKEN="your_jwt_token_here"

# Make API request
curl -X POST "https://your-domain.com/api/generate" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your_jwt_token_here" \
  -d '{
    "prompt": "A cheerful pop song about summer vacation",
    "make_instrumental": false,
    "model": "chirp-v3-5"
  }'

Using Cookie (Legacy)

# Set cookie
export SUNO_COOKIE="your_cookie_here"

# Make API request
curl -X POST "https://your-domain.com/api/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A cheerful pop song about summer vacation",
    "make_instrumental": false,
    "model": "chirp-v3-5"
  }'

Using Automated Authentication (Recommended for this fork)

# Enable automated authentication
export USE_AUTOMATED_AUTH=true

# Initialize authentication (run once)
npm run init-auth

# Make API request with automated auth
curl -X POST "https://your-domain.com/api/generate" \
  -H "Content-Type: application/json" \
  -H "X-Use-Automated-Auth: true" \
  -d '{
    "prompt": "A cheerful pop song about summer vacation",
    "make_instrumental": false,
    "model": "chirp-v3-5"
  }'

# Or include in request body
curl -X POST "https://your-domain.com/api/generate" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A cheerful pop song about summer vacation",
    "make_instrumental": false,
    "model": "chirp-v3-5",
    "use_automated_auth": true
  }'

get cookie

3. Register on 2Captcha and top up your balance

2Captcha is a paid CAPTCHA solving service that uses real workers to solve the CAPTCHA and has high accuracy. It is needed because of Suno constantly requesting hCaptcha solving that currently isn't possible for free by any means.

Create a new 2Captcha account, top up your balance and get your API key.

Note

If you are located in Russia or Belarus, use the ruCaptcha interface instead of 2Captcha. It's the same service, but it supports payments from those countries.

Tip

If you want as few CAPTCHAs as possible, it is recommended to use a macOS system. macOS systems usually get fewer CAPTCHAs than Linux and Windows—this is due to its unpopularity in the web scraping industry. Running suno-api on Windows and Linux will work, but in some cases, you could get a pretty large number of CAPTCHAs.

3. Clone and deploy this project

You can choose your preferred deployment method:

Deploy to Vercel

Deploy with Vercel

Run locally

git clone https://github.com/gcui-art/suno-api.git
cd suno-api
npm install

Docker

Important

GPU acceleration will be disabled in Docker. If you have a slow CPU, it is recommended to deploy locally.

Alternatively, you can use Docker Compose. However, follow the step below before running.

docker compose build && docker compose up

4. Configure suno-api

  • If deployed to Vercel, please add the environment variables in the Vercel dashboard.

  • If you’re running this locally, be sure to add the following to your .env file:

Environment variables

Required for Manual Authentication:

  • SUNO_COOKIE — the Cookie header you obtained in the first step.
  • SUNO_JWT_TOKEN — JWT token from Clerk authentication (alternative to cookie).

Required for Automated Authentication (this fork):

  • USE_AUTOMATED_AUTH=true — enables automated authentication system
  • account.env — file containing Microsoft credentials (see setup instructions above)

Required for CAPTCHA Solving:

  • TWOCAPTCHA_KEY — your 2Captcha API key from the second step.

Browser Configuration:

  • BROWSER — the name of the browser that is going to be used to solve the CAPTCHA. Only chromium and firefox supported.
  • BROWSER_GHOST_CURSOR — use ghost-cursor-playwright to simulate smooth mouse movements. Please note that it doesn't seem to make any difference in the rate of CAPTCHAs, so you can set it to false. Retained for future testing.
  • BROWSER_LOCALE — the language of the browser. Using either en or ru is recommended, since those have the most workers on 2Captcha. List of supported languages
  • BROWSER_HEADLESS — run the browser without the window. You probably want to set this to true.

Example .env file:

# Manual Authentication (choose one)
SUNO_COOKIE=<your_cookie_here>
# OR
SUNO_JWT_TOKEN=<your_jwt_token_here>

# Automated Authentication (this fork)
USE_AUTOMATED_AUTH=true

# CAPTCHA Solving
TWOCAPTCHA_KEY=<your_2captcha_key>

# Browser Configuration
BROWSER=chromium
BROWSER_GHOST_CURSOR=false
BROWSER_LOCALE=en
BROWSER_HEADLESS=true

Example account.env file (for automated auth):

microsoft email: [email protected]
password: your-password

5. Run suno-api

  • If you’ve deployed to Vercel:
    • Please click on Deploy in the Vercel dashboard and wait for the deployment to be successful.
    • Visit the https://<vercel-assigned-domain>/api/get_limit API for testing.
  • If running locally:
    • Run npm run dev.
    • Visit the http://localhost:3000/api/get_limit API for testing.
  • If the following result is returned:
{
  "credits_left": 50,
  "period": "day",
  "monthly_limit": 50,
  "monthly_usage": 50
}

it means the program is running normally.

6. Use Suno API

You can check out the detailed API documentation at : suno.gcui.ai/docs

API Reference

Suno API currently mainly implements the following APIs:

- `/api/generate`: Generate music
- `/v1/chat/completions`: Generate music - Call the generate API in a format that works with OpenAI’s API.
- `/api/custom_generate`: Generate music (Custom Mode, support setting lyrics, music style, title, etc.)
- `/api/generate_lyrics`: Generate lyrics based on prompt
- `/api/get`: Get music information based on the id. Use “,” to separate multiple ids.
    If no IDs are provided, all music will be returned.
- `/api/get_limit`: Get quota Info
- `/api/extend_audio`: Extend audio length
- `/api/generate_stems`: Make stem tracks (separate audio and music track)
- `/api/get_aligned_lyrics`: Get list of timestamps for each word in the lyrics
- `/api/clip`: Get clip information based on ID passed as query parameter `id`
- `/api/concat`: Generate the whole song from extensions

You can also specify the cookies in the Cookie header of your request, overriding the default cookies in the SUNO_COOKIE environment variable. This comes in handy when, for example, you want to use multiple free accounts at the same time.

For more detailed documentation, please check out the demo site: suno.gcui.ai/docs

API Integration Code Examples

Python

import time
import requests

# replace with your suno-api URL
base_url = 'http://localhost:3000'


def custom_generate_audio(payload):
    url = f"{base_url}/api/custom_generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def extend_audio(payload):
    url = f"{base_url}/api/extend_audio"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()

def generate_audio_by_prompt(payload):
    url = f"{base_url}/api/generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def get_audio_information(audio_ids):
    url = f"{base_url}/api/get?ids={audio_ids}"
    response = requests.get(url)
    return response.json()


def get_quota_information():
    url = f"{base_url}/api/get_limit"
    response = requests.get(url)
    return response.json()

def get_clip(clip_id):
    url = f"{base_url}/api/clip?id={clip_id}"
    response = requests.get(url)
    return response.json()

def generate_whole_song(clip_id):
    payload = {"clip_id": clip_id}
    url = f"{base_url}/api/concat"
    response = requests.post(url, json=payload)
    return response.json()


if __name__ == '__main__':
    data = generate_audio_by_prompt({
        "prompt": "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
        "make_instrumental": False,
        "wait_audio": False
    })

    ids = f"{data[0]['id']},{data[1]['id']}"
    print(f"ids: {ids}")

    for _ in range(60):
        data = get_audio_information(ids)
        if data[0]["status"] == 'streaming':
            print(f"{data[0]['id']} ==> {data[0]['audio_url']}")
            print(f"{data[1]['id']} ==> {data[1]['audio_url']}")
            break
        # sleep 5s
        time.sleep(5)

JavaScript

const axios = require("axios");

// replace your vercel domain
const baseUrl = "http://localhost:3000";

async function customGenerateAudio(payload) {
  const url = `${baseUrl}/api/custom_generate`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function generateAudioByPrompt(payload) {
  const url = `${baseUrl}/api/generate`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function extendAudio(payload) {
  const url = `${baseUrl}/api/extend_audio`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function getAudioInformation(audioIds) {
  const url = `${baseUrl}/api/get?ids=${audioIds}`;
  const response = await axios.get(url);
  return response.data;
}

async function getQuotaInformation() {
  const url = `${baseUrl}/api/get_limit`;
  const response = await axios.get(url);
  return response.data;
}

async function getClipInformation(clipId) {
  const url = `${baseUrl}/api/clip?id=${clipId}`;
  const response = await axios.get(url);
  return response.data;
}

async function main() {
  const data = await generateAudioByPrompt({
    prompt:
      "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
    make_instrumental: false,
    wait_audio: false,
  });

  const ids = `${data[0].id},${data[1].id}`;
  console.log(`ids: ${ids}`);

  for (let i = 0; i < 60; i++) {
    const data = await getAudioInformation(ids);
    if (data[0].status === "streaming") {
      console.log(`${data[0].id} ==> ${data[0].audio_url}`);
      console.log(`${data[1].id} ==> ${data[1].audio_url}`);
      break;
    }
    // sleep 5s
    await new Promise((resolve) => setTimeout(resolve, 5000));
  }
}

main();

Integration with Custom Agents

You can integrate Suno AI as a tool/plugin/action into your AI agent.

Integration with GPTs

[coming soon...]

Integration with Coze

[coming soon...]

Integration with LangChain

[coming soon...]

Contributing

There are four ways you can support this project:

  1. Fork and Submit Pull Requests: We welcome any PRs that enhance the functionality, APIs, response time and availability. You can also help us just by translating this README into your language—any help for this project is welcome!
  2. Open Issues: We appreciate reasonable suggestions and bug reports.
  3. Donate: If this project has helped you, consider buying us a coffee using the Sponsor button at the top of the project. Cheers! ☕
  4. Spread the Word: Recommend this project to others, star the repo, or add a backlink after using the project.

Questions, Suggestions, Issues, or Bugs?

We use GitHub Issues to manage feedback. Feel free to open an issue, and we'll address it promptly.

License

The license of this project is LGPL-3.0 or later. See LICENSE for more information.

Related Links

Statement

suno-api is an unofficial open source project, intended for learning and research purposes only.

About

Use API to call the music generation AI of suno.ai, and easily integrate it into agents like GPTs.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 87.4%
  • JavaScript 10.3%
  • Dockerfile 2.0%
  • CSS 0.3%