TutorialMusic Generation🎵 Audio Generation2026

How to Use Lyria 2 Music API — Complete Tutorial 2026

Build production-ready AI audio generation in minutes using Lyria 2 Music via NexaAPI on RapidAPI. 2.5x cheaper than the official API.

Introduction

Lyria 2 Music is a cutting-edge AI model by Google for AI music generation from text by Google DeepMind. In 2026, it represents the state of the art in music generation, delivering exceptional quality with fast generation times and reliable API access.

While the official Lyria 2 Music API costs $0.05/gen, NexaAPI provides the same model at just $0.02/gen — that's 2.5x cheaper. NexaAPI is available on RapidAPI, making it easy to integrate into any Python project with a single API key.

In this guide, you'll learn how to integrate Lyria 2 Music into your Python application — from a simple one-liner to production-ready workflows with error handling and retry logic.

Pricing Comparison

ProviderPriceSavingsAccess
Official Google API$0.05/genDirect API
NexaAPI (RapidAPI)$0.02/gen2.5x cheaper ✓RapidAPI

* Prices as of 2026. Pay-per-use, no subscription required.

Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • A free RapidAPI account to get your API key
  • Basic knowledge of Python and HTTP requests

Installation

Install the requests library and set your API key:

pip install requests
# Set your RapidAPI key as environment variable
export RAPIDAPI_KEY="your-rapidapi-key-here"

Complete Python Code

Here's a complete, production-ready Python script for Lyria 2 Music:

import requests
import os

# Get your API key from RapidAPI: https://rapidapi.com/nexaquency/api/lyria-2-music
RAPIDAPI_KEY = os.environ.get("RAPIDAPI_KEY", "your-rapidapi-key-here")
API_HOST = "lyria-2-music.p.rapidapi.com"

def generate(prompt: str, **kwargs) -> dict:
    """
    Generate content using Lyria 2 Music API via NexaAPI on RapidAPI.
    
    Args:
        prompt: Text description of the content to generate
        **kwargs: Additional model-specific parameters
    
    Returns:
        dict with result URL
    """
    url = f"https://{API_HOST}/generate"
    
    headers = {
        "x-rapidapi-key": RAPIDAPI_KEY,
        "x-rapidapi-host": API_HOST,
        "Content-Type": "application/json"
    }
    
    payload = {
        "prompt": prompt,
        **kwargs
    }
    
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    print(f"Generating with Lyria 2 Music...")
    
    result = generate(
        prompt="an uplifting orchestral piece with piano and strings, cinematic, 30 seconds",
    )
    
    output_url = result.get("url") or result.get("audio_url") or result.get("images", [{}])[0].get("url")
    print(f"Output URL: {output_url}")
    print(f"Cost: $0.02/gen via NexaAPI")

Error Handling & Best Practices

For production use, always implement proper error handling:

import requests
import time
import os

RAPIDAPI_KEY = os.environ.get("RAPIDAPI_KEY")
API_HOST = "lyria-2-music.p.rapidapi.com"

def api_call_with_retry(endpoint: str, payload: dict, max_retries: int = 3) -> dict:
    """Make API call with exponential backoff retry."""
    for attempt in range(max_retries):
        try:
            response = requests.post(
                f"https://{API_HOST}/{endpoint}",
                json=payload,
                headers={
                    "x-rapidapi-key": RAPIDAPI_KEY,
                    "x-rapidapi-host": API_HOST,
                    "Content-Type": "application/json"
                },
                timeout=120  # 2 minute timeout for generation
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:
                wait = 2 ** attempt
                print(f"Rate limited. Waiting {wait}s...")
                time.sleep(wait)
            elif e.response.status_code >= 500:
                print(f"Server error. Retry {attempt+1}/{max_retries}")
                time.sleep(2)
            else:
                raise
        except requests.exceptions.Timeout:
            print(f"Timeout. Retry {attempt+1}/{max_retries}")
            time.sleep(5)
    raise Exception(f"Failed after {max_retries} retries")

Common Use Cases

📱 App Development

Power music generation features in your SaaS app without managing model infrastructure.

🎬 Content Creation

Generate professional audio content at scale for marketing, social media, and entertainment.

🤖 Automation

Batch process audio generation tasks programmatically in your data pipelines.

💼 Enterprise

Integrate Lyria 2 Music into enterprise workflows with reliable uptime and pay-per-use pricing.

Lyria 2 Music — Pros & Cons

✅ Pros

  • • State-of-the-art music generation quality
  • • Fast generation with reliable uptime
  • • Simple REST API, works with any language
  • • Available via RapidAPI with pay-per-use pricing
  • • 2.5x cheaper than official API via NexaAPI

❌ Cons

  • • Requires API key management
  • • Generation time varies with server load
  • • Content policy restrictions apply
  • • No free tier (pay-per-use only)

Conclusion

Lyria 2 Music delivers outstanding AI music generation from text by Google DeepMind capabilities in 2026. By accessing it through NexaAPI on RapidAPI, you get the same model quality at 2.5x the cost of the official API — with no infrastructure management, no minimum commitment, and a simple REST interface.

Whether you're building a production SaaS app, prototyping a new feature, or running batch audio generation pipelines, NexaAPI's Lyria 2 Music endpoint is the most cost-effective way to get started in 2026.

Start Using Lyria 2 Music API Today

Get access to Lyria 2 Music at $0.02/gen — 2.5x cheaper than official pricing. No subscription required.

Subscribe on RapidAPI →

Questions? Email us at [email protected]