0

I just decided to start learning about API's and how to append it to a label i.e

The thing is I've been looking over at GitHub & Codeproject but I couldnt find any examples or opensource projects that demonstrates what I want to learn.

I want to append the "id" from the API to a label.

https://api.coinmarketcap.com/v1/ticker/ethereum/
https://coinmarketcap.com/api/

But I have no idea how to initialize this.. Would I call I HttpWebRequest?

John V Dole
  • 321
  • 1
  • 3
  • 11

2 Answers2

3

Look up HttpClient. In the System.Net.Http interface. Here is some sample code but your exact implementation depends of course on the api you are calling:

string completeUrl = String.Format("{0}{1}", urlbase,apiext); 

//apiext in this case is the call to the api method appended to the url

HttpClient http = new HttpClient();
http.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthHeader);  // If you need authorization
http.DefaultRequestHeaders.Add("User-Agent","(myemail.com)");
var response = await http.GetAsync(completeUrl);
return await response.Content.ReadAsStringAsync();
John V Dole
  • 321
  • 1
  • 3
  • 11
Haim Katz
  • 455
  • 3
  • 15
3

Use Newtonsoft.Json to deserialize your Json results into a C# object. Call the API Uri and get the content and use JsonConvert to deserialize to an object.

First, import Json library (Make sure you install from Package Manager)

using Newtonsoft.Json;

Then, use the following code to retrieve the id of the ticker.

const string uri = @"https://api.coinmarketcap.com/v1/ticker/ethereum/";
var client = new WebClient();
var content = client.DownloadString(uri);

var results = JsonConvert.DeserializeObject<List<CoinApi>>(content);

label1.Text = results[0].Id; // ethereum

You need to specify the model class to deserialize.

public class CoinApi
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Symbol { get; set; }
    // ...
}
abdul
  • 1,562
  • 1
  • 17
  • 22