-1

I am a student working on a project. I am trying to use the Yahoo! Finance API as a source for my data https://www.yahoofinanceapi.com . I can use HttpWebRequests to call the API and get the "OK" code, see the code below on how I did it:

            string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";
                        
            string addSymbol = "%2C";
            string URL = BaseURL;

            foreach (string stock in stocks)
            {
                URL += addSymbol + stock;
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Headers.Add("X-API-KEY", "[My API key]");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Console.WriteLine(response.ContentType);
            Console.WriteLine(response.StatusCode);

response.ContentType gives back "application/json". response.StatusCode gives back "OK".

Since the response is a JSON I tried to parse it into a string using .ToString() but this obviously doesn't work. When I print it, it just says "System.Net.HttpWebResponse" instead of the showing the actual data in the JSON.

After that I tried to deserialize it using newtonsoft

Results result = JsonConvert.DeserializeObject<Results>(request.GetResponse().ToString());

where Results is a class I made where there is a list of stocks, Stock is also a class I made with some variables in it with the same names of variables in the JSON response. I got a JSON response from PostMan when I tested the API, opened the response to see what kind of data it contained.

When I ran my code I got the following error message:

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: S. Path '', line 0, position 0.'

This was as far as I got, I tested a few other methods trying to get this working but this one worked the "best".

My biggest issue at the moment is mapping the response into a c# object. Anything that can help me understand is appreciated :D

Roel Stam
  • 3
  • 4
  • 1
    You have an object representing the response, not the actual response. You need to read the actual response, the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse?view=net-5.0) can be of help in this endeavour. – fredrik Oct 04 '21 at 12:02
  • And obviously you did check what is `request.GetResponse().ToString()` ? – Selvin Oct 04 '21 at 12:05
  • Thanks for the answers, the documentation helped me understand a lot more. – Roel Stam Oct 05 '21 at 08:32

1 Answers1

0

You're trying to serialise the HttpWebResponse object into Results, which means deserialisation won't work.

The data is still wrapped & won't be in the format of the Results object.

The GetResponseStream() method can be used to get the contents of the HTTP response as a stream, which can then be deserialised directly, in this case, using Json.NET.

Replace this section:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine(response.ContentType);
Console.WriteLine(response.StatusCode);

With this:

var serializer = new JsonSerializer();

using (var response = (HttpWebResponse)request.GetResponse())
{
    var encoding = Encoding.GetEncoding(response.CharacterSet);

    using var responseStream = response.GetResponseStream();
    using var reader = new StreamReader(responseStream, encoding);
    using (var jsonTextReader = new JsonTextReader(reader))
    {
        Console.WriteLine(response.ContentType);
        Console.WriteLine(response.StatusCode);

        Results result = serializer.Deserialize<Results>(jsonTextReader);
    }
}

Alternatively, a much better solution if you're using .NET 4.5 <= would be to use HttpClient like below:

private static readonly HttpClient httpClient = new HttpClient();
...

string BaseURL = "https://yfapi.net/v6/finance/quote?symbols=AAPL";

string addSymbol = "%2C";
string URL = BaseURL;

foreach(string stock in stocks) {
  URL += addSymbol + stock;
}

client.DefaultRequestHeaders.Add("X-API-KEY", "[My API key]");

var data = await httpClient.GetStringAsync(address);

Results result = JsonConvert.DeserializeObject<Results>(data);
Ermiya Eskandary
  • 15,323
  • 3
  • 31
  • 44