Quick Start
This quick start gets you set up with the Cyanite REST API. We will go through the process of starting a handler for analysis notifications, uploading content to Cyanite, and then retrieving the results once the analysis is ready.
The Cyanite REST API analysis flow is asynchronous, meaning that there's a gap in time between uploading your music and the completion of the analysis. We use a Webhook to notify you when the analysis is completed for a track.
We'll cover how to
- Implement a Webhook handler to receive the notification of the analysis becoming available
- Upload a file to the Cyanite API with your API key in place
- Make an API call to retrieve the results
Preparation
To use the Cyanite REST API, you will need an API key. Please contact us to request access if you have not already received your credentials.
To progress through this tutorial, you will need an MP3 file to upload. If you don't have a file handy, have a look through Wikimedia Commons for a track you like. Make sure that it's an MP3 - you can use ffmpeg, among other tools, to convert to mp3.
We use a Webhook to notify you that your results are available. Please provide your Webhook URL when requesting API access, and we will configure it for your account. We will also provide you with a Webhook Secret, which you can use to verify the authenticity of any requests to your Webhook endpoint.
Set your API key and webhook secret as environment variables. The secret you
receive is base64-encoded. Add the whsec_ prefix that
Standard Webhooks secrets carry:
export CYANITE_API_KEY=your_api_key_here
export CYANITE_WEBHOOK_SECRET=whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw
Choosing a Webhook URL
In a fully synchronous REST API, the customer makes requests to the server for data and state modifications over HTTP. In an asynchronous API, some workflows involve having the server make an HTTP request to the customer.
A Webhook is an endpoint that you implement so that Cyanite can call you. In practice, this means that you will implement an API endpoint accessible on the public internet, and configure Cyanite to make a call to this URL when certain events happen within our systems (the completion or failure of music file processing).
We'll cover how you can use the Webhook Secret to verify that a request to your endpoint came from Cyanite.
When you're implementing your integration, you'll need a URL accessible via the public internet that Cyanite can call. In development, you can achieve this in several ways:
- You can use a cloud tunnel service to expose your locally running webserver to the public internet. You will need to make sure that the URL remains stable. If your URL changes, Cyanite will need to update the configured webhook url.
- Use a webhook management service such as webhook.site to receive and forward notifications
- You can write your code directly on a machine that's exposed to the public internet via the various tools available (editing over SSH, FTP file upload, in-browser code editor from your service provider, etc.)
While cloud tunnel or webhook management services are useful in development, we do not recommend their use in a production environment. Instead, you should use typical web hosting of your application/handler.
Step 1: Start your webhook handler
The handler receives the notification, verifies its signature, and fetches the
track's results as model outputs with
GET /v1/library-tracks/{id}/models.
Run it so that it's reachable at your webhook URL. The TypeScript and Python
examples listen on port 8080 and accept notifications on any path.
The webhook endpoint needs to be accessible via the public internet by Cyanite's servers. For example, you could deploy it to a server using the domain and endpoint URL https://receiver.example.com/webhooks/cyanite-webhook. This would then be your webhook URL you provide to Cyanite for configuration.
Let's see how to implement a webhook handler to receive the notification and retrieve the analysis results.
- Typescript
- PHP
- Python
Install the Standard Webhooks library:
npm install standardwebhooks
import { createServer } from "node:http";
import { Webhook } from "standardwebhooks";
type Notification = { type: string; data: { track: { id: string } } };
const webhook = new Webhook(process.env.CYANITE_WEBHOOK_SECRET!);
createServer((req, res) => {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", async () => {
// Verify the signature on the raw body before doing anything else
let payload: Notification;
try {
payload = webhook.verify(body, {
"webhook-id": req.headers["webhook-id"] as string,
"webhook-timestamp": req.headers["webhook-timestamp"] as string,
"webhook-signature": req.headers["webhook-signature"] as string,
}) as Notification;
} catch {
res.writeHead(400);
res.end();
return;
}
try {
const trackId = payload.data.track.id;
const musicDataResponse = await fetch(
`https://rest-api.cyanite.ai/v1/library-tracks/${trackId}/models?model=TempoV1&model=KeyV2&model=BpmV2`,
{ headers: { "x-api-key": process.env.CYANITE_API_KEY! } },
);
if (!musicDataResponse.ok) {
throw new Error(`Cyanite API responded with ${musicDataResponse.status}`);
}
const musicData = await musicDataResponse.json();
console.log(payload.type, trackId, JSON.stringify(musicData, null, 2));
// Acknowledge only after the notification has been handled
res.writeHead(200);
res.end();
} catch (err) {
// Any status other than 2xx makes Cyanite retry the notification
res.writeHead(500);
res.end();
}
});
}).listen(process.env.PORT || 8080);
This example is a Laravel route. Add it to routes/api.php, which makes your
webhook URL https://<your-domain>/api/cyanite-webhook. Since Laravel 11,
routes/api.php only exists after you run php artisan install:api. Routes
in routes/web.php are protected against CSRF and reject every notification
with 419. Install the Standard Webhooks library:
composer require standard-webhooks/standard-webhooks
Read the environment variables in config/services.php. Calling env()
elsewhere returns null once the configuration is cached with
php artisan config:cache:
'cyanite' => [
'api_key' => env('CYANITE_API_KEY'),
'webhook_secret' => env('CYANITE_WEBHOOK_SECRET'),
],
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use StandardWebhooks\Webhook;
use StandardWebhooks\Exception\WebhookVerificationException;
Route::post('/cyanite-webhook', function (Request $request) {
// Verify the signature on the raw body before doing anything else
try {
$payload = (new Webhook(config('services.cyanite.webhook_secret')))->verify(
$request->getContent(),
[
'webhook-id' => $request->header('webhook-id'),
'webhook-timestamp' => $request->header('webhook-timestamp'),
'webhook-signature' => $request->header('webhook-signature'),
]
);
} catch (WebhookVerificationException $e) {
return response()->json(['error' => 'Invalid signature'], 400);
}
$trackId = $payload['data']['track']['id'];
$musicData = Http::withHeaders([
'x-api-key' => config('services.cyanite.api_key'),
])->get("https://rest-api.cyanite.ai/v1/library-tracks/{$trackId}/models?model=TempoV1&model=KeyV2&model=BpmV2")
->throw() // Turn an API error into an exception
->json();
Log::info($payload['type'], ['trackId' => $trackId, 'musicData' => $musicData]);
// Acknowledge only after the notification has been handled. If this
// code throws, Laravel responds with 500 and Cyanite retries.
return response()->json([], 200);
});
Install the Standard Webhooks library and requests:
pip install standardwebhooks requests
import http.server
import json
import os
import requests
from standardwebhooks.webhooks import Webhook, WebhookVerificationError
webhook = Webhook(os.environ["CYANITE_WEBHOOK_SECRET"])
class WebhookHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
# Verify the signature on the raw body before doing anything else
try:
payload = webhook.verify(
body.decode("utf-8"),
{
"webhook-id": self.headers.get("webhook-id", ""),
"webhook-timestamp": self.headers.get("webhook-timestamp", ""),
"webhook-signature": self.headers.get("webhook-signature", ""),
},
)
except WebhookVerificationError:
self.send_response(400)
self.end_headers()
return
track_id = payload["data"]["track"]["id"]
response = requests.get(
f"https://rest-api.cyanite.ai/v1/library-tracks/{track_id}/models",
params={"model": ["TempoV1", "KeyV2", "BpmV2"]},
headers={"x-api-key": os.environ["CYANITE_API_KEY"]},
)
response.raise_for_status()
print(payload["type"], track_id, json.dumps(response.json(), indent=2))
# Acknowledge only after the notification has been handled. If the
# code above raises, no response is sent, and Cyanite retries.
self.send_response(200)
self.end_headers()
port = int(os.environ.get("PORT", 8080))
http.server.HTTPServer(("0.0.0.0", port), WebhookHandler).serve_forever()
Cyanite treats any 2xx response as delivered and retries the notification
otherwise. That's why the handler only responds with 200 after verifying and
handling it. It's kept short for this tutorial: for production, see
Understanding Webhooks.
Step 2: Upload your track to Cyanite
In order for Cyanite to analyze and tag your track, you will need to upload it via our API.
If your integration involves first uploading content to your own system via HTTP, make sure that your max upload size is configured appropriately.
Cyanite supports audio files that meet all of the following criteria:
- MP3 format
- Up to 20 MB in size
- Up to 15 minutes in total length
- Typescript
- PHP
- Python
import { readFile } from "node:fs/promises";
async function uploadTrack() {
const fileData = await readFile("/path/to/your/track.mp3");
const formData = new FormData();
formData.append("title", "your_track_name");
formData.append("inputType", "MP3");
formData.append("file", new File([new Uint8Array(fileData)], "track.mp3", { type: "audio/mpeg" }));
const response = await fetch("https://rest-api.cyanite.ai/v1/library-tracks", {
method: "POST",
headers: { "x-api-key": process.env.CYANITE_API_KEY! },
body: formData,
});
if (!response.ok) {
throw new Error(`Cyanite API responded with ${response.status}: ${await response.text()}`);
}
const { trackId } = await response.json();
console.log(trackId);
}
uploadTrack();
<?php
use Illuminate\Support\Facades\Http;
$response = Http::withHeaders([
'x-api-key' => config('services.cyanite.api_key'),
])->attach(
'file', fopen('/path/to/your/track.mp3', 'r'), 'track.mp3'
)->post('https://rest-api.cyanite.ai/v1/library-tracks', [
'title' => 'your_track_name',
'inputType' => 'MP3',
])->throw();
echo $response->json('trackId');
import os
import requests
with open("/path/to/your/track.mp3", "rb") as f:
response = requests.post(
"https://rest-api.cyanite.ai/v1/library-tracks",
headers={"x-api-key": os.environ["CYANITE_API_KEY"]},
data={"title": "your_track_name", "inputType": "MP3"},
files={"file": ("track.mp3", f, "audio/mpeg")},
)
response.raise_for_status()
print(response.json()["trackId"])
Step 3: Receive the results
Cyanite now analyzes the track. When the analysis is complete, it sends an
analysisJob/finished notification with the track's ID to your webhook URL.
Your handler fetches the results and logs them: an items list with one model
output per requested model. For example, the tag of BpmV2 is the track's
BPM, and the tag of KeyV2 is its key.
That's your first complete round trip: upload, notification, results. If the
analysis fails, you receive analysisJob/failed instead, see
Failed analyses.
Summary
Congratulations! You've made your first track data inference using the Cyanite API. You should now have a good understanding of the basics of how to use our API. We keep as much consistent from endpoint to endpoint as possible, so the understanding you gained here will help you as you explore other endpoints as well.
Next steps
- Tagging - Fetch the tags of a track as model outputs and use them in your application
- Search - Find tracks in your Library by a prompt or by similar tracks, and narrow the results with metadata filters
- AI Music Detection - Request and interpret the AI Music Detection result
- Segmentation - Fetch the sections of a track and use their boundaries for sync pitches, search and cueing
- Understanding Webhooks: make your handler production-ready.
- Understanding Limits: handle rate limits (
429) and quota limits (403). - API Reference - Get into the details of all our API endpoints
Feedback
We'd love to hear your feedback on this quick start guide. If you have any suggestions for improvements or if you found any issues, please let us know at support@cyanite.ai. Your feedback will help us improve the documentation and make it easier for others to get started with the Cyanite API.