Skip to content

api

Module for handling API requests.

check_update() ¤

Check for update.

Returns¤
  • returns True if there is an update.
Source code in spotdl/web/api.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@router.get("/api/check_update")
def check_update() -> bool:
    """
    Check for update.

    ### Returns
    - returns True if there is an update.
    """

    try:
        _, ahead, _ = get_status(__version__, "master")
        if ahead > 0:
            return True
    except RuntimeError:
        latest_version = get_latest_version()
        latest_tuple = tuple(latest_version.replace("v", "").split("."))
        current_tuple = tuple(__version__.split("."))
        if latest_tuple > current_tuple:
            return True
    except RateLimitError:
        return False

    return False

connect_endpoint(client_id) async ¤

Websocket endpoint.

Arguments¤
  • websocket: The WebSocket instance.
Source code in spotdl/web/api.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@router.get("/api/connect")
async def connect_endpoint(client_id: str):
    """
    Websocket endpoint.

    ### Arguments
    - websocket: The WebSocket instance.
    """

    if not CLIENT_ID_REGEX.match(client_id):
        raise HTTPException(status_code=400, detail="Invalid client_id.")

    await Client(client_id).connect()

download_file(file, client=Depends(get_client), state=Depends(get_current_state)) async ¤

Download file using path.

Arguments¤
  • file: The file path.
  • client: The client's state.
Returns¤
  • returns the file response, filename specified to return as attachment.
Source code in spotdl/web/api.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@router.get("/api/download/file")
async def download_file(
    file: str,
    client: Client = Depends(get_client),
    state: ApplicationState = Depends(get_current_state),
):
    """
    Download file using path.

    ### Arguments
    - file: The file path.
    - client: The client's state.

    ### Returns
    - returns the file response, filename specified to return as attachment.
    """

    if state.web_settings.get("web_use_output_dir", False):
        # Use the static part of the server's output template, if it ends
        # partway through a file name, use the directory that file would be in
        output_prefix = state.downloader_settings["output"].split("{", 1)[0]
        expected_dir = Path(output_prefix)
        if not output_prefix.endswith(("/", os.sep)):
            expected_dir = expected_dir.parent
    else:
        expected_dir = get_spotdl_path() / f"web/sessions/{client.client_id}"

    # Resolve both paths so ".." segments and symlinks can't escape the directory
    file_path = Path(file).resolve()
    if (file_path.suffix[1:] not in FFMPEG_FORMATS) or (
        not file_path.is_relative_to(expected_dir.resolve())
    ):
        raise HTTPException(status_code=400, detail="Invalid download path.")

    return FileResponse(
        file_path,
        filename=file_path.name,
    )

download_url(url, client=Depends(get_client), state=Depends(get_current_state)) async ¤

Download songs using Song url.

Arguments¤
  • url: The url to download.
Returns¤
  • returns the file path if the song was downloaded.
Source code in spotdl/web/api.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@router.post("/api/download/url")
async def download_url(
    url: str,
    client: Client = Depends(get_client),
    state: ApplicationState = Depends(get_current_state),
) -> Optional[str]:
    """
    Download songs using Song url.

    ### Arguments
    - url: The url to download.

    ### Returns
    - returns the file path if the song was downloaded.
    """

    # Use the server's output setting, clients can't choose where files go
    if state.web_settings.get("web_use_output_dir", False):
        client.downloader.settings["output"] = state.downloader_settings["output"]
    else:
        client.downloader.settings["output"] = str(
            (get_spotdl_path() / f"web/sessions/{client.client_id}").absolute()
        )

    try:
        # Fetch song metadata
        song = Song.from_url(url)

        # Download Song
        _, path = await client.downloader.pool_download(song)

        if path is None:
            state.logger.error(f"Failure downloading {song.name}")

            raise HTTPException(
                status_code=500, detail=f"Error downloading: {song.name}"
            )

        return str(path.absolute())

    except Exception as exception:
        state.logger.error(f"Error downloading! {exception}")

        raise HTTPException(
            status_code=500, detail=f"Error downloading: {exception}"
        ) from exception

get_options() ¤

Get options model (possible settings).

Returns¤
  • returns the options.
Source code in spotdl/web/api.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@router.get("/api/options_model")
def get_options() -> Dict[str, Any]:
    """
    Get options model (possible settings).

    ### Returns
    - returns the options.
    """

    parser = create_parser()

    options = {}
    for action in parser._actions:  # pylint: disable=protected-access
        if action.dest not in WEB_EDITABLE_SETTINGS:
            continue

        default = app_state.downloader_settings.get(action.dest, None)
        choices = list(action.choices) if action.choices else None

        type_name = ""
        if action.type is not None:
            if hasattr(action.type, "__objclass__"):
                type_name: str = action.type.__objclass__.__name__  # type: ignore
            else:
                type_name: str = action.type.__name__  # type: ignore

        if isinstance(
            action,
            argparse._StoreConstAction,  # pylint: disable=protected-access
        ):
            type_name = "bool"

        if choices is not None and action.nargs == "*":
            type_name = "list"

        options[action.dest] = {
            "type": type_name,
            "choices": choices,
            "default": default,
            "help": action.help,
        }

    return options

get_settings(client=Depends(get_client)) ¤

Get client settings.

Arguments¤
  • client: The client's state.
Returns¤
  • returns the settings.
Source code in spotdl/web/api.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
@router.get("/api/settings")
def get_settings(
    client: Client = Depends(get_client),
) -> DownloaderOptions:
    """
    Get client settings.

    ### Arguments
    - client: The client's state.

    ### Returns
    - returns the settings.
    """

    return client.downloader_settings

Parse search term and return list of Song objects.

Arguments¤
  • query: The query to parse.
Returns¤
  • returns a list of Song objects.
Source code in spotdl/web/api.py
158
159
160
161
162
163
164
165
166
167
168
169
170
@router.get("/api/songs/search", response_model=None)
def query_search(query: str) -> List[Song]:
    """
    Parse search term and return list of Song objects.

    ### Arguments
    - query: The query to parse.

    ### Returns
    - returns a list of Song objects.
    """

    return get_search_results(query)

shutdown_event() async ¤

Called when the server is shutting down.

Source code in spotdl/web/api.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@router.on_event("shutdown")
async def shutdown_event():
    """
    Called when the server is shutting down.
    """

    if (
        not app_state.web_settings["keep_sessions"]
        and not app_state.web_settings["web_use_output_dir"]
    ):
        app_state.logger.info("Removing sessions directories")
        sessions_dir = Path(get_spotdl_path(), "web/sessions")
        if sessions_dir.exists():
            shutil.rmtree(sessions_dir)

songs_from_url(url) ¤

Search for a song, playlist, artist or album on spotify using url.

Arguments¤
  • url: The url to search.
Returns¤
  • returns a list with Song objects to be downloaded.
Source code in spotdl/web/api.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@router.get("/api/url", response_model=None)
def songs_from_url(url: str) -> List[Song]:
    """
    Search for a song, playlist, artist or album on spotify using url.

    ### Arguments
    - url: The url to search.

    ### Returns
    - returns a list with Song objects to be downloaded.
    """

    if "playlist" in url:
        playlist = Playlist.from_url(url)
        return list(map(Song.from_url, playlist.urls))
    if "album" in url:
        album = Album.from_url(url)
        return list(map(Song.from_url, album.urls))
    if "artist" in url:
        artist = Artist.from_url(url)
        return list(map(Song.from_url, artist.urls))

    return [Song.from_url(url)]

update_settings(settings, client=Depends(get_client)) ¤

Update client settings, and re-initialize downloader.

Arguments¤
  • settings: The settings to change.
  • client: The client's state.
Returns¤
  • returns the new settings.
Source code in spotdl/web/api.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
@router.post("/api/settings/update")
def update_settings(
    settings: DownloaderOptionalOptions,
    client: Client = Depends(get_client),
) -> DownloaderOptions:
    """
    Update client settings, and re-initialize downloader.

    ### Arguments
    - settings: The settings to change.
    - client: The client's state.

    ### Returns
    - returns the new settings.
    """

    try:
        return client.update_settings(settings)
    except ValueError as exception:
        raise HTTPException(status_code=400, detail=str(exception)) from exception

version() ¤

Get the current version This method is created to ensure backward compatibility of the web app, as the web app is updated with the latest regardless of the backend version

Returns¤
  • returns the version of the app
Source code in spotdl/web/api.py
128
129
130
131
132
133
134
135
136
137
138
139
@router.get("/api/version", response_model=None)
def version() -> str:
    """
    Get the current version
    This method is created to ensure backward compatibility of the web app,
    as the web app is updated with the latest regardless of the backend version

    ### Returns
    -  returns the version of the app
    """

    return __version__