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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
b509cd2b60
commit
89f8589424
11 files changed
+2828
-14
No files matched your search
+2503
File diff suppressed because it is too large.
Load diff
@@ -50,3 +50,7 @@ def init_app(app: Flask) -> None:
|
|||||||
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions")
|
||||||
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens")
|
||||||
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
api.register_blueprint(stats.blp, url_prefix="/api/v1/me")
|
||||||
|
|
||||||
|
from scrobbler.openapi import lastfm
|
||||||
|
|
||||||
|
lastfm.register(app, api)
|
||||||
@@ -6,7 +6,7 @@ from scrobbler.schemas import ApiAppCreateSchema, ApiAppSchema, ErrorSchema
|
|||||||
from scrobbler.services import accounts
|
from scrobbler.services import accounts
|
||||||
|
|
||||||
blp = Blueprint(
|
blp = Blueprint(
|
||||||
"ui_apps",
|
"Apps",
|
||||||
__name__,
|
__name__,
|
||||||
description=(
|
description=(
|
||||||
"API applications. Each has an API key and shared secret that a scrobbling "
|
"API applications. Each has an API key and shared secret that a scrobbling "
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from scrobbler.api.decorators import authenticated, bearer_token
|
|||||||
from scrobbler.schemas import ErrorSchema, LoginSchema, RegisterSchema, TokenSchema, UserSchema
|
from scrobbler.schemas import ErrorSchema, LoginSchema, RegisterSchema, TokenSchema, UserSchema
|
||||||
from scrobbler.services import accounts
|
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"])
|
@blp.route("/register", methods=["POST"])
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from scrobbler.schemas import ErrorSchema, SessionSchema
|
|||||||
from scrobbler.services import accounts
|
from scrobbler.services import accounts
|
||||||
|
|
||||||
blp = Blueprint(
|
blp = Blueprint(
|
||||||
"ui_sessions",
|
"Sessions",
|
||||||
__name__,
|
__name__,
|
||||||
description="Last.fm session keys issued to scrobbling clients on your behalf.",
|
description="Last.fm session keys issued to scrobbling clients on your behalf.",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from scrobbler.schemas import (
|
|||||||
)
|
)
|
||||||
from scrobbler.services import scrobbles, stats
|
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 = {
|
TOP_KINDS = {
|
||||||
"artists": stats.top_artists,
|
"artists": stats.top_artists,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from scrobbler.schemas import ApproveTokenSchema, AuthTokenInfoSchema, ErrorSche
|
|||||||
from scrobbler.services import accounts
|
from scrobbler.services import accounts
|
||||||
|
|
||||||
blp = Blueprint(
|
blp = Blueprint(
|
||||||
"ui_tokens",
|
"Tokens",
|
||||||
__name__,
|
__name__,
|
||||||
description=(
|
description=(
|
||||||
"Approve Last.fm desktop-auth tokens. Clients send the user to `/api/auth/`, "
|
"Approve Last.fm desktop-auth tokens. Clients send the user to `/api/auth/`, "
|
||||||
|
|||||||
Whitespace-only changes.
@@ -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": '`<lfm status="ok">` 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": '<lfm status="failed"><error code="6">Invalid parameters</error></lfm>',
|
||||||
|
},
|
||||||
|
"application/json": {"schema": {"$ref": "#/components/schemas/LastfmError"}},
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
)
|
||||||
@@ -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}
|
"/api/v1/auth/me", headers={"Origin": "https://evil.example", **preflight}
|
||||||
)
|
)
|
||||||
assert "Access-Control-Allow-Origin" not in evil.headers
|
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
|
|
||||||
Reference in new issue
Block a user