---
title: "Turn a radio station into a Spotify playlist"
description: "A small Python service that adds the songs a radio station plays to a Spotify playlist: AudD stream callbacks carry the Spotify track, a Spotify search by ISRC or by artist and title covers results without one, and repeats are skipped."
slug: "/resources/recipes/radio-to-spotify-playlist"
section: "recipes"
keywords: [audd, spotify playlist, radio, streams, callbacks, spotify web api, python, flask]
---

# Turn a radio station into a Spotify playlist

If you're a developer or a station hobbyist and want a Spotify playlist that follows a radio station, this recipe is for you. We wanted to make it as simple as possible: you send us the URL of the station's stream, we send you the songs in real time, and a small Python program adds them to your playlist.

## What you'll build

You send us the URL of the station's stream once. Callbacks are the requests with recognition results our servers will send to your server: by default, we will send new results after songs end playing. With `?return=spotify` in the callback URL, the results include the Spotify tracks of the songs. The program receives them and adds the tracks to your playlist, and it skips the songs it has added in the last 7 days.

## Prerequisites

- You can get a token from our [API Dashboard](https://dashboard.audd.io). Set the limit of audio streams and pay on the API Dashboard. Stream monitoring is $45 per stream per month. New accounts that get the free trial may also get a 3-day trial of one stream. The `test` token doesn't work for streams; use your own token.
- Spotify Premium: the app owner must have a Spotify Premium account for apps in development mode to function.
- To be able to receive callbacks from AudD, your server needs to be accessible from the web over HTTPS. The program listens on `127.0.0.1:8080`, behind a reverse proxy like nginx or Caddy. In the examples, the address is `https://your-server.example`.
- The code requires Python 3.10 or later, the official SDK, Flask, Requests and Waitress: `pip install audd flask requests waitress`

## Step 1: Create the Spotify app

The program adds the songs using a Spotify app. Create one on the [Spotify Developer Dashboard](https://developer.spotify.com/dashboard) (click Create an app), with `https://your-server.example/spotify/callback` as the redirect URI. You'll find the Client ID and the Client Secret in the app's Settings.

Spotify sends you back to the redirect URI after you log in, so it must be the same in the app and in `SPOTIFY_REDIRECT_URI` (Step 3). If you want to test the program on your computer, add `http://127.0.0.1:8080/spotify/callback` too: Spotify doesn't allow `localhost`.

You can use any playlist of yours, or create a new one. The ID of the playlist is the end of its address: `3cEYpjA9oz9GiPac4AsH4n` in `open.spotify.com/playlist/3cEYpjA9oz9GiPac4AsH4n`.

New Spotify apps are in development mode, so only you and the users you add on the Users Management tab can use the app. Please add the account if the playlist belongs to another account; otherwise, you'll get a `403` error.

## Step 2: The program

Save this as `playlist.py`. In `PLAYLISTS`, put the `radio_id` you'll give the station in Step 4 (here, `1`) and your playlist ID.

```python
"""Add the songs AudD recognizes on a radio stream to a Spotify playlist."""
import json
import logging
import os
import queue
import secrets
import threading
import time
from pathlib import Path
from urllib.parse import quote, urlencode

import requests
from flask import Flask, abort, redirect, request
from waitress import serve

from audd import AudD, AudDSerializationError

# The radio_id of each stream -> the ID of the playlist its songs go to
PLAYLISTS = {1: "your-playlist-id"}
REPEAT_WINDOW = 7 * 24 * 3600  # skip a track added to the same playlist in the last 7 days

ACCOUNTS = "https://accounts.spotify.com"
API = "https://api.spotify.com/v1"
CLIENT_ID = os.environ["SPOTIFY_CLIENT_ID"]
CLIENT_SECRET = os.environ["SPOTIFY_CLIENT_SECRET"]
REDIRECT_URI = os.environ["SPOTIFY_REDIRECT_URI"]  # https://your-server.example/spotify/callback
CALLBACK_SECRET = os.environ["CALLBACK_SECRET"]  # a long random string, also in the callback URL
SCOPES = "playlist-modify-public playlist-modify-private"

STATE_FILE = Path("playlist-state.json")  # the Spotify refresh token and the tracks added
state = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {}
state.setdefault("refresh_token", None)
state.setdefault("added", {})
lock = threading.Lock()
token = {"access": None, "expires": 0.0}
login_states = set()
jobs = queue.Queue()

audd = AudD()  # reads AUDD_API_TOKEN
app = Flask(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
log = logging.getLogger("playlist")


def update_state(**changes):
    with lock:
        state.update(changes)
        cutoff = time.time() - REPEAT_WINDOW
        state["added"] = {k: t for k, t in state["added"].items() if t > cutoff}
        STATE_FILE.write_text(json.dumps(state))


@app.post("/audd-callback/<secret>")
def audd_callback(secret):
    if not secrets.compare_digest(secret.encode(), CALLBACK_SECRET.encode()):
        abort(404)
    try:
        match, notification = audd.streams.handle_callback(request)
    except AudDSerializationError as exc:
        log.warning("unreadable callback: %s", exc)
        return "", 200
    if match and match.song and match.radio_id in PLAYLISTS:
        jobs.put((PLAYLISTS[match.radio_id], match.song))  # results[0]
    elif notification:
        log.info("stream %s: %s %s", notification.radio_id,
                 notification.notification_code, notification.notification_message)
    return "", 200  # answer at once; the worker thread talks to Spotify


def remember_tokens(t):
    token["access"], token["expires"] = t["access_token"], time.time() + t["expires_in"]
    if t.get("refresh_token"):  # Spotify may send a new refresh token; keep it
        update_state(refresh_token=t["refresh_token"])


def access_token():
    if time.time() < token["expires"] - 60:
        return token["access"]
    if not state["refresh_token"]:
        raise RuntimeError("Spotify isn't connected: open /spotify/login")
    r = requests.post(f"{ACCOUNTS}/api/token", auth=(CLIENT_ID, CLIENT_SECRET), timeout=10,
                      data={"grant_type": "refresh_token", "refresh_token": state["refresh_token"]})
    if r.status_code == 400 and r.json().get("error") == "invalid_grant":
        update_state(refresh_token=None)  # expired or revoked: log in again
        raise RuntimeError("the Spotify login has expired: open /spotify/login")
    r.raise_for_status()
    remember_tokens(r.json())
    return token["access"]


def spotify(method, path, **kwargs):
    for _ in range(3):
        r = requests.request(method, API + path, timeout=10, **kwargs,
                             headers={"Authorization": f"Bearer {access_token()}"})
        if r.status_code != 429:
            r.raise_for_status()
            return r.json()
        time.sleep(int(r.headers.get("Retry-After", 5)))  # rate limited: wait, then retry
    r.raise_for_status()


def find_track(song):
    if song.spotify and song.spotify.uri:  # the Spotify block, from ?return=spotify
        return song.spotify.uri
    if song.isrc:
        q = f"isrc:{song.isrc}"
    elif song.artist and song.title:
        q = f"track:{song.title} artist:{song.artist}"
    else:
        return None
    found = spotify("GET", "/search", params={"q": q, "type": "track", "limit": 1})
    items = (found.get("tracks") or {}).get("items") or []
    return items[0].get("uri") if items else None


def add_song(playlist, song):
    uri = find_track(song)
    if not uri:
        log.info("not found on Spotify: %s - %s", song.artist, song.title)
        return
    key = f"{playlist}:{uri}"
    if time.time() - state["added"].get(key, 0) < REPEAT_WINDOW:
        log.info("added recently, skipped: %s - %s", song.artist, song.title)
        return
    spotify("POST", f"/playlists/{playlist}/items", json={"uris": [uri]})
    update_state(added={**state["added"], key: time.time()})
    log.info("added: %s - %s (%s)", song.artist, song.title, uri)


def worker():
    while True:
        playlist, song = jobs.get()
        try:
            add_song(playlist, song)
        except Exception as exc:  # log it and go on to the next song
            log.warning("failed: %s - %s: %s", song.artist, song.title, exc)


@app.get("/spotify/login")
def spotify_login():
    if state["refresh_token"]:
        abort(404)  # already connected
    login_state = secrets.token_urlsafe(16)
    login_states.add(login_state)
    return redirect(f"{ACCOUNTS}/authorize?" + urlencode({
        "client_id": CLIENT_ID, "response_type": "code", "redirect_uri": REDIRECT_URI,
        "scope": SCOPES, "state": login_state}, quote_via=quote))


@app.get("/spotify/callback")
def spotify_callback():
    if state["refresh_token"] or request.args.get("state") not in login_states:
        abort(400)
    login_states.discard(request.args["state"])
    if "code" not in request.args:
        return "The Spotify login was cancelled or failed.", 400
    r = requests.post(f"{ACCOUNTS}/api/token", auth=(CLIENT_ID, CLIENT_SECRET), timeout=10,
                      data={"grant_type": "authorization_code", "code": request.args["code"],
                            "redirect_uri": REDIRECT_URI})
    r.raise_for_status()
    remember_tokens(r.json())
    return "Spotify is connected. You can close this tab."


if __name__ == "__main__":
    if not state["refresh_token"]:
        log.info("Spotify isn't connected yet: open /spotify/login on this server")
    threading.Thread(target=worker, daemon=True).start()
    serve(app, host="127.0.0.1", port=8080)
```

Always respond `200 OK` to a callback. If your server doesn't respond to the callbacks with the 200 OK status or we can't connect to your server, we'll put the callbacks in a queue. That's why the route only puts the song on a queue and answers at once, and a worker thread talks to Spotify.

The results contain the recognized songs. The program takes the first one, `match.song`, and reads the Spotify URI of the track from its `spotify` block. Then it adds the URI to your playlist with Spotify's Add Items to Playlist endpoint, `POST /v1/playlists/{playlist_id}/items`. If the position is omitted, the items will be appended to the playlist.

The program connects to Spotify with the authorization code flow. After you accept, Spotify sends you back to `/spotify/callback` with a code, and the program exchanges the code for an access token and a refresh token. Spotify's access tokens expire in 1 hour, and the refresh tokens expire in 6 months. The program gets a new access token with the refresh token when it needs one. Once an account is connected, the two login routes return an error, so nobody else can connect theirs.

## Step 3: Run it and connect Spotify

On the server, set the variables and start the program. `CALLBACK_SECRET` is any long random string, for example from `python -c "import secrets; print(secrets.token_urlsafe(32))"`.

```bash
export AUDD_API_TOKEN=your-api-token
export SPOTIFY_CLIENT_ID=your-client-id
export SPOTIFY_CLIENT_SECRET=your-client-secret
export SPOTIFY_REDIRECT_URI=https://your-server.example/spotify/callback
export CALLBACK_SECRET=your-long-random-secret
python playlist.py
```

Open `https://your-server.example/spotify/login` in your browser, log in to Spotify and accept. When you see "Spotify is connected. You can close this tab.", the program has saved the refresh token in `playlist-state.json`. Please keep this file private, like your tokens.

Callbacks are the requests with recognition results our servers will send to your server, so for a quick test, you can send one yourself. Run this on the server:

```bash
curl -X POST http://127.0.0.1:8080/audd-callback/your-long-random-secret \
  -H "Content-Type: application/json" \
  -d '{"status":"success","result":{"radio_id":1,"timestamp":"2020-04-13 10:31:43","play_length":111,"results":[{"artist":"Tears For Fears","title":"Everybody Wants To Rule The World","song_link":"https://lis.tn/NbkVb","spotify":{"uri":"spotify:track:5B9qVIyjqeWkeOAp2tJgqL"}}]}}'
```

The program logs `added: Tears For Fears - Everybody Wants To Rule The World`, and the song appears at the end of your playlist. If you send it again, you'll see `added recently, skipped` in the log. For other ways to send test callbacks, see [Test AudD callbacks locally](/resources/recipes/test-callbacks-locally).

## Step 4: Add the station

Set the URL for callbacks, and then add the stream. There is no per-stream callback URL: the callbacks from all your streams will be sent to the specified URL. AudD reads the `return` parameter from the callback URL, so a callback URL that ends in `?return=spotify` makes the stream results include the Spotify block. The `return_metadata` option of `set_callback_url` adds the parameter for you.

```python
from audd import AudD

audd = AudD()  # reads AUDD_API_TOKEN
audd.streams.set_callback_url(
    "https://your-server.example/audd-callback/your-long-random-secret",
    return_metadata=["spotify"],  # the URL gets ?return=spotify
)
audd.streams.add(url="https://npr-ice.streamguys1.com/live.mp3", radio_id=1)
```

As the URL of the audio stream, you can simply send the URL of the station's stream. We support most of the stream formats, including DASH, Icecast, HLS, m3u/m3u8. As the `radio_id`, send any integer that will identify this stream for you: the program looks it up in `PLAYLISTS`. By default, we will send new results after songs end playing, so a song goes into the playlist once it has played.

You'll receive the first result seconds or minutes after you add the stream, and then one result for every new song. To add another station, add its stream with a new `radio_id`, and put that `radio_id` in `PLAYLISTS` with its playlist.

## When a result has no Spotify block

We add the Spotify block to the results only when Spotify has the recording. Otherwise, the program searches Spotify for the song by its ISRC, or by its artist and title if the result has no ISRC. Enterprise features such as ISRC and UPC codes and the match score are available on a Startup plan or higher, on request: email api@audd.io.

If Spotify finds several tracks, the program adds the first one. If it finds none, you'll see `not found on Spotify` in the log, and the song is skipped.

## When the station plays the same song again

Radio stations play the same songs many times a day. The program remembers when it added each song, and skips the song if it was added less than `REPEAT_WINDOW` seconds ago (7 days). If you want each song in the playlist only once, set `REPEAT_WINDOW` to a very large number. When your server is back online after downtime, we'll gradually send all the backlog, and the program adds the songs it missed.

## When Spotify returns an error

These are the errors you might see from Spotify. In each case, the program logs the error with the song (`failed: …`) and goes on to the next one. A `403` error can mean that the account you connected isn't on the app's allowlist (see Step 1).

If your app makes a lot of Web API requests in a short period of time, it may receive a `429` error response from Spotify. The header of the 429 response will normally include a `Retry-After` header with a value in seconds, and the program waits that long before it tries again (up to 3 times).

If you see `the Spotify login has expired`, Spotify has answered `invalid_grant`: the refresh token has expired or was revoked, and the program has discarded it. Open `/spotify/login` again and log in.

## When the stream has a problem

If something happens to an audio stream, we'll let you know by sending a notification so you can fix the stream or change its URL. The program logs it, like `stream 1: 650 Recognition failed: can't connect to the audiostream`. There are 3 codes: `0` (which means that everything's fine), `650` (which means that we can't connect to the stream) and `651` (which means that we don't receive any music from the stream, only white noise). See [Stream health](/resources/concepts/stream-health) for what to do about each code.

## Who can send callbacks

Callbacks aren't signed, so the program checks the secret in the callback URL. Please keep the callback URL private, like your API token: anyone who knows it can add songs to your playlist. See [Securing your callback endpoint](/resources/concepts/securing-your-callback-endpoint) for more.

---

**Related**

- [Spotify metadata block](/resources/reference/spotify)
- [Stream callback and longpoll payload reference](/resources/reference/streams-callback-shape)
- [Webhook callbacks vs longpoll for stream results](/resources/concepts/callback-vs-longpoll)
- [Test AudD callbacks locally](/resources/recipes/test-callbacks-locally)
- [Monitor radio airplay for your music catalog](/resources/recipes/radio-airplay-monitor)
- [Streams API reference](https://docs.audd.io/streams)

## Sitemap

See the [resources sitemap](https://audd.io/resources/sitemap.md) for every guide and the [glossary](https://audd.io/resources/reference/glossary.md) for AudD terms.
