From 89f8589424c6163ac792e572b7d4d64fd3cb4146 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 14:13:47 +0100 Subject: [PATCH] OpenAPI: document the Last.fm API and commit the exported spec - /2.0/ and /api/auth/ are described from the Last.fm method registry: method enum, per-method parameter tables, auth requirements, notes, request schemas and XML example responses - Readable tags (Auth, Apps, Sessions, Tokens, Stats, Last.fm) - docs/openapi.json is exported with `flask openapi write`; tests fail if it drifts from the code, if any route is undocumented, or if a UI route is missing its bearer-auth security declaration Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 2503 +++++++++++++++++++++++++++++ src/scrobbler/api/__init__.py | 4 + src/scrobbler/api/apps.py | 2 +- src/scrobbler/api/auth.py | 2 +- src/scrobbler/api/sessions.py | 2 +- src/scrobbler/api/stats.py | 2 +- src/scrobbler/api/tokens.py | 2 +- src/scrobbler/openapi/__init__.py | 0 src/scrobbler/openapi/lastfm.py | 241 +++ tests/test_openapi.py | 75 + tests/test_ui_auth.py | 9 - 11 files changed, 2828 insertions(+), 14 deletions(-) create mode 100644 docs/openapi.json create mode 100644 src/scrobbler/openapi/__init__.py create mode 100644 src/scrobbler/openapi/lastfm.py create mode 100644 tests/test_openapi.py diff --git a/docs/openapi.json b/docs/openapi.json new file mode 100644 index 0000000..b759e2e --- /dev/null +++ b/docs/openapi.json @@ -0,0 +1,2503 @@ +{ + "info": { + "description": "Two APIs: `/2.0/` is Last.fm (Audioscrobbler 2.0) compatible, for players and scrobblers; `/api/v1/` is the JSON API used by the web UI.", + "title": "Scrobbler API", + "version": "v1" + }, + "paths": { + "/api/v1/auth/register": { + "post": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "400": { + "description": "Invalid username or password", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Username taken", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Token" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Register" + } + } + } + }, + "summary": "Create an account", + "description": "Registers a user and logs them in, returning a bearer token.", + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/login": { + "post": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "401": { + "description": "Wrong username or password", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Token" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Login" + } + } + } + }, + "summary": "Log in", + "description": "Exchanges a username and password for a bearer token valid for 30 days.", + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/logout": { + "post": { + "responses": { + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Log out", + "description": "Revokes the bearer token used for this request.", + "tags": [ + "Auth" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/auth/me": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Current user", + "tags": [ + "Auth" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/apps": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ApiApp" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "List your API applications", + "tags": [ + "Apps" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiApp" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiAppCreate" + } + } + } + }, + "summary": "Create an API application", + "tags": [ + "Apps" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/apps/{api_key}": { + "delete": { + "responses": { + "404": { + "description": "No such application", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Delete an API application", + "description": "Also revokes every session issued to it.", + "tags": [ + "Apps" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "api_key", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/api/v1/sessions": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Session" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "List client sessions", + "tags": [ + "Sessions" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/sessions/{session_id}": { + "delete": { + "responses": { + "404": { + "description": "No such session", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Revoke a client session", + "description": "The client's session key stops working immediately (Last.fm error 9).", + "tags": [ + "Sessions" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "session_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, + "/api/v1/tokens/{token}": { + "get": { + "responses": { + "404": { + "description": "Unknown or expired token", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthTokenInfo" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Describe a token awaiting approval", + "description": "Returns the name of the application asking for access.", + "tags": [ + "Tokens" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "token", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/api/v1/tokens/approve": { + "post": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "404": { + "description": "Unknown or expired token", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApproveToken" + } + } + } + }, + "summary": "Approve a token", + "description": "Grants the requesting application a session for your account once it calls\nauth.getSession.", + "tags": [ + "Tokens" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/now-playing": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NowPlaying" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "What you're listening to now", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/recent": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecentPage" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Recent scrobbles, newest first", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/top/artists": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + }, + { + "in": "query", + "name": "period", + "schema": { + "type": "string", + "default": "7day", + "enum": [ + "overall", + "7day", + "1month", + "3month", + "6month", + "12month" + ] + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TopPage" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Top artists over a period", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/top/albums": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + }, + { + "in": "query", + "name": "period", + "schema": { + "type": "string", + "default": "7day", + "enum": [ + "overall", + "7day", + "1month", + "3month", + "6month", + "12month" + ] + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TopPage" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Top albums over a period", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/top/tracks": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + }, + { + "in": "query", + "name": "period", + "schema": { + "type": "string", + "default": "7day", + "enum": [ + "overall", + "7day", + "1month", + "3month", + "6month", + "12month" + ] + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TopPage" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Top tracks over a period", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/counts": { + "get": { + "parameters": [ + { + "in": "query", + "name": "period", + "schema": { + "type": "string", + "default": "1month", + "enum": [ + "overall", + "7day", + "1month", + "3month", + "6month", + "12month" + ] + }, + "required": false + }, + { + "in": "query", + "name": "bucket", + "schema": { + "type": "string", + "default": "day", + "enum": [ + "day", + "week", + "month" + ] + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Count" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Scrobbles per day, week or month", + "description": "Day buckets include days with no scrobbles, so the series is continuous.", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/me/summary": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Summary" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Totals: scrobbles, distinct artists and tracks", + "tags": [ + "Stats" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/2.0/": { + "get": { + "tags": [ + "Last.fm" + ], + "summary": "Call a Last.fm API method (query string)", + "description": "Last.fm (Audioscrobbler 2.0) compatible API. Point a scrobbler's \"custom Last.fm\nserver\" setting at this server's `/2.0/`.\n\n**Signing.** Signed methods need `api_sig`: take every parameter except `format`,\n`callback` and `api_sig`, sort by name, concatenate each name followed by its\nvalue, append your application's shared secret, and take the md5 hex digest.\n\n**Sessions.** Methods that act as a user need `sk`, a session key from\n`auth.getMobileSession` or the desktop flow (`auth.getToken`, approval at\n`/api/auth/`, then `auth.getSession`).\n\n**Errors** use Last.fm's codes: 2 (Invalid service), 3 (Invalid Method), 4 (Authentication Failed), 6 (Invalid parameters), 8 (Operation failed), 9 (Invalid session key), 10 (Invalid API key), 13 (Invalid method signature supplied), 14 (Unauthorized Token), 15 (This token has expired), 29 (Rate limit exceeded).\n\n## Methods\n### `auth.getMobileSession`\n\nCreate a session key from a username and password.\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `username` | yes | Username |\n| `password` | yes | Password (send over HTTPS, as a POST body) |\n\nThe legacy `authToken` (md5 of username + md5(password)) form is not supported, because it requires storing unsalted password hashes. Clients that only support it (such as pylast's `password_hash`) should use the desktop flow instead.\n\n### `auth.getSession`\n\nExchange an approved token for a session key (desktop auth flow, step 3).\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `token` | yes | Token from auth.getToken, approved by the user |\n\n### `auth.getToken`\n\nFetch an unapproved request token (desktop auth flow, step 1).\n\n*Requires:* signed.\n\nSend the user to `/api/auth/?api_key=\u2026&token=\u2026` to approve the token, then call auth.getSession. Tokens expire after 60 minutes.\n\n### `track.scrobble`\n\nScrobble up to 50 tracks.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist[i]` | yes | Artist name |\n| `track[i]` | yes | Track title |\n| `timestamp[i]` | yes | Unix time the track started playing |\n| `album[i]` | no | Album title |\n| `albumArtist[i]` | no | Album artist, if different from the track artist |\n| `duration[i]` | no | Track length in seconds |\n| `trackNumber[i]` | no | Position on the album |\n| `mbid[i]` | no | MusicBrainz track id |\n\nTracks are array parameters indexed from 0 (`artist[0]`, `track[0]`, ...); a single un-indexed track is also accepted. Tracks are ignored (not an error) when the artist or track is empty (codes 1/2), the timestamp is over 14 days old (3) or more than 5 minutes in the future (4). Re-sending an already stored scrobble is accepted, so retries are safe.\n\n### `track.updateNowPlaying`\n\nSet the track the user is listening to now.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist` | yes | Artist name |\n| `track` | yes | Track title |\n| `album` | no | Album title |\n| `albumArtist` | no | Album artist |\n| `duration` | no | Track length in seconds; now-playing expires after it |\n| `trackNumber` | no | Position on the album |\n| `mbid` | no | MusicBrainz track id |\n\nNow playing expires after the track's duration (10 minutes if not given).\n\n### `user.getInfo`\n\nA user's profile and play count.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n\n### `user.getRecentTracks`\n\nRecently scrobbled tracks, newest first, led by the now-playing track.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `limit` | no | Results per page (default 50, max 200) |\n| `page` | no | Page number (default 1) |\n| `from` | no | Only scrobbles at or after this Unix time |\n| `to` | no | Only scrobbles at or before this Unix time |\n\n### `user.getTopAlbums`\n\nMost played albums over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopArtists`\n\nMost played artists over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopTracks`\n\nMost played tracks over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |", + "operationId": "lastfmGet", + "parameters": [ + { + "name": "method", + "in": "query", + "required": true, + "description": "The API method to call, e.g. `track.scrobble`", + "schema": { + "type": "string", + "enum": [ + "auth.getMobileSession", + "auth.getSession", + "auth.getToken", + "track.scrobble", + "track.updateNowPlaying", + "user.getInfo", + "user.getRecentTracks", + "user.getTopAlbums", + "user.getTopArtists", + "user.getTopTracks" + ] + } + }, + { + "name": "api_key", + "in": "query", + "required": true, + "description": "API key of one of your applications", + "schema": { + "type": "string" + } + }, + { + "name": "api_sig", + "in": "query", + "required": false, + "description": "Request signature; required by signed methods (see below)", + "schema": { + "type": "string" + } + }, + { + "name": "sk", + "in": "query", + "required": false, + "description": "Session key; required by methods that act as a user", + "schema": { + "type": "string" + } + }, + { + "name": "format", + "in": "query", + "required": false, + "description": "`xml` (default) or `json`", + "schema": { + "type": "string", + "enum": [ + "xml", + "json" + ] + } + }, + { + "name": "username", + "in": "query", + "required": false, + "description": "Username (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "password", + "in": "query", + "required": false, + "description": "Password (send over HTTPS, as a POST body) (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "token", + "in": "query", + "required": false, + "description": "Token from auth.getToken, approved by the user (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "artist", + "in": "query", + "required": false, + "description": "Artist name (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "track", + "in": "query", + "required": false, + "description": "Track title (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "album", + "in": "query", + "required": false, + "description": "Album title (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "albumArtist", + "in": "query", + "required": false, + "description": "Album artist (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "duration", + "in": "query", + "required": false, + "description": "Track length in seconds; now-playing expires after it (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "trackNumber", + "in": "query", + "required": false, + "description": "Position on the album (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "mbid", + "in": "query", + "required": false, + "description": "MusicBrainz track id (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "user", + "in": "query", + "required": false, + "description": "Username to fetch data for (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Results per page (default 50, max 200) (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "Page number (default 1) (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "from", + "in": "query", + "required": false, + "description": "Only scrobbles at or after this Unix time (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "to", + "in": "query", + "required": false, + "description": "Only scrobbles at or before this Unix time (only for methods that take it)", + "schema": { + "type": "string" + } + }, + { + "name": "period", + "in": "query", + "required": false, + "description": "overall | 7day | 1month | 3month | 6month | 12month (default overall) (only for methods that take it)", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "`` wrapping the method's result, or JSON", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "examples": { + "auth.getMobileSession": { + "summary": "auth.getMobileSession", + "value": "aliced580d57f32848f5dcf574d1ce18d78b20" + }, + "auth.getSession": { + "summary": "auth.getSession", + "value": "aliced580d57f32848f5dcf574d1ce18d78b20" + }, + "auth.getToken": { + "summary": "auth.getToken", + "value": "cf45fe5a3e3cebe168480a086d7fe481" + }, + "track.scrobble": { + "summary": "track.scrobble", + "value": "ReckonerRadioheadIn Rainbows1700000000" + }, + "track.updateNowPlaying": { + "summary": "track.updateNowPlaying", + "value": "ReckonerRadiohead" + }, + "user.getInfo": { + "summary": "user.getInfo", + "value": "alice123421080001700000000" + }, + "user.getRecentTracks": { + "summary": "user.getRecentTracks", + "value": "RadioheadNudeIn RainbowsRadioheadReckonerIn Rainbows14 Nov 2023, 22:13" + }, + "user.getTopAlbums": { + "summary": "user.getTopAlbums", + "value": "In Rainbows20Radiohead" + }, + "user.getTopArtists": { + "summary": "user.getTopArtists", + "value": "Radiohead42" + }, + "user.getTopTracks": { + "summary": "user.getTopTracks", + "value": "Reckoner29012Radiohead" + } + } + }, + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "description": "Unknown method or invalid parameters (codes 3, 6)", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "example": "Invalid parameters" + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LastfmError" + } + } + } + }, + "403": { + "description": "Authentication failed (codes 4, 9, 10, 13, 14, 15)", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "example": "Invalid parameters" + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LastfmError" + } + } + } + } + } + }, + "post": { + "tags": [ + "Last.fm" + ], + "summary": "Call a Last.fm API method (form body)", + "description": "Same as GET, with parameters in an `application/x-www-form-urlencoded` body. Write methods (`track.*`, `auth.getMobileSession`) should use POST.", + "operationId": "lastfmPost", + "requestBody": { + "required": true, + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "oneOf": [ + { + "$ref": "#/components/schemas/LastfmAuthGetMobileSessionRequest" + }, + { + "$ref": "#/components/schemas/LastfmAuthGetSessionRequest" + }, + { + "$ref": "#/components/schemas/LastfmAuthGetTokenRequest" + }, + { + "$ref": "#/components/schemas/LastfmTrackScrobbleRequest" + }, + { + "$ref": "#/components/schemas/LastfmTrackUpdateNowPlayingRequest" + }, + { + "$ref": "#/components/schemas/LastfmUserGetInfoRequest" + }, + { + "$ref": "#/components/schemas/LastfmUserGetRecentTracksRequest" + }, + { + "$ref": "#/components/schemas/LastfmUserGetTopAlbumsRequest" + }, + { + "$ref": "#/components/schemas/LastfmUserGetTopArtistsRequest" + }, + { + "$ref": "#/components/schemas/LastfmUserGetTopTracksRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "`` wrapping the method's result, or JSON", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "examples": { + "auth.getMobileSession": { + "summary": "auth.getMobileSession", + "value": "aliced580d57f32848f5dcf574d1ce18d78b20" + }, + "auth.getSession": { + "summary": "auth.getSession", + "value": "aliced580d57f32848f5dcf574d1ce18d78b20" + }, + "auth.getToken": { + "summary": "auth.getToken", + "value": "cf45fe5a3e3cebe168480a086d7fe481" + }, + "track.scrobble": { + "summary": "track.scrobble", + "value": "ReckonerRadioheadIn Rainbows1700000000" + }, + "track.updateNowPlaying": { + "summary": "track.updateNowPlaying", + "value": "ReckonerRadiohead" + }, + "user.getInfo": { + "summary": "user.getInfo", + "value": "alice123421080001700000000" + }, + "user.getRecentTracks": { + "summary": "user.getRecentTracks", + "value": "RadioheadNudeIn RainbowsRadioheadReckonerIn Rainbows14 Nov 2023, 22:13" + }, + "user.getTopAlbums": { + "summary": "user.getTopAlbums", + "value": "In Rainbows20Radiohead" + }, + "user.getTopArtists": { + "summary": "user.getTopArtists", + "value": "Radiohead42" + }, + "user.getTopTracks": { + "summary": "user.getTopTracks", + "value": "Reckoner29012Radiohead" + } + } + }, + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "description": "Unknown method or invalid parameters (codes 3, 6)", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "example": "Invalid parameters" + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LastfmError" + } + } + } + }, + "403": { + "description": "Authentication failed (codes 4, 9, 10, 13, 14, 15)", + "content": { + "application/xml": { + "schema": { + "type": "string" + }, + "example": "Invalid parameters" + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LastfmError" + } + } + } + } + } + } + }, + "/api/auth/": { + "get": { + "tags": [ + "Last.fm" + ], + "summary": "Approve a desktop-auth token", + "description": "Where Last.fm clients send the user after `auth.getToken`. Redirects to the web UI's approve page, which asks the user to allow access.", + "operationId": "lastfmApproveRedirect", + "parameters": [ + { + "name": "api_key", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "token", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "302": { + "description": "Redirect to the web UI's approve page" + } + } + } + } + }, + "tags": [ + { + "name": "Auth", + "description": "Web UI accounts and login" + }, + { + "name": "Apps", + "description": "API applications. Each has an API key and shared secret that a scrobbling client uses against the Last.fm-compatible `/2.0/` endpoint." + }, + { + "name": "Sessions", + "description": "Last.fm session keys issued to scrobbling clients on your behalf." + }, + { + "name": "Tokens", + "description": "Approve Last.fm desktop-auth tokens. Clients send the user to `/api/auth/`, which redirects to the UI's approve page, which calls these endpoints." + }, + { + "name": "Stats", + "description": "Your listening history and statistics" + }, + { + "name": "Last.fm", + "description": "Last.fm-compatible API for players and scrobblers" + } + ], + "openapi": "3.1.0", + "components": { + "schemas": { + "ErrorDetail": { + "type": "object", + "properties": { + "code": { + "type": "string", + "example": "invalid_credentials" + }, + "message": { + "type": "string", + "example": "Wrong username or password" + }, + "details": { + "type": "object", + "description": "Per-field validation errors, if any", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + }, + "Error": { + "type": "object", + "properties": { + "error": { + "$ref": "#/components/schemas/ErrorDetail" + } + }, + "required": [ + "error" + ], + "additionalProperties": false + }, + "PaginationMetadata": { + "type": "object", + "properties": { + "total": { + "type": "integer", + "description": "Total number of items." + }, + "total_pages": { + "type": "integer", + "description": "Total number of pages." + }, + "first_page": { + "type": "integer", + "description": "First available page number." + }, + "last_page": { + "type": "integer", + "description": "Last available page number." + }, + "page": { + "type": "integer", + "description": "Current page number." + }, + "previous_page": { + "type": "integer", + "description": "Previous page number." + }, + "next_page": { + "type": "integer", + "description": "Next page number." + } + }, + "additionalProperties": false + }, + "Register": { + "type": "object", + "properties": { + "username": { + "type": "string", + "minLength": 2, + "maxLength": 32 + }, + "email": { + "type": "string", + "format": "email" + }, + "password": { + "type": "string", + "writeOnly": true, + "minLength": 8 + } + }, + "required": [ + "email", + "password", + "username" + ], + "additionalProperties": false + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "username": { + "type": "string", + "readOnly": true, + "example": "alice" + }, + "email": { + "type": "string", + "readOnly": true, + "example": "alice@example.com" + }, + "created_at": { + "type": "string", + "format": "date-time", + "readOnly": true + } + }, + "additionalProperties": false + }, + "Token": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "Bearer token for the Authorization header" + }, + "user": { + "$ref": "#/components/schemas/User" + } + }, + "required": [ + "token", + "user" + ], + "additionalProperties": false + }, + "Login": { + "type": "object", + "properties": { + "username": { + "type": "string" + }, + "password": { + "type": "string", + "writeOnly": true + } + }, + "required": [ + "password", + "username" + ], + "additionalProperties": false + }, + "ApiApp": { + "type": "object", + "properties": { + "name": { + "type": "string", + "readOnly": true, + "example": "Living room player" + }, + "api_key": { + "type": "string", + "readOnly": true, + "example": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + }, + "shared_secret": { + "type": "string", + "readOnly": true, + "example": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + }, + "created_at": { + "type": "string", + "format": "date-time", + "readOnly": true + } + }, + "additionalProperties": false + }, + "ApiAppCreate": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + }, + "required": [ + "name" + ], + "additionalProperties": false + }, + "Session": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "readOnly": true + }, + "app_name": { + "type": "string", + "readOnly": true, + "example": "Pano Scrobbler" + }, + "created_at": { + "type": "string", + "format": "date-time", + "readOnly": true + } + }, + "additionalProperties": false + }, + "AuthTokenInfo": { + "type": "object", + "properties": { + "app_name": { + "type": "string", + "readOnly": true, + "example": "Pano Scrobbler" + }, + "approved": { + "type": "boolean", + "readOnly": true + } + }, + "additionalProperties": false + }, + "ApproveToken": { + "type": "object", + "properties": { + "token": { + "type": "string", + "description": "Token from auth.getToken" + } + }, + "required": [ + "token" + ], + "additionalProperties": false + }, + "NowPlayingTrack": { + "type": "object", + "properties": { + "artist": { + "type": "string" + }, + "track": { + "type": "string" + }, + "album": { + "type": [ + "string", + "null" + ] + }, + "duration": { + "type": [ + "integer", + "null" + ] + }, + "started_at": { + "type": "string", + "format": "date-time" + }, + "expires_at": { + "type": "string", + "format": "date-time" + } + }, + "additionalProperties": false + }, + "NowPlaying": { + "type": "object", + "properties": { + "now_playing": { + "description": "null when idle", + "anyOf": [ + { + "$ref": "#/components/schemas/NowPlayingTrack" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "Scrobble": { + "type": "object", + "properties": { + "artist": { + "type": "string" + }, + "track": { + "type": "string" + }, + "album": { + "type": [ + "string", + "null" + ] + }, + "album_artist": { + "type": [ + "string", + "null" + ] + }, + "duration": { + "type": [ + "integer", + "null" + ] + }, + "played_at": { + "type": "string", + "format": "date-time" + } + }, + "additionalProperties": false + }, + "RecentPage": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "per_page": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_pages": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Scrobble" + } + } + }, + "additionalProperties": false + }, + "TopItem": { + "type": "object", + "properties": { + "rank": { + "type": "integer" + }, + "name": { + "type": "string" + }, + "artist": { + "type": [ + "string", + "null" + ], + "description": "Albums and tracks only" + }, + "playcount": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "TopPage": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "per_page": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_pages": { + "type": "integer" + }, + "period": { + "type": "string" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TopItem" + } + } + }, + "additionalProperties": false + }, + "Count": { + "type": "object", + "properties": { + "start": { + "type": "string", + "format": "date", + "description": "First day of the bucket (UTC)" + }, + "count": { + "type": "integer" + } + }, + "additionalProperties": false + }, + "Summary": { + "type": "object", + "properties": { + "scrobbles": { + "type": "integer" + }, + "artists": { + "type": "integer" + }, + "tracks": { + "type": "integer" + }, + "first_scrobble_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } + }, + "additionalProperties": false + }, + "LastfmError": { + "type": "object", + "properties": { + "error": { + "type": "integer", + "examples": [ + 6 + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "error", + "message" + ] + }, + "LastfmAuthGetMobileSessionRequest": { + "type": "object", + "title": "auth.getMobileSession", + "description": "Create a session key from a username and password", + "properties": { + "method": { + "type": "string", + "const": "auth.getMobileSession" + }, + "api_key": { + "type": "string" + }, + "api_sig": { + "type": "string", + "description": "md5 request signature" + }, + "username": { + "type": "string", + "description": "Username", + "examples": [ + "alice" + ] + }, + "password": { + "type": "string", + "description": "Password (send over HTTPS, as a POST body)" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "api_sig", + "username", + "password" + ] + }, + "LastfmAuthGetSessionRequest": { + "type": "object", + "title": "auth.getSession", + "description": "Exchange an approved token for a session key (desktop auth flow, step 3)", + "properties": { + "method": { + "type": "string", + "const": "auth.getSession" + }, + "api_key": { + "type": "string" + }, + "api_sig": { + "type": "string", + "description": "md5 request signature" + }, + "token": { + "type": "string", + "description": "Token from auth.getToken, approved by the user" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "api_sig", + "token" + ] + }, + "LastfmAuthGetTokenRequest": { + "type": "object", + "title": "auth.getToken", + "description": "Fetch an unapproved request token (desktop auth flow, step 1)", + "properties": { + "method": { + "type": "string", + "const": "auth.getToken" + }, + "api_key": { + "type": "string" + }, + "api_sig": { + "type": "string", + "description": "md5 request signature" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "api_sig" + ] + }, + "LastfmTrackScrobbleRequest": { + "type": "object", + "title": "track.scrobble", + "description": "Scrobble up to 50 tracks", + "properties": { + "method": { + "type": "string", + "const": "track.scrobble" + }, + "api_key": { + "type": "string" + }, + "api_sig": { + "type": "string", + "description": "md5 request signature" + }, + "sk": { + "type": "string", + "description": "Session key" + }, + "artist[i]": { + "type": "string", + "description": "Artist name", + "examples": [ + "Radiohead" + ] + }, + "track[i]": { + "type": "string", + "description": "Track title", + "examples": [ + "Reckoner" + ] + }, + "timestamp[i]": { + "type": "string", + "description": "Unix time the track started playing" + }, + "album[i]": { + "type": "string", + "description": "Album title" + }, + "albumArtist[i]": { + "type": "string", + "description": "Album artist, if different from the track artist" + }, + "duration[i]": { + "type": "string", + "description": "Track length in seconds" + }, + "trackNumber[i]": { + "type": "string", + "description": "Position on the album" + }, + "mbid[i]": { + "type": "string", + "description": "MusicBrainz track id" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "api_sig", + "sk", + "artist[i]", + "track[i]", + "timestamp[i]" + ] + }, + "LastfmTrackUpdateNowPlayingRequest": { + "type": "object", + "title": "track.updateNowPlaying", + "description": "Set the track the user is listening to now", + "properties": { + "method": { + "type": "string", + "const": "track.updateNowPlaying" + }, + "api_key": { + "type": "string" + }, + "api_sig": { + "type": "string", + "description": "md5 request signature" + }, + "sk": { + "type": "string", + "description": "Session key" + }, + "artist": { + "type": "string", + "description": "Artist name", + "examples": [ + "Radiohead" + ] + }, + "track": { + "type": "string", + "description": "Track title", + "examples": [ + "Reckoner" + ] + }, + "album": { + "type": "string", + "description": "Album title" + }, + "albumArtist": { + "type": "string", + "description": "Album artist" + }, + "duration": { + "type": "string", + "description": "Track length in seconds; now-playing expires after it" + }, + "trackNumber": { + "type": "string", + "description": "Position on the album" + }, + "mbid": { + "type": "string", + "description": "MusicBrainz track id" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "api_sig", + "sk", + "artist", + "track" + ] + }, + "LastfmUserGetInfoRequest": { + "type": "object", + "title": "user.getInfo", + "description": "A user's profile and play count", + "properties": { + "method": { + "type": "string", + "const": "user.getInfo" + }, + "api_key": { + "type": "string" + }, + "user": { + "type": "string", + "description": "Username to fetch data for", + "examples": [ + "alice" + ] + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "user" + ] + }, + "LastfmUserGetRecentTracksRequest": { + "type": "object", + "title": "user.getRecentTracks", + "description": "Recently scrobbled tracks, newest first, led by the now-playing track", + "properties": { + "method": { + "type": "string", + "const": "user.getRecentTracks" + }, + "api_key": { + "type": "string" + }, + "user": { + "type": "string", + "description": "Username to fetch data for", + "examples": [ + "alice" + ] + }, + "limit": { + "type": "string", + "description": "Results per page (default 50, max 200)", + "examples": [ + "50" + ] + }, + "page": { + "type": "string", + "description": "Page number (default 1)", + "examples": [ + "1" + ] + }, + "from": { + "type": "string", + "description": "Only scrobbles at or after this Unix time" + }, + "to": { + "type": "string", + "description": "Only scrobbles at or before this Unix time" + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "user" + ] + }, + "LastfmUserGetTopAlbumsRequest": { + "type": "object", + "title": "user.getTopAlbums", + "description": "Most played albums over a period", + "properties": { + "method": { + "type": "string", + "const": "user.getTopAlbums" + }, + "api_key": { + "type": "string" + }, + "user": { + "type": "string", + "description": "Username to fetch data for", + "examples": [ + "alice" + ] + }, + "period": { + "type": "string", + "description": "overall | 7day | 1month | 3month | 6month | 12month (default overall)", + "examples": [ + "7day" + ] + }, + "limit": { + "type": "string", + "description": "Results per page (default 50, max 1000)", + "examples": [ + "50" + ] + }, + "page": { + "type": "string", + "description": "Page number (default 1)", + "examples": [ + "1" + ] + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "user" + ] + }, + "LastfmUserGetTopArtistsRequest": { + "type": "object", + "title": "user.getTopArtists", + "description": "Most played artists over a period", + "properties": { + "method": { + "type": "string", + "const": "user.getTopArtists" + }, + "api_key": { + "type": "string" + }, + "user": { + "type": "string", + "description": "Username to fetch data for", + "examples": [ + "alice" + ] + }, + "period": { + "type": "string", + "description": "overall | 7day | 1month | 3month | 6month | 12month (default overall)", + "examples": [ + "7day" + ] + }, + "limit": { + "type": "string", + "description": "Results per page (default 50, max 1000)", + "examples": [ + "50" + ] + }, + "page": { + "type": "string", + "description": "Page number (default 1)", + "examples": [ + "1" + ] + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "user" + ] + }, + "LastfmUserGetTopTracksRequest": { + "type": "object", + "title": "user.getTopTracks", + "description": "Most played tracks over a period", + "properties": { + "method": { + "type": "string", + "const": "user.getTopTracks" + }, + "api_key": { + "type": "string" + }, + "user": { + "type": "string", + "description": "Username to fetch data for", + "examples": [ + "alice" + ] + }, + "period": { + "type": "string", + "description": "overall | 7day | 1month | 3month | 6month | 12month (default overall)", + "examples": [ + "7day" + ] + }, + "limit": { + "type": "string", + "description": "Results per page (default 50, max 1000)", + "examples": [ + "50" + ] + }, + "page": { + "type": "string", + "description": "Page number (default 1)", + "examples": [ + "1" + ] + }, + "format": { + "type": "string", + "enum": [ + "xml", + "json" + ], + "default": "xml" + } + }, + "required": [ + "method", + "api_key", + "user" + ] + } + }, + "responses": { + "UNPROCESSABLE_CONTENT": { + "description": "Unprocessable Content", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "DEFAULT_ERROR": { + "description": "Default error response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "securitySchemes": { + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "description": "Token from POST /api/v1/auth/login" + } + } + } +} diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index 3ed2e10..7a520ab 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -50,3 +50,7 @@ def init_app(app: Flask) -> None: api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions") api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens") api.register_blueprint(stats.blp, url_prefix="/api/v1/me") + + from scrobbler.openapi import lastfm + + lastfm.register(app, api) diff --git a/src/scrobbler/api/apps.py b/src/scrobbler/api/apps.py index 1c2d754..d1322cc 100644 --- a/src/scrobbler/api/apps.py +++ b/src/scrobbler/api/apps.py @@ -6,7 +6,7 @@ from scrobbler.schemas import ApiAppCreateSchema, ApiAppSchema, ErrorSchema from scrobbler.services import accounts blp = Blueprint( - "ui_apps", + "Apps", __name__, description=( "API applications. Each has an API key and shared secret that a scrobbling " diff --git a/src/scrobbler/api/auth.py b/src/scrobbler/api/auth.py index 214178e..af1614f 100644 --- a/src/scrobbler/api/auth.py +++ b/src/scrobbler/api/auth.py @@ -6,7 +6,7 @@ from scrobbler.api.decorators import authenticated, bearer_token from scrobbler.schemas import ErrorSchema, LoginSchema, RegisterSchema, TokenSchema, UserSchema from scrobbler.services import accounts -blp = Blueprint("ui_auth", __name__, description="Web UI accounts and login") +blp = Blueprint("Auth", __name__, description="Web UI accounts and login") @blp.route("/register", methods=["POST"]) diff --git a/src/scrobbler/api/sessions.py b/src/scrobbler/api/sessions.py index 66bc565..0c2498e 100644 --- a/src/scrobbler/api/sessions.py +++ b/src/scrobbler/api/sessions.py @@ -6,7 +6,7 @@ from scrobbler.schemas import ErrorSchema, SessionSchema from scrobbler.services import accounts blp = Blueprint( - "ui_sessions", + "Sessions", __name__, description="Last.fm session keys issued to scrobbling clients on your behalf.", ) diff --git a/src/scrobbler/api/stats.py b/src/scrobbler/api/stats.py index c0d97a3..792495b 100644 --- a/src/scrobbler/api/stats.py +++ b/src/scrobbler/api/stats.py @@ -14,7 +14,7 @@ from scrobbler.schemas import ( ) from scrobbler.services import scrobbles, stats -blp = Blueprint("ui_stats", __name__, description="Your listening history and statistics") +blp = Blueprint("Stats", __name__, description="Your listening history and statistics") TOP_KINDS = { "artists": stats.top_artists, diff --git a/src/scrobbler/api/tokens.py b/src/scrobbler/api/tokens.py index 2c6394e..cd7599a 100644 --- a/src/scrobbler/api/tokens.py +++ b/src/scrobbler/api/tokens.py @@ -6,7 +6,7 @@ from scrobbler.schemas import ApproveTokenSchema, AuthTokenInfoSchema, ErrorSche from scrobbler.services import accounts blp = Blueprint( - "ui_tokens", + "Tokens", __name__, description=( "Approve Last.fm desktop-auth tokens. Clients send the user to `/api/auth/`, " diff --git a/src/scrobbler/openapi/__init__.py b/src/scrobbler/openapi/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/scrobbler/openapi/lastfm.py b/src/scrobbler/openapi/lastfm.py new file mode 100644 index 0000000..16a8326 --- /dev/null +++ b/src/scrobbler/openapi/lastfm.py @@ -0,0 +1,241 @@ +"""OpenAPI description of the Last.fm-compatible /2.0/ endpoint. + +/2.0/ is a single endpoint that dispatches on the `method` parameter, which OpenAPI +can't express as one operation per method. It's documented as one GET and one POST +operation, with `method` as an enum and every method's parameters, auth needs, +notes and example responses generated from the handler registry. +""" + +from flask import Flask +from flask_smorest import Api + +from scrobbler.lastfm.errors import MESSAGES +from scrobbler.lastfm.registry import METHODS, LastfmMethod + +TAG = "Last.fm" + +COMMON_PARAMS = [ + ("method", "The API method to call, e.g. `track.scrobble`", True), + ("api_key", "API key of one of your applications", True), + ("api_sig", "Request signature; required by signed methods (see below)", False), + ("sk", "Session key; required by methods that act as a user", False), + ("format", "`xml` (default) or `json`", False), +] + +INTRO = """\ +Last.fm (Audioscrobbler 2.0) compatible API. Point a scrobbler's "custom Last.fm +server" setting at this server's `/2.0/`. + +**Signing.** Signed methods need `api_sig`: take every parameter except `format`, +`callback` and `api_sig`, sort by name, concatenate each name followed by its +value, append your application's shared secret, and take the md5 hex digest. + +**Sessions.** Methods that act as a user need `sk`, a session key from +`auth.getMobileSession` or the desktop flow (`auth.getToken`, approval at +`/api/auth/`, then `auth.getSession`). + +**Errors** use Last.fm's codes: {errors}. + +## Methods +""" + + +def _method_section(method: LastfmMethod) -> str: + needs = [] + if method.signed: + needs.append("signed") + if method.session: + needs.append("session key") + lines = [f"### `{method.name}`", "", method.summary + ".", ""] + lines.append(f"*Requires:* {', '.join(needs) if needs else 'api_key only'}.") + if method.params: + lines += ["", "| Parameter | Required | Description |", "|---|---|---|"] + lines += [ + f"| `{p.name}` | {'yes' if p.required else 'no'} | {p.description} |" + for p in method.params + ] + if method.notes: + lines += ["", method.notes] + return "\n".join(lines) + + +def _params_schema(method: LastfmMethod) -> dict: + properties = { + "method": {"type": "string", "const": method.name}, + "api_key": {"type": "string"}, + } + required = ["method", "api_key"] + if method.signed: + properties["api_sig"] = {"type": "string", "description": "md5 request signature"} + required.append("api_sig") + if method.session: + properties["sk"] = {"type": "string", "description": "Session key"} + required.append("sk") + for param in method.params: + prop = {"type": "string", "description": param.description} + if param.example is not None: + prop["examples"] = [param.example] + properties[param.name] = prop + if param.required: + required.append(param.name) + properties["format"] = {"type": "string", "enum": ["xml", "json"], "default": "xml"} + return { + "type": "object", + "title": method.name, + "description": method.summary, + "properties": properties, + "required": required, + } + + +def _schema_name(method: LastfmMethod) -> str: + return "Lastfm" + "".join(part[:1].upper() + part[1:] for part in method.name.split(".")) + + +def register(app: Flask, api: Api) -> None: + rules = {rule.endpoint: rule for rule in app.url_map.iter_rules()} + methods = sorted(METHODS.values(), key=lambda m: m.name) + spec = api.spec + + spec.tag({"name": TAG, "description": "Last.fm-compatible API for players and scrobblers"}) + spec.components.schema( + "LastfmError", + { + "type": "object", + "properties": { + "error": {"type": "integer", "examples": [6]}, + "message": {"type": "string"}, + }, + "required": ["error", "message"], + }, + ) + for method in methods: + spec.components.schema(f"{_schema_name(method)}Request", _params_schema(method)) + + errors = ", ".join(f"{code} ({message.split(' - ')[0]})" for code, message in MESSAGES.items()) + description = INTRO.format(errors=errors) + "\n\n".join(map(_method_section, methods)) + + # Every non-array parameter any method takes, so "Try it out" works for all of them. + method_params = {} + for method in methods: + for param in method.params: + if not param.name.endswith("[i]"): + method_params.setdefault(param.name, param) + + query_params = [ + { + "name": name, + "in": "query", + "required": required, + "description": desc, + "schema": ( + {"type": "string", "enum": [m.name for m in methods]} + if name == "method" + else {"type": "string", "enum": ["xml", "json"]} + if name == "format" + else {"type": "string"} + ), + } + for name, desc, required in COMMON_PARAMS + ] + [ + { + "name": p.name, + "in": "query", + "required": False, + "description": f"{p.description} (only for methods that take it)", + "schema": {"type": "string"}, + } + for p in method_params.values() + ] + + responses = { + "200": { + "description": '`` wrapping the method\'s result, or JSON', + "content": { + "application/xml": { + "schema": {"type": "string"}, + "examples": { + m.name: {"summary": m.name, "value": m.example_xml} + for m in methods + if m.example_xml + }, + }, + "application/json": {"schema": {"type": "object"}}, + }, + }, + "400": _error_response("Unknown method or invalid parameters (codes 3, 6)"), + "403": _error_response("Authentication failed (codes 4, 9, 10, 13, 14, 15)"), + } + + request_schemas = [{"$ref": f"#/components/schemas/{_schema_name(m)}Request"} for m in methods] + spec.path( + rule=rules["lastfm.dispatch"], + operations={ + "get": { + "tags": [TAG], + "summary": "Call a Last.fm API method (query string)", + "description": description, + "operationId": "lastfmGet", + "parameters": query_params, + "responses": responses, + }, + "post": { + "tags": [TAG], + "summary": "Call a Last.fm API method (form body)", + "description": ( + "Same as GET, with parameters in an `application/x-www-form-urlencoded` " + "body. Write methods (`track.*`, `auth.getMobileSession`) should use POST." + ), + "operationId": "lastfmPost", + "requestBody": { + "required": True, + "content": { + "application/x-www-form-urlencoded": {"schema": {"oneOf": request_schemas}} + }, + }, + "responses": responses, + }, + }, + ) + spec.path( + rule=rules["lastfm.approve_redirect"], + operations={ + "get": { + "tags": [TAG], + "summary": "Approve a desktop-auth token", + "description": ( + "Where Last.fm clients send the user after `auth.getToken`. Redirects to " + "the web UI's approve page, which asks the user to allow access." + ), + "operationId": "lastfmApproveRedirect", + "parameters": [ + { + "name": "api_key", + "in": "query", + "required": True, + "schema": {"type": "string"}, + }, + { + "name": "token", + "in": "query", + "required": True, + "schema": {"type": "string"}, + }, + ], + "responses": {"302": {"description": "Redirect to the web UI's approve page"}}, + } + }, + ) + + +def _error_response(description: str) -> dict: + return { + "description": description, + "content": { + "application/xml": { + "schema": {"type": "string"}, + "example": 'Invalid parameters', + }, + "application/json": {"schema": {"$ref": "#/components/schemas/LastfmError"}}, + }, + } diff --git a/tests/test_openapi.py b/tests/test_openapi.py new file mode 100644 index 0000000..da5b309 --- /dev/null +++ b/tests/test_openapi.py @@ -0,0 +1,75 @@ +import json +import re +from pathlib import Path + +import pytest +from openapi_spec_validator import validate + +from scrobbler.lastfm.registry import METHODS + +COMMITTED_SPEC = Path(__file__).resolve().parents[1] / "docs" / "openapi.json" +DOCUMENTED_PREFIXES = ("/api/v1/", "/2.0/", "/api/auth/") +HTTP_VERBS = {"get", "put", "post", "delete", "patch", "head", "options"} + + +@pytest.fixture(scope="module") +def spec(app): + return app.test_client().get("/api/openapi.json").get_json() + + +def openapi_path(rule: str) -> str: + return re.sub(r"<(?:[^:<>]+:)?([^<>]+)>", r"{\1}", rule) + + +def test_spec_is_valid_openapi(spec): + validate(spec) + + +def test_every_api_route_is_documented(app, spec): + for rule in app.url_map.iter_rules(): + if not rule.rule.startswith(DOCUMENTED_PREFIXES): + continue + path = openapi_path(rule.rule) + assert path in spec["paths"], f"{rule.rule} is missing from the OpenAPI document" + documented = {m.upper() for m in spec["paths"][path] if m in HTTP_VERBS} + assert rule.methods - {"HEAD", "OPTIONS"} <= documented, rule.rule + + +def test_every_lastfm_method_is_documented(spec): + get = spec["paths"]["/2.0/"]["get"] + [method_param] = [p for p in get["parameters"] if p["name"] == "method"] + assert set(method_param["schema"]["enum"]) == {m.name for m in METHODS.values()} + for method in METHODS.values(): + assert f"### `{method.name}`" in get["description"] + request_schemas = spec["paths"]["/2.0/"]["post"]["requestBody"]["content"][ + "application/x-www-form-urlencoded" + ]["schema"]["oneOf"] + assert len(request_schemas) == len(METHODS) + + +def test_ui_routes_declare_bearer_auth(spec): + public = {("/api/v1/auth/login", "post"), ("/api/v1/auth/register", "post")} + for path, operations in spec["paths"].items(): + if not path.startswith("/api/v1/"): + continue + for verb, operation in operations.items(): + if verb not in HTTP_VERBS: + continue + if (path, verb) in public: + assert "security" not in operation + else: + assert operation.get("security") == [{"bearerAuth": []}], f"{verb} {path}" + assert "401" in operation["responses"], f"{verb} {path}" + + +def test_docs_pages_are_served(client): + assert client.get("/api/docs").status_code == 200 + assert client.get("/api/redoc").status_code == 200 + + +def test_committed_spec_is_up_to_date(spec): + committed = json.loads(COMMITTED_SPEC.read_text()) + assert committed == spec, ( + "docs/openapi.json is stale. Regenerate it with: " + "uv run flask --app scrobbler openapi write --format=json docs/openapi.json" + ) diff --git a/tests/test_ui_auth.py b/tests/test_ui_auth.py index 9563b8b..7e9bc8b 100644 --- a/tests/test_ui_auth.py +++ b/tests/test_ui_auth.py @@ -98,12 +98,3 @@ def test_cors_allows_only_the_configured_ui_origin(client, app): "/api/v1/auth/me", headers={"Origin": "https://evil.example", **preflight} ) assert "Access-Control-Allow-Origin" not in evil.headers - - -def test_api_docs_are_served(client): - spec = client.get("/api/openapi.json").get_json() - assert "/api/v1/auth/login" in spec["paths"] - assert spec["components"]["securitySchemes"]["bearerAuth"]["scheme"] == "bearer" - assert spec["paths"]["/api/v1/auth/me"]["get"]["security"] == [{"bearerAuth": []}] - assert client.get("/api/docs").status_code == 200 - assert client.get("/api/redoc").status_code == 200