Search code examples
c#.netwpfwinforms

How do I call a web site API in my application


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

The thing is I've been looking over at GitHub and Codeproject but I couldn't 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?


Solution

  • 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; }
        // ...
    }