Skip to main content

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.)
warning

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.

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);
Retries

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.

info

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
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();

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.