Search code examples
swiftspotify

Swift Spotify API Error code 405 add to library?


I am trying to add Track to a user's library using Spotify API but I am getting a 400 response status. I've tried this request with Alamofire and start getting postCount error because of Spotify header token ..

here is the Part of Code :

func spotify_addToLibrary()
{

    self.spotify_verifySession(completion:{ success , auth in

        if !success
        {
            return
        }

        let postString                  = "ids=[\"\(self.trackid)\"]"
        let url: NSURL                  = NSURL(string: "https://api.spotify.com/v1/me/tracks")!
        var request                     = URLRequest(url: url as URL)
            request.cachePolicy         = .useProtocolCachePolicy
            request.timeoutInterval     = 8000
            request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue("Bearer \(auth.session.accessToken!)", forHTTPHeaderField: "Authorization")
            request.httpMethod = "post"
            request.httpBody   = postString.data(using: .utf8)

         URLSession.shared.dataTask(with: request) {data, response, err in

                    if err == nil
                    {
                        print("Add to Library success \(String(describing: response))")

                    }else
                    {
                        print("Add to Library Error \(String(describing: err))")
                    }

                }.resume()
    })
}

And this is the Log:

Add to Library success Optional(<NSHTTPURLResponse: 0x174c25d80> { URL: https://api.spotify.com/v1/me/tracks } { status code: 405, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "private, max-age=0";
    "Content-Length" = 0;
    Date = "Fri, 08 Sep 2017 14:29:24 GMT";
    Server = nginx;
    "access-control-allow-credentials" = true;
    "access-control-allow-headers" = "Accept, Authorization, Origin, Content-Type";
    "access-control-allow-methods" = "GET, POST, OPTIONS, PUT, DELETE";
    "access-control-max-age" = 604800;
    allow = "DELETE, GET, HEAD, OPTIONS, PUT";
} })

What did I miss there?


Solution

  • HTTP error 405 means you are trying to use a method in your REST request that is not valid on the specific endpoint.

    If you check the documentation of the Spotify Web API, it clearly states that the valid HTTP verbs to be used for the /me/tracks endpoint are: DELETE, GET and PUT. POST is not allowed, hence the error.

    Just change request.httpMethod = "post" to request.httpMethod = "put" and the error should be solved.

    Some generic advice: don't use Foundation types when native Swift equivalents exist (NSURL instead of URL) and conform to the Swift naming convention, which is lower-camelCase for variable and function names (spotify_addToLibrary should be spotifyAddToLibrary). A timeout interval of 8000 seconds also seems to be quite unrealistic.