C
C#4mo ago
bLanco

C# Spotify Api

Yo guys i need help i think, I even don't know what's the problem. My code was working 2 hours ago and now it's not
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace SpotifyApiExample
{
class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main(string[] args)
{
try
{
using (HttpClient client = new HttpClient())
{
var clientId = "";
var clientSecret = ";
var authToken = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));

var accessToken = "";
// Sanatçı bilgilerini al
string artistInfo = await GetArtistInfoAsync(clientId, accessToken);
Console.WriteLine("Artist Info: " + artistInfo);

// Yeni çıkan albümleri al
string json = await GetSpotifyDataAsync(accessToken);

// Albümleri ayıkla
string[] albumInfo = ParseAlbums(json);
foreach (string info in albumInfo)
{
Console.WriteLine(info);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}

private static async Task<string> GetArtistInfoAsync(string artistId, string accessToken)
{
string artistUrl = $"https://api.spotify.com/v1/artists/{artistId}";

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

HttpResponseMessage response = await client.GetAsync(artistUrl);
response.EnsureSuccessStatusCode();

string jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse;
}

private static async Task<string> GetSpotifyDataAsync(string accessToken)
{
// Spotify API URL ve access token'ı buraya ekle
string apiUrl = "https://api.spotify.com/v1/browse/new-releases";

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

HttpResponseMessage response = await client.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();
return json;
}

private static string[] ParseAlbums(string json)
{
JObject data = JObject.Parse(json);
JArray albumsArray = (JArray)data["albums"]["items"];
string[] albums = new string[albumsArray.Count];

for (int i = 0; i < albumsArray.Count; i++)
{
JObject album = (JObject)albumsArray[i];
string name = album["name"].ToString();
string releaseDate = album["release_date"].ToString();
string artistName = album["artists"][0]["name"].ToString();
string albumUrl = album["external_urls"]["spotify"].ToString();
string albumImageUrl = album["images"][0]["url"].ToString();

albums[i] = $"Album Name: {name}, Release Date: {releaseDate}, Artist: {artistName}, Album URL: {albumUrl}, Album Image URL: {albumImageUrl}";
}

return albums;
}
}
}
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace SpotifyApiExample
{
class Program
{
private static readonly HttpClient client = new HttpClient();

static async Task Main(string[] args)
{
try
{
using (HttpClient client = new HttpClient())
{
var clientId = "";
var clientSecret = ";
var authToken = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"));

var accessToken = "";
// Sanatçı bilgilerini al
string artistInfo = await GetArtistInfoAsync(clientId, accessToken);
Console.WriteLine("Artist Info: " + artistInfo);

// Yeni çıkan albümleri al
string json = await GetSpotifyDataAsync(accessToken);

// Albümleri ayıkla
string[] albumInfo = ParseAlbums(json);
foreach (string info in albumInfo)
{
Console.WriteLine(info);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}

private static async Task<string> GetArtistInfoAsync(string artistId, string accessToken)
{
string artistUrl = $"https://api.spotify.com/v1/artists/{artistId}";

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

HttpResponseMessage response = await client.GetAsync(artistUrl);
response.EnsureSuccessStatusCode();

string jsonResponse = await response.Content.ReadAsStringAsync();
return jsonResponse;
}

private static async Task<string> GetSpotifyDataAsync(string accessToken)
{
// Spotify API URL ve access token'ı buraya ekle
string apiUrl = "https://api.spotify.com/v1/browse/new-releases";

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

HttpResponseMessage response = await client.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();
return json;
}

private static string[] ParseAlbums(string json)
{
JObject data = JObject.Parse(json);
JArray albumsArray = (JArray)data["albums"]["items"];
string[] albums = new string[albumsArray.Count];

for (int i = 0; i < albumsArray.Count; i++)
{
JObject album = (JObject)albumsArray[i];
string name = album["name"].ToString();
string releaseDate = album["release_date"].ToString();
string artistName = album["artists"][0]["name"].ToString();
string albumUrl = album["external_urls"]["spotify"].ToString();
string albumImageUrl = album["images"][0]["url"].ToString();

albums[i] = $"Album Name: {name}, Release Date: {releaseDate}, Artist: {artistName}, Album URL: {albumUrl}, Album Image URL: {albumImageUrl}";
}

return albums;
}
}
}
And the error is
Error: Response status code does not indicate success: 400 (Bad Request).
Error: Response status code does not indicate success: 400 (Bad Request).
. Because I use C# i couldn't find anything about it on the internet. Can anyone help me about it ?
7 Replies
Buddy
Buddy4mo ago
Please parse JSON into types as you should and try adding a user-agent to your request, I would also suggest reading docs for any missing information
bLanco
bLancoOP4mo ago
actually it's working now and im not kidding i sent the code to chat gpt and told her to convert into python python code worked but C# didnt xd
Buddy
Buddy4mo ago
Don't trust ChatGPT, it should always require a human to validate the code. And please, do as I mentioned.
bLanco
bLancoOP4mo ago
Okay I'll do it, thanks!
Buddy
Buddy4mo ago
Also, remove Newtonsoft dependency. It is pretty much pointless over System.Text.Json
bLanco
bLancoOP4mo ago
I removed it Thanks for the advices ❤️
Buddy
Buddy4mo ago
Anytime.
Want results from more Discord servers?
Add your server