Reputation: 30471
How can I receive an access_token through Client Credentials Flow to Spotify by using Alamofire?
Here is my code so far:
// Spotify API
func callAlamo(url: String) {
let parameters = ["client_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"client_secret" : "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"grant_type" : "client_credentials"]
let headers = ["Authorization" : "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] // <- xxx is the client_id
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters, headers: headers).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
}
Here is a section of my print log:
SUCCESS
Optional({ error = "invalid_client"; })
What is wrong with this code? Am I sending the wrong parameters or headers? Did I forget something?
Note: The client_id
and client_secret
are correct
- If there is anything unclear, please message me -
Upvotes: 0
Views: 1211
Reputation: 30471
After multiple days and 2 questions later, I figured it out myself. It was an extremely simple fix, which is frustrating.
All I did was delete the headers
parameter in the request.
Another option is that you can set headers
to nil
.
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: parameters).responseJSON(completionHandler: {
response in
print(response.result)
print(response.result.value)
})
Upvotes: 3
Reputation: 554
Well I don't know how this is working. In theory, the correct execution is: - Make a POST request to url: https://accounts.spotify.com/api/token
set as headers:
"Content-Type": "application/x-www-form-urlencoded"
"Authorization": "Basic xxxxx"
Where xxxxx is the base64 encoded string of client_id:client_secret (so client_id string and client_secret separated by :)
This will give you the correct response
eg.
{
"access_token": "BQCJeyp3ocQZzSksvNn3IXuvY0NsYI26YMF400jp-7Dd8zGz6ecXyywwmSdy4jrPWwLZA_6l4e59lu8dYfg",
"token_type": "Bearer",
"expires_in": 3600,
"scope": ""
}
Upvotes: 0