1
votes
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

/**
 * SpotifyService works querying the Spotify Web API
 * https://developer.spotify.com/web-api/
 */

@Injectable()
export class SpotifyService {
  static BASE_URL = 'https://api.spotify.com/v1';

  constructor(private http: Http) {
  }

  query(URL: string, params?: Array<string>): Observable<any[]> {
    let queryURL = `${SpotifyService.BASE_URL}${URL}`;
    if (params) {
      queryURL = `${queryURL}?${params.join('&')}`;
    }

    return this.http.request(queryURL).map((res: any) => res.json());
  }

  search(query: string, type: string): Observable<any[]> {
    return this.query(`/search`, [
      `q=${query}`,
      `type=${type}`
    ]);
  }

  searchTrack(query: string): Observable<any[]> {
    return this.search(query, 'track');
  }

  getTrack(id: string): Observable<any[]> {
    return this.query(`/tracks/${id}`);
  }

  getArtist(id: string): Observable<any[]> {
    return this.query(`/artists/${id}`);
  }

  getAlbum(id: string): Observable<any[]> {
    return this.query(`/albums/${id}`);
  }
}

export const SPOTIFY_PROVIDERS: Array<any> = [
  { provide: SpotifyService, useClass: SpotifyService }
];

That is my spotify.service.ts file. The console is giving me this error:

Failed to load resource: the server responded with a status of 401 (Unauthorized) core.es5.js:1084 ERROR Responseheaders: Headers {_headers: Map(1), _normalizedNames: Map(1)}ok: falsestatus: 401statusText: "Unauthorized"type: 2url: "https://api.spotify.com/v1/search?q=eminem&type=track"_body: "{↵ "error": {↵ "status": 401,↵ "message": "No token provided"↵ }↵}"proto: Bodyconstructor: ƒ Response(responseOptions)toString: ƒ ()proto: Object defaultErrorLogger @ core.es5.js:1084

Am I to assume this is because I don't have an API Key? This is the example code provided straight from the book. If I need a key how would I implement it?

2
I see that as of may 29th 2017 they've required an api key for every request. This book was published in 2017 so it's a very recent change. Do I just add my key at the end of the BASE_URL? - Zak Nichols

2 Answers

1
votes

From the Spotify documentation

On 29th May 2017 the /search /tracks /albums /artists and /users (and related) endpoints will start requiring an access token...

To get a token, sign-up in the spotify dev site here and create an app. Hope this helps.

0
votes

As described by @brijmcq, Spotify has enabled access token for almost all api, here is a simple tutorial to get a temporary valid access_token.

ATTENTION: this is only for running examples in ngbook when learning Angular, to obtain access_token in production environment, please refer to Spotify official authorization guide: https://developer.spotify.com/documentation/general/guides/authorization-guide/ .

  1. open https://developer.spotify.com/dashboard/ in your browser, sign up a new Spotify account or sign in with your existed account.

  2. after logging in, click the CREATE A CLIENT ID button at https://developer.spotify.com/dashboard/applications

  3. click the app you just created.

3.5 you can find you own CLIENT_ID at top-left, which will be needed in the next step.

  1. click EDIT SETTINGS button (left of the LOGOUT button)

  2. fill Redirect URIs with some valid url, like 'http://www.google.com' and click ADD

  3. don't forget to SAVE

  4. open 'https://accounts.spotify.com/en/authorize?client_id=CLIENT_ID&response_type=token&redirect_uri=http://www.google.com' in your browser

CLIENT_ID is mentioned at 3.5.

redirect_uri should match the Redirect URIs you saved before.

  1. login with any Spotify account, click the AGREE button, browser will redirect the url you saved before with access_token and token expire time, like 'https://www.google.com/#access_token=CyOWA36wg&token_type=Bearer&expires_in=3600'

access_token here is what you want to get.

  1. you can visit Spotify api like 'curl https://api.spotify.com/v1/albums/2Ti79nwTsont5ZHfdxIzAm?access_token=BQAyClDejfK' now.

  2. modify your SpotifyService in ngbook music-search example, add 'access_token' param to each Spotify query.

  3. if you meed 401 after the access_token expired, you need to repeat step 8 again to get new access_token, for which this tutorial is not recommended in production environment.

(you can make a copy of your own url mentioned in step 8 for re-auth)