Test stream callbacks locally
Receive AudD stream callbacks on your laptop: post the recorded result and notification bodies to your receiver with curl, then put the receiver behind a Cloudflare quick tunnel or ngrok to get real callbacks, and set your callback URL back when you're done.
Callbacks are the requests with recognition results our servers will send to your server. To be able to receive callbacks from AudD, your server needs to be accessible from the web, and a receiver on your laptop isn’t. If you’re building a receiver on your laptop, you can send the callbacks to it yourself with curl, using the bodies we recorded. You can also use a tunnel to receive the real callbacks from your streams.
A receiver to test
We want our server to listen to POST requests, at /audd-callback/<secret>, because that’s where we’ll tell AudD our callback URL is. The commands below send the callbacks to http://127.0.0.1:8080/audd-callback/<secret>, like the receivers in Securing your stream callback endpoint. If you don’t have a receiver yet, use this one: it prints every callback it gets, and it uses only the standard library of Node.
// receiver.mjs: AUDD_CALLBACK_SECRET=... node receiver.mjs
import { createServer } from "node:http";
import { createHash, timingSafeEqual } from "node:crypto";
const PREFIX = "/audd-callback/";
const secret = process.env.AUDD_CALLBACK_SECRET ?? "";
if (secret.length < 32) throw new Error("Set AUDD_CALLBACK_SECRET to a long random string.");
const sha256 = (s) => createHash("sha256").update(s).digest();
createServer((req, res) => {
const path = (req.url ?? "").split("?")[0]; // the URL may also carry ?return=...
const given = path.startsWith(PREFIX) ? path.slice(PREFIX.length) : "";
if (req.method !== "POST" || !timingSafeEqual(sha256(given), sha256(secret))) {
res.writeHead(404).end();
return;
}
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
res.writeHead(200).end("OK"); // answer first, then look at the body
const raw = Buffer.concat(chunks);
console.log(`POST, Content-Type: ${req.headers["content-type"] ?? "none"}, ${raw.length} bytes`);
let body;
try {
body = JSON.parse(raw.toString("utf8")); // whatever the Content-Type header says
} catch {
console.log(` not JSON: ${raw.toString("utf8").slice(0, 100)}`);
return;
}
const n = body?.notification;
if (n) {
console.log(` stream ${n.radio_id}: notification ${n.notification_code}, ${n.notification_message}`);
return;
}
const r = body?.result;
for (const song of Array.isArray(r?.results) ? r.results : []) {
console.log(` stream ${r.radio_id} at ${r.timestamp}: ${song?.artist} - ${song?.title}`);
}
});
}).listen(8080, "127.0.0.1");
The receiver checks the secret before it reads the body. As soon as the body is read, it responds with 200 OK, and only then does it parse and print the callback. It’s for testing only. For production, see the receivers in Securing your stream callback endpoint: they also limit the size of the body and handle repeated results.
Replay recorded callbacks with curl
The fastest way to test a receiver is to send it the callbacks yourself. Create a secret and start the receiver in one terminal:
openssl rand -hex 32 > callback-secret.txt
AUDD_CALLBACK_SECRET=$(cat callback-secret.txt) node receiver.mjs
In another terminal, in the same folder, download the two recorded callback bodies from the public audd-openapi fixtures and post them with curl:
export AUDD_CALLBACK_SECRET=$(cat callback-secret.txt)
F=https://raw.githubusercontent.com/AudDMusic/audd-openapi/main/fixtures
curl -sO $F/streams_callback_with_result.json
curl -sO $F/streams_callback_with_notification.json
U=http://127.0.0.1:8080/audd-callback/$AUDD_CALLBACK_SECRET
# a result
curl -s -w " %{http_code}\n" --data-binary @streams_callback_with_result.json $U # OK 200
# the same result, with another Content-Type and ?return= in the URL
curl -s -w " %{http_code}\n" -H "Content-Type: application/json" \
--data-binary @streams_callback_with_result.json "$U?return=spotify" # OK 200
# a notification
curl -s -w " %{http_code}\n" --data-binary @streams_callback_with_notification.json $U # OK 200
# a body that isn't JSON
curl -s -w " %{http_code}\n" --data-binary "this is not JSON" $U # OK 200
# the wrong secret
curl -s -o /dev/null -w "%{http_code}\n" --data-binary @streams_callback_with_result.json \
http://127.0.0.1:8080/audd-callback/wrong-secret # 404
In the first terminal, the receiver prints:
POST, Content-Type: application/x-www-form-urlencoded, 435 bytes
stream 7 at 2020-04-13 10:31:43: Alan Walker, A$AP Rocky - Live Fast (PUBGM)
POST, Content-Type: application/json, 435 bytes
stream 7 at 2020-04-13 10:31:43: Alan Walker, A$AP Rocky - Live Fast (PUBGM)
POST, Content-Type: application/x-www-form-urlencoded, 228 bytes
stream 3: notification 650, Recognition failed: can't connect to the audiostream
POST, Content-Type: application/x-www-form-urlencoded, 16 bytes
not JSON: this is not JSON
A body that isn’t JSON still gets 200 OK: another status code won’t fix the body, it will only put the same callback back in our queue. The same result can also arrive twice, as Securing your stream callback endpoint explains. If your receiver saves results, post one result twice, and you should find it saved once.
Receive real callbacks through a tunnel
To receive the real callbacks, we need to expose our local development environment to the internet. Because we’re using a tunnel to expose our local environment, we don’t need to set up a real server somewhere online, and can test our code locally.
The test token doesn’t work with streams. Get your own token at dashboard.audd.io and send it as api_token in every request. You’ll also need at least one stream on the account. The music recognition costs $45 per audio stream per month with our music DB, and new accounts that get the free trial may also get a 3-day trial of one stream.
There is no per-stream callback URL: the callbacks from all the streams will be sent to the specified URL. While the tunnel address is set, your other servers won’t receive any callbacks, so if you have a production server, test at a time when it can miss a few results.
Start a tunnel
If you don’t want to create an account, use a Cloudflare quick tunnel. Install cloudflared, and run:
cloudflared tunnel --url http://localhost:8080
Copy the trycloudflare.com URL printed by cloudflared. Anyone with the URL can access your local service, and the URL stops working when you stop the cloudflared process. The hostname changes each time you create a quick tunnel, so after a restart, you’ll have to set the new URL as the callback URL.
You can also develop locally with a tool like ngrok, which needs an account. Connect the ngrok agent to your account with the auth token from the ngrok dashboard, then start the tunnel:
ngrok config add-authtoken <your-ngrok-authtoken>
ngrok http 8080
ngrok prints the forwarding URL. You can stop and restart the ngrok agent without losing your domain (unlike a quick tunnel), so you only have to set the callback URL once. If you enable the Traffic Inspector in the ngrok dashboard, you’ll see each request there, with its headers and body.
Don’t put a login in front of the tunnel, such as --allowed-mail in cloudflared or an OAuth policy in ngrok: the callbacks come from our servers, and they can’t sign in. The secret in the URL is the check.
Save your current callback URL
Use the getCallbackUrl method to get the current callback URL, and keep it to set it back later:
export AUDD_API_TOKEN=your-api-token # in the terminal where AUDD_CALLBACK_SECRET is set
curl https://api.audd.io/getCallbackUrl/ -F api_token="$AUDD_API_TOKEN"
{"status":"success","result":"https://yourapp.example/audd-callback/your-production-secret"}
If you haven’t set a callback URL yet, you’ll get error 19, “Getting the URL for callbacks failed: Internal error.” You can also get the URL with the AudD CLI: audd streams callback get.
Point the callback URL at the tunnel
Set the URL for callbacks using the setCallbackUrl API method. You can change the URL at any time using this method.
curl https://api.audd.io/setCallbackUrl/ \
-F api_token="$AUDD_API_TOKEN" \
-F url="https://your-tunnel-host/audd-callback/$AUDD_CALLBACK_SECRET"
Since we’re developing locally, we’ll set it to the tunnel’s URL, followed by /audd-callback/ and the secret. Use a different secret from the one in your production URL: every request through the tunnel, path included, passes through the tunnel provider. If you want the callbacks to contain Apple Music, Spotify, Deezer or MusicBrainz metadata, add ?return= to the URL, like ?return=spotify; our server reads ?return= from the callback URL.
By default, we will send new results after songs end playing, so the first result can take as long as the song that is playing now. A notification arrives when something happens to one of your streams. If you add a stream only for this test, you can add it with callbacks=before to get the results when songs start playing; just note that those results don’t contain play_length.
Put the old callback URL back
When you’re done, set the URL you saved back with the setCallbackUrl method, and do it before you stop the tunnel:
curl https://api.audd.io/setCallbackUrl/ \
-F api_token="$AUDD_API_TOKEN" \
-F url="https://yourapp.example/audd-callback/your-production-secret"
This way, no callbacks are sent to an address that no longer exists. If the account had no callback URL before the test, set https://audd.tech/empty/, which responds with 200 OK to any POST. Use the deleteStream method to remove a stream you added only for the test: every stream takes up one of the streams in the limit you pay for.
Without a tunnel
In addition to callbacks, you can use HTTP longpolling to get the new results without having to spin up a web server or have a static IP: see Webhook callbacks vs longpoll. The AudD CLI can also post each result it receives this way to your receiver, shaped like a callback, with audd streams watch --forward-to http://127.0.0.1:8080/audd-callback/<secret>.
Related
Reading this as an AI agent? The raw Markdown is at recipes/test-callbacks-locally.md, and the full index is /resources/llms.txt.
