Reputation:
Could someone tell me if this is a good way to retrieve data from an API? I'm new to this, and wonder if someone could recommend me some kind of setup and structure, and if this could be done in a more correct way?
string baseUrl = "https://api.data.com/getITems/
//Create a new instance of HttpClient
using (HttpClient client = new HttpClient())
{
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
using (HttpResponseMessage result = await client.GetAsync(baseUrl))
using (HttpContent content = result.Content)
{
result.EnsureSuccessStatusCode();
string data = await content.ReadAsStringAsync();
var test1 = JsonConvert.DeserializeObject<Results>(data);
foreach (var item in test1.results)
{
foreach (var item1 in item.result)
{
Console.WriteLine("Result: {0}", item1.Symbol);
}
}
}
Upvotes: 0
Views: 135
Reputation: 23935
Deciding if your implementation is a good way, is out of my scope, since I do not know your requirements and genereally you can always extract some functionality into some other class, while juggeling the effort you put in against the expected value you get out of it.
That being said, I'll just go into the one thing that springs to my eye and that is your usage of HttpClient
itself.
If this is a long lived application and you keep calling that part of your code, you will always new-up an new instance of HttpClient
and then dispose it. This will kill the connections to your endpoint immediately, but leave the ports in TIME_WAIT
state.
Do this is a couple of hundred or thousand times and you will most likely run into SocketException
, because your machine has run out of available sockets to use.
From the documentation:
HttpClient is intended to be instantiated once and reused throughout the life of an application.
If all HttpClients, share the same headers and base address, you can re-use a single instance of that client throughout your application. If you have different headers, create a new static client. In both scenarios you want to use them as a singleton throughout your application.
Some further reading:
Upvotes: 0
Reputation: 52952
Your code looks fine. You could use a nuget package to simplify some of the operations or turn it into a helper class. The only thing you should do differently is not create a new HttpClient
every time, this is against the practices. You should only create it once and use it lots of times.
Upvotes: 1