Hey everyone! I’m having trouble getting an access token for the Spotify API in C#. I’ve set up my app and have the client ID and secret, but I’m getting a 400 Bad Request error. Here’s what I’ve tried:
async Task<string> FetchSpotifyToken()
{
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));
var content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Basic {auth}");
var response = await client.PostAsync("https://accounts.spotify.com/api/token", content);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var token = JsonConvert.DeserializeObject<SpotifyToken>(result);
return token.AccessToken;
}
throw new Exception($"Failed to get token: {response.StatusCode}");
}
Am I missing something obvious? Any help would be awesome!
I’ve encountered this issue before. One thing to check is the content type header. Try explicitly setting it like this:
client.DefaultRequestHeaders.Add(“Content-Type”, “application/x-www-form-urlencoded”);
Also, ensure you’re using HTTPS for the API endpoint. Sometimes, a misconfigured URL can cause unexpected errors.
If that doesn’t work, consider using Fiddler or Postman to inspect the exact request being sent. This can help identify any discrepancies between what you’re sending and what Spotify expects.
Lastly, double-check that your Spotify Developer account has the necessary permissions enabled for the API endpoints you’re trying to access. Sometimes, the issue lies in account configuration rather than code.
hey markseeker91, i had that issue too. check ur app settings in spotify dashboard - make sure redirect URI is set even for client credentials flow. also, try using var instead of explicit types, it can help catch subtle errors. good luck with ur project!
I ran into a similar issue when I first started working with Spotify’s API. One thing that helped me was double-checking the client ID and secret. Make sure they’re exactly as shown in your Spotify Developer Dashboard, as even a single character off can cause a 400 error.
Another tip: try using a library like SpotifyAPI-NET. It handles a lot of the authentication hassle for you. I switched to it after struggling with raw HTTP requests, and it made my life much easier.
If you’re set on using HttpClient, you might want to add some logging to see exactly what’s being sent in the request. Sometimes the issue is in how the request is formatted rather than the credentials themselves.
Lastly, ensure your app in the Spotify Developer Dashboard has the correct redirect URI set up, even if you’re not using it for this particular flow. Spotify can be picky about that.