It’s really easy to call REST based web services from C#.Net. Let’s see how to do it. We’ll be calling Yahoo Web Services as an example here.
Make REST Calls With C#
The .NET Framework provides classes for performing HTTP requests. This HOWTO describes how to perform both GET and POST requests.
Overview
The System.Net namespace contains the HttpWebRequest and HttpWebResponse classes which fetch data from web servers and HTTP based web services. Often you will also want to add a reference to System.Web which will give you access to the HttpUtility class that provides methods to HTML and URL encode and decode text strings.
Yahoo! Web Services return XML data. While some web services can also return the data in other formats, such as JSON and Serialized PHP, it is easiest to utilize XML since the .NET Framework has extensive support for reading and manipulating data in this format.
Simple GET Requests
The following example retrieves a web page and prints out the source.
C# GET SAMPLE 1
Simple POST Requests Some APIs require you to make POST requests. To accomplish this we change the request method and content type and then write the data into a stream that is sent with the request. C# POST SAMPLE 1
// We use the HttpUtility class from the System.Web namespace using System.Web; Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction"); // Create the web request HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; // Set type to POST request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; // Create the data we want to send string appId = "YahooDemo"; string context = "Italian sculptors and painters of the renaissance" + "favored the Virgin Mary for inspiration"; string query = "madonna"; StringBuilder data = new StringBuilder(); data.Append("appid=" + HttpUtility.UrlEncode(appId)); data.Append("&context=" + HttpUtility.UrlEncode(context)); data.Append("&query=" + HttpUtility.UrlEncode(query)); // Create a byte array of the data we want to send byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); // Set the content length in the request headers request.ContentLength = byteData.Length; // Write data using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output Console.WriteLine(reader.ReadToEnd()); }
HTTP Authenticated requests
The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance ofNetworkCredentials to the request.
C# HTTP AUTHENTICATION
// Create the web request HttpWebRequest request = WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest; // Add authentication to request request.Credentials = new NetworkCredential("username", "password"); // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output Console.WriteLine(reader.ReadToEnd()); }
Error Handling
Yahoo! offers many REST based web services but they don’t all use the same error handling. Some web services return status code 200 (OK) and a detailed error message in the returned XML data while others return a standard HTTP status code to indicate an error. Please read the documentation for the web services you are using to see what type of error response you should expect. Remember that HTTP Authentication is different from the Yahoo!Browser-Based Authentication.
Calling HttpRequest.GetResponse() will raise an exception if the server does not return the status code 200 (OK), the request times out or there is a network error. Redirects are, however, handled automatically.
Here is a more full featured sample method that prints the contents of a web page and has basic error handling for HTTP error codes.
C# GET SAMPLE 2
public static void PrintSource(Uri address) { HttpWebRequest request; HttpWebResponse response = null; StreamReader reader; StringBuilder sbSource; if (address == null) { throw new ArgumentNullException("address"); } try { // Create and initialize the web request request = WebRequest.Create(address) as HttpWebRequest; request.UserAgent = ".NET Sample"; request.KeepAlive = false; // Set timeout to 15 seconds request.Timeout = 15 * 1000; // Get response response = request.GetResponse() as HttpWebResponse; if (request.HaveResponse == true && response != null) { // Get the response stream reader = new StreamReader(response.GetResponseStream()); // Read it into a StringBuilder sbSource = new StringBuilder(reader.ReadToEnd()); // Console application output Console.WriteLine(sbSource.ToString()); } } catch (WebException wex) { // This exception will be raised if the server didn't return 200 - OK // Try to retrieve more information about the network error if (wex.Response != null) { using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response) { Console.WriteLine( "The server returned '{0}' with the status code {1} ({2:d}).", errorResponse.StatusDescription, errorResponse.StatusCode, errorResponse.StatusCode); } } } finally { if (response != null) { response.Close(); } } }
Further reading
Related information on the web.
[…] Another REST API C# tutorial that can help as well: https://mjawaid.wordpress.com/2010/06/30/rest-web-services-calls-with-csharp/ […]
Good ¡V I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, site theme . a tones way for your client to communicate. Excellent task..