Class: Spotted::Client

Inherits:
Internal::Transport::BaseClient show all
Defined in:
lib/spotted/client.rb

Constant Summary collapse

DEFAULT_MAX_RETRIES =

Default max number of retries to attempt after a failed retryable request.

2
DEFAULT_TIMEOUT_IN_SECONDS =

Default per-request timeout.

60.0
DEFAULT_INITIAL_RETRY_DELAY =

Default initial retry delay in seconds. Overall delay is calculated using exponential backoff + jitter.

0.5
DEFAULT_MAX_RETRY_DELAY =

Default max retry delay in seconds.

8.0

Constants inherited from Internal::Transport::BaseClient

Internal::Transport::BaseClient::MAX_REDIRECTS, Internal::Transport::BaseClient::PLATFORM_HEADERS

Instance Attribute Summary collapse

Attributes inherited from Internal::Transport::BaseClient

#base_url, #headers, #idempotency_header, #initial_retry_delay, #max_retries, #max_retry_delay, #requester, #timeout

Instance Method Summary collapse

Methods inherited from Internal::Transport::BaseClient

follow_redirect, #inspect, reap_connection!, #request, #send_request, should_retry?, validate!

Methods included from Internal::Util::SorbetRuntimeSupport

#const_missing, #define_sorbet_constant!, #sorbet_constant_defined?, #to_sorbet_type, to_sorbet_type

Constructor Details

#initialize(client_id: ENV["SPOTIFY_CLIENT_ID"], client_secret: ENV["SPOTIFY_CLIENT_SECRET"], access_token: ENV["SPOTIFY_ACCESS_TOKEN"], base_url: ENV["SPOTTED_BASE_URL"], max_retries: self.class::DEFAULT_MAX_RETRIES, timeout: self.class::DEFAULT_TIMEOUT_IN_SECONDS, initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY, max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY) ⇒ Client

Creates and returns a new client for interacting with the API.

‘“api.example.com/v2/”`. Defaults to `ENV`

Parameters:

  • client_id (String, nil) (defaults to: ENV["SPOTIFY_CLIENT_ID"])

    Defaults to ‘ENV`

  • client_secret (String, nil) (defaults to: ENV["SPOTIFY_CLIENT_SECRET"])

    Defaults to ‘ENV`

  • access_token (String, nil) (defaults to: ENV["SPOTIFY_ACCESS_TOKEN"])

    Defaults to ‘ENV`

  • base_url (String, nil) (defaults to: ENV["SPOTTED_BASE_URL"])

    Override the default base URL for the API, e.g.,

  • max_retries (Integer) (defaults to: self.class::DEFAULT_MAX_RETRIES)

    Max number of retries to attempt after a failed retryable request.

  • timeout (Float) (defaults to: self.class::DEFAULT_TIMEOUT_IN_SECONDS)
  • initial_retry_delay (Float) (defaults to: self.class::DEFAULT_INITIAL_RETRY_DELAY)
  • max_retry_delay (Float) (defaults to: self.class::DEFAULT_MAX_RETRY_DELAY)


148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/spotted/client.rb', line 148

def initialize(
  client_id: ENV["SPOTIFY_CLIENT_ID"],
  client_secret: ENV["SPOTIFY_CLIENT_SECRET"],
  access_token: ENV["SPOTIFY_ACCESS_TOKEN"],
  base_url: ENV["SPOTTED_BASE_URL"],
  max_retries: self.class::DEFAULT_MAX_RETRIES,
  timeout: self.class::DEFAULT_TIMEOUT_IN_SECONDS,
  initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY,
  max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY
)
  base_url ||= "https://api.spotify.com/v1"

  @client_id = client_id&.to_s
  @client_secret = client_secret&.to_s
  @access_token = access_token&.to_s

  super(
    base_url: base_url,
    timeout: timeout,
    max_retries: max_retries,
    initial_retry_delay: initial_retry_delay,
    max_retry_delay: max_retry_delay
  )

  @albums = Spotted::Resources::Albums.new(client: self)
  @artists = Spotted::Resources::Artists.new(client: self)
  @shows = Spotted::Resources::Shows.new(client: self)
  @episodes = Spotted::Resources::Episodes.new(client: self)
  @audiobooks = Spotted::Resources::Audiobooks.new(client: self)
  @me = Spotted::Resources::Me.new(client: self)
  @chapters = Spotted::Resources::Chapters.new(client: self)
  @tracks = Spotted::Resources::Tracks.new(client: self)
  @search = Spotted::Resources::Search.new(client: self)
  @playlists = Spotted::Resources::Playlists.new(client: self)
  @users = Spotted::Resources::Users.new(client: self)
  @browse = Spotted::Resources::Browse.new(client: self)
  @audio_features = Spotted::Resources::AudioFeatures.new(client: self)
  @audio_analysis = Spotted::Resources::AudioAnalysis.new(client: self)
  @recommendations = Spotted::Resources::Recommendations.new(client: self)
  @markets = Spotted::Resources::Markets.new(client: self)
end

Instance Attribute Details

#access_tokenString? (readonly)

Returns:

  • (String, nil)


25
26
27
# File 'lib/spotted/client.rb', line 25

def access_token
  @access_token
end

#albumsSpotted::Resources::Albums (readonly)



28
29
30
# File 'lib/spotted/client.rb', line 28

def albums
  @albums
end

#artistsSpotted::Resources::Artists (readonly)



31
32
33
# File 'lib/spotted/client.rb', line 31

def artists
  @artists
end

#audio_analysisSpotted::Resources::AudioAnalysis (readonly)



67
68
69
# File 'lib/spotted/client.rb', line 67

def audio_analysis
  @audio_analysis
end

#audio_featuresSpotted::Resources::AudioFeatures (readonly)



64
65
66
# File 'lib/spotted/client.rb', line 64

def audio_features
  @audio_features
end

#audiobooksSpotted::Resources::Audiobooks (readonly)



40
41
42
# File 'lib/spotted/client.rb', line 40

def audiobooks
  @audiobooks
end

#browseSpotted::Resources::Browse (readonly)



61
62
63
# File 'lib/spotted/client.rb', line 61

def browse
  @browse
end

#chaptersSpotted::Resources::Chapters (readonly)



46
47
48
# File 'lib/spotted/client.rb', line 46

def chapters
  @chapters
end

#client_idString? (readonly)

Returns:

  • (String, nil)


19
20
21
# File 'lib/spotted/client.rb', line 19

def client_id
  @client_id
end

#client_secretString? (readonly)

Returns:

  • (String, nil)


22
23
24
# File 'lib/spotted/client.rb', line 22

def client_secret
  @client_secret
end

#episodesSpotted::Resources::Episodes (readonly)



37
38
39
# File 'lib/spotted/client.rb', line 37

def episodes
  @episodes
end

#marketsSpotted::Resources::Markets (readonly)



73
74
75
# File 'lib/spotted/client.rb', line 73

def markets
  @markets
end

#meSpotted::Resources::Me (readonly)



43
44
45
# File 'lib/spotted/client.rb', line 43

def me
  @me
end

#oauth_2_0_stateSpotted::Internal::OAuth2ClientCredentials (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



101
102
103
# File 'lib/spotted/client.rb', line 101

def oauth_2_0_state
  @oauth_2_0_state
end

#playlistsSpotted::Resources::Playlists (readonly)



55
56
57
# File 'lib/spotted/client.rb', line 55

def playlists
  @playlists
end

#recommendationsSpotted::Resources::Recommendations (readonly)



70
71
72
# File 'lib/spotted/client.rb', line 70

def recommendations
  @recommendations
end

#searchSpotted::Resources::Search (readonly)



52
53
54
# File 'lib/spotted/client.rb', line 52

def search
  @search
end

#showsSpotted::Resources::Shows (readonly)



34
35
36
# File 'lib/spotted/client.rb', line 34

def shows
  @shows
end

#tracksSpotted::Resources::Tracks (readonly)



49
50
51
# File 'lib/spotted/client.rb', line 49

def tracks
  @tracks
end

#usersSpotted::Resources::Users (readonly)



58
59
60
# File 'lib/spotted/client.rb', line 58

def users
  @users
end

Instance Method Details

#authorization_url(redirect_uri:, scope: nil, state: nil, show_dialog: false) ⇒ String

Generates the Spotify authorization URL for OAuth2 authorization code flow.

Examples:

Basic usage

client = Spotted::Client.new(client_id: "...", client_secret: "...")
url = client.authorization_url(redirect_uri: "http://localhost:3000/callback")

With scopes and state

url = client.authorization_url(
  redirect_uri: "http://localhost:3000/callback",
  scope: ["user-read-private", "user-read-email"],
  state: "random_state_string"
)

Parameters:

  • redirect_uri (String)

    The URI to redirect to after authorization

  • scope (String, Array<String>, nil) (defaults to: nil)

    Space-delimited string or array of authorization scopes

  • state (String, nil) (defaults to: nil)

    Optional state parameter for CSRF protection

  • show_dialog (Boolean) (defaults to: false)

    Whether to force the user to approve the app again

Returns:

  • (String)

    The authorization URL to redirect the user to



209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/spotted/client.rb', line 209

def authorization_url(redirect_uri:, scope: nil, state: nil, show_dialog: false)
  params = {
    client_id: @client_id,
    response_type: "code",
    redirect_uri: redirect_uri
  }

  params[:scope] = scope.is_a?(Array) ? scope.join(" ") : scope if scope
  params[:state] = state if state
  params[:show_dialog] = "true" if show_dialog

  query_string = URI.encode_www_form(params)
  "https://accounts.spotify.com/authorize?#{query_string}"
end

#exchange_authorization_code(code:, redirect_uri:) ⇒ Object

Exchanges an authorization code for an access token.

Parameters:

  • code (String)

    The authorization code to exchange

  • redirect_uri (String)

    The redirect URI used to obtain the authorization code

Returns:

  • (Object)

    The access token and refresh token



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/spotted/client.rb', line 230

def exchange_authorization_code(code:, redirect_uri:)
  if @client_id.nil? || @client_secret.nil?
    raise ArgumentError, "Both client_id and client_secret must be set to exchange an authorization code."
  end
  body = URI.encode_www_form(
    grant_type: "authorization_code",
    code: code,
    redirect_uri: redirect_uri
  )
  client = Spotted::Client.new(
    client_id: @client_id,
    client_secret: @client_secret,
    base_url: "https://accounts.spotify.com"
  )
  client.request(
    method: :post,
    headers: {
      "Content-Type" => "application/x-www-form-urlencoded",
      "Authorization" => "Basic #{Base64.strict_encode64("#{@client_id}:#{@client_secret}")}"
    },
    path: "/api/token",
    body: body
  )
end

#refresh_access_token(refresh_token:) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/spotted/client.rb', line 255

def refresh_access_token(refresh_token:)
  if @client_id.nil? || @client_secret.nil?
    raise ArgumentError, "Both client_id and client_secret must be set to refresh an access token."
  end
  body = URI.encode_www_form(
    grant_type: "refresh_token",
    refresh_token: refresh_token
  )
  client = Spotted::Client.new(client_id: @client_id, client_secret: @client_secret, base_url: "https://accounts.spotify.com")
  client.request(
    method: :post,
    headers: {
      "Content-Type" => "application/x-www-form-urlencoded",
      "Authorization" => "Basic #{Base64.strict_encode64("#{@client_id}:#{@client_secret}")}"
    },
    path: "/api/token",
    body: body
  )
end