Introducing a new way to review your PRs.

Read the announcement

crmne / spotifast

Spotify, native and fast. One lightweight Rust app for your whole library, local playback, and Spotify Connect on Linux, macOS, and Windows.

View on GitHub

19 documents · Updated Nov 18, 2026

docs / spotify-api-client-and-gateway

Spotify API client and gateway

The Spotify API client and gateway provide one safe boundary for account data, catalogue data, playlist changes, and playback control. They select the right Spotify access grant, send requests through the shared HTTP transport, limit request pressure, and turn changing Spotify responses into stable app data.

Access boundary

The Web API boundary is split between a typed client and an account-aware gateway. The client knows how to call Spotify. The gateway decides which authorized source may answer each kind of request.

API client

The client exposes typed operations for identity, playback, queues, playlists, libraries, search, and catalogue pages. Callers work with domain values such as Track, Playlist, and PlaybackState instead of raw HTTP responses. One request boundary adds the current Web API token, applies shared request rules, and returns stable success or error results for both reads and writes. References: src/…/client.rs• L1-5, src/…/client.rs• L378-455, src/…/client.rs• L531-719, src/…/client.rs• L721-1327

API gateway

The gateway coordinates two possible Web API sessions: Shared is a legacy app grant that may still work, and Personal is the listener’s own Spotify app. It maps an Operation to a source based on account state and playlist access. A personal session takes over when no shared grant exists. Both sessions must belong to the same Spotify account. References: src/…/gateway.rs• L56-143, src/…/gateway.rs• L192-257, src/…/gateway.rs• L303-407

Playlist access is learned from playlist ownership and collaboration state. Unknown or external playlists remain on the source that can read them, while owned and collaborative playlists can use the personal source when it is ready. This keeps restricted development-mode access from changing the meaning of a playlist operation. References: src/…/gateway.rs• L76-155, src/…/gateway.rs• L415-446

Request flow

The request flow starts with an operation, waits for a matching session, obtains a current token, sends the HTTP request, and returns typed data or a boundary error. Requests to the partner service use a separate wait state so a slow or limited partner call does not block unrelated Web API calls.

This diagram shows how an app operation becomes a Spotify request and then a typed result or boundary error.

flowchart LR
    A[App operation] --> B[API gateway]
    B --> C{Shared or personal session}
    C --> D[API client]
    D --> E[Current Web API token]
    E --> F[Shared HTTP transport]
    F --> G[Spotify Web API]
    G --> H[Typed model or ApiError]

References: src/…/gateway.rs• L368-407 src/…/client.rs• L463-507 src/…/client.rs• L531-675 src/…/models.rs• L28-42

HTTP transport

The HTTP layer gives all network users a replaceable client. The Web API, token refresh, artwork, lyrics, and update checks can therefore follow one proxy choice and pick up a corrected client without restarting the app. References: src/http.rs• L1-16

Shared HTTP client

src/http.rs defines the shared Http handle. Its state can hold either a working client or a configuration error. An invalid proxy does not silently become a direct connection. A successful replacement makes the new client visible to every clone of the handle. References: src/http.rs• L18-57, src/http.rs• L93-140

The transport supports no proxy, system proxy, HTTP proxy, and SOCKS5 proxy modes. It applies the app user agent and uses bounded timeouts. Collection mutations use a stricter client with no automatic retries or redirects because an uncertain write must not be replayed. References: src/http.rs• L65-80, src/http.rs• L106-135

Request control

The client controls request load at the boundary instead of leaving each caller to manage Spotify limits. Foreground work has a separate budget from background work, and each authorized source keeps its own cooldown when Spotify asks the app to wait. References: src/…/client.rs• L22-26, src/…/client.rs• L378-427, src/…/client.rs• L509-527

Concurrency and cooldowns

Normal requests allow up to six in flight. Background work has four additional permits so quiet checks do not consume the foreground budget. A 429 response extends the source cooldown from Retry-After; ordinary requests retry within a bounded policy, while queue writes preserve order and honor the server wait. Partner requests use a separate cooldown that is also bounded and cannot be shortened by an older response. References: src/…/client.rs• L424-427, src/…/client.rs• L461-527, src/…/client.rs• L565-638, src/…/client.rs• L2114-2134

The client reports live network activity to the interface. The activity covers the logical request while it waits for capacity or a cooldown. Background checks can run as unseen work, so a rate-limited grant check does not make the whole app look blocked. Shared-source rate limits are counted separately because they can guide the user toward a personal app. References: src/…/client.rs• L286-375, src/…/client.rs• L559-564

Data model boundary

The model layer converts Spotify JSON into stable values used by the rest of the app. It treats missing and null fields as normal because Spotify may omit fields by endpoint, account, market, or response version. References: src/…/models.rs• L1-26, src/…/models.rs• L188-232

Collection models

Page and cursor models express the two main Spotify paging styles. A page carries its offset and next link. A cursor page carries its cursor values. Null list entries are skipped when they do not affect positions. Positional track endpoints keep null slots so later playback and edit offsets remain correct. References: src/…/models.rs• L28-122

Media and account models

Tracks, episodes, albums, shows, artists, playlists, devices, playback state, queues, users, and search results form the main data contract. PlayableItem gives tracks and episodes one shared interface for mixed Spotify lists. Playlist items accept both the current item field and the older track field. References: src/…/models.rs• L211-344, src/…/models.rs• L399-532, src/…/models.rs• L594-685, src/…/models.rs• L739-864

The models also retain identity that matters across Spotify responses. Track recording keys can link market-specific releases, playlist snapshots support safe edits, and image selection chooses an artwork size suited to the display. These values let higher layers compare, render, and update content without parsing Spotify JSON again. References: src/…/models.rs• L124-186, src/…/models.rs• L338-370, src/…/models.rs• L534-592, src/…/models.rs• L879-900

Error and credential boundaries

The API boundary separates an unavailable session, an invalid grant, a network failure, a bad Spotify status, a rate limit, and an unreadable response. This lets the app choose between sign-in guidance, retry behavior, quota guidance, and ordinary failure feedback. References: src/…/client.rs• L28-69

Token lifecycle

Web API access uses a registered app’s PKCE grant. The client refreshes the grant before expiry and retries once after Spotify rejects the current access token. A rejected refresh ends the session. Tokens are remembered only after the Web API verifies the account, and refreshes update protected credential storage when persistence is enabled. A request that receives a late rejection does not replace a newer token from the same session. References: src/…/client.rs• L85-116, src/…/client.rs• L119-215, src/…/client.rs• L597-600

The Web API grant is separate from the playback grant. Playback uses Spotify’s desktop-client identity for streaming, while Web API calls use a personal app or an older shared app grant. A playback token is not a substitute for Web API authorization. References: src/auth.rs• L1-17, src/auth.rs• L33-65

Transport and API errors

Transport failures become network errors and JSON failures become decode errors. Spotify status responses keep their status code and a safe message. 401 can trigger one token refresh. 429 can become a bounded rate-limit error or a development-mode quota error. Successful writes do not require a JSON body because Spotify player commands may return an empty or non-JSON response. References: src/…/client.rs• L59-76, src/…/client.rs• L597-719

Protected credential storage

Durable Web API grants pass through a credential lease that ties each asynchronous read or write to the current sign-in generation. Sign-out invalidates old work before deletion, so a late refresh cannot restore an account. The native credential store is the durable boundary; ordinary state JSON is not the source for active grants. References: src/credentials.rs• L1-20, src/credentials.rs• L58-110, src/credentials.rs• L721-759, src/credentials.rs• L907-1072

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the gateway operation matrix aligned with playlist access classification and the fallback from shared to personal access.
  • Keep Web API scopes, token refresh behavior, and the protected credential slots aligned when a feature adds a new account capability.
  • Preserve both item and track playlist-entry shapes when Spotify changes response names.
  • Preserve positional nulls in album and other offset-based track pages; removing them changes later edit and playback positions.
  • Keep Retry-After, queue-write ordering, source-specific cooldowns, and the separate partner cooldown aligned when request retry policy changes.
  • Keep the logical activity signal aligned with permit waits and cooldown waits so the interface does not report the wrong network state.
  • Update every consumer of the shared Http handle when proxy failure or replacement behavior changes; invalid configuration must not regain a direct path.

Important failure modes

TriggerConsequenceGuard
Shared and personal grants belong to different accountsThe second session is rejected and cannot be installedThe gateway checks account identity before marking a session ready
Spotify returns 429 with a long waitRequests enter cooldown and may return RateLimitedCooldowns honor Retry-After with a bounded wait; queue writes keep their ordered retry path
Concurrent partner responses carry different waitsA later, longer wait could be lost and requests could resume too soonThe partner cooldown keeps the maximum wait and caps extreme headers
Spotify reports QUOTA_EXCEEDEDThe request stops with a quota message instead of a normal retry errorThe client checks the structured error reason before applying rate-limit retries
A stored refresh grant is rejectedThe Web API session becomes expired and needs browser sign-inToken refresh maps grant rejection to SignInExpired
A late request uses a grant after sign-outOld work could return or persist credentials for the signed-out accountThe credential lease rejects stale generations before token use or save
Proxy construction failsAll clones remain unavailable instead of bypassing the configured proxyHttp stores the build error until a valid client replaces it
A playlist response changes track to item or omits fieldsContent could disappear or pages could fail to decodeModels accept both entry names and default optional fields

Key files

FileWhy to read it
src/…/gateway.rsUnderstand source selection, session state, playlist access, and account binding
src/…/client.rsUnderstand typed Web API operations, token use, request limits, partner requests, retries, and error mapping
src/…/models.rsUnderstand the stable data contract between Spotify responses and app features
src/http.rsUnderstand proxy selection, client replacement, timeouts, and transport failure behavior
src/auth.rsUnderstand the separate Web API and playback grants and their token lifecycle
src/credentials.rsUnderstand protected grant persistence, sign-out invalidation, and stale-work protection
Spotify service integrationRead the wider boundary between Web API access, playback, Connect, and Spotify-specific services
Authentication and credentialsRead the user sign-in flow and credential ownership in more detail