Call upon a REST API online using C#


This short tutorial will cover one of many ways to call a REST API online to do various data based operations such as GET or POST requests. Working with REST services is essential, and learning to do simple requests to retrieve all kinds of data online can give your apps and websites more richness.

For this post, we are going to do a GET request, using headers, and then from the result, save a json file, and then parse that json file into a data object/structure. Since we’re also working with json files, the best tool for doing json operations is Newtonsoft’s Json.NET.

Remember that this is just one way of doing it, there are much more ways of doing REST API calls in C#. And it also depends on the API you are trying to call, so if it doesn’t work the first time, you have to configure the request until the response is ok.

Lastly, to parse a json file to a serializable object, you can use: http://json2csharp.com/. Simply paste a sample json and it will create a C# class for you that matches the json structure.

 

//for doing web based operations, should you do this in a method, 
//you must have the async keyword before return type
static async void getRequest() 
{
            string url = "https://onlinerestapi.com/api/weather";
            string api_key = "456dsadA6DF52s65wqq2z13as";
            string header = "Sample-Key";
            

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            //configure the request
            //we want a json response
            request.ContentType = "application/json";
            //add the headers
            request.Headers.Add(header, api_key);
            //set the Accept property to "Accept"
            request.Accept = "Accept";
            //this is a GET request
            request.Method = "GET";

            //send the request
            WebResponse response = await request.GetResponseAsync();

            // Get a stream representation of the HTTP web response:
            using (Stream stream = response.GetResponseStream())
            {
                //write out the response json to disk
                using (StreamReader sr = new StreamReader(stream))
                {
                    var jsonResponse = sr.ReadToEnd();
                    StreamWriter sw = new StreamWriter("sample_data.json");
                    sw.Write(jsonResponse);
                    sw.Close();
                    sr.Close();
                }
            }

            //parse the json file into a league standings object
            Weather weatherObject = JsonConvert.DeserializeObject<Weather>(File.ReadAllText("sample_data.json"));
            return;
}

I hope this short tutorial helped you in any way. If you liked it, please rate, comment, give feedback, etc. It helps me improve my tutorials and I learn better myself.

Another REST API C# tutorial that can help as well: https://mjawaid.wordpress.com/2010/06/30/rest-web-services-calls-with-csharp/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s