User Story

As a developer
I want to call a RESTful API from my c# application
So that I can consume and use the resources it provides

Overview

I’m guessing if you’re reading this that you probably have some idea what a RESTful API is, so I won’t delve too deeply into the why’s and wherefores, however some key points to note:

  • Centers around the concept of “resources” that you consume, create, update and destroy
  • Accessed via a “base” URI
  • Can return data in any format, (XML, atom etc.), but most usually JSON
  • Usually accessed over HTTP with the usual string of verbs: GET, POST PUT etc.
  • Platform agnostic
  • Lightweight (and usually fast!)

Ingredients

For this tutorial you will need the following, (or something similar):

  • Windows PC (I’m running Windows 10 on a Surface Pro 3)
  • Visual Studio Community Edition
  • Internet Access (if you want to use the sample REST service – if you’re reading this then I guess this is already sorted!)
  • 30-40 minutes of your time

Ok – Let’s get started!

Test the REST

Before we launch into writing code to access your REST service, you should simply be able to access it directly from your browser and observe the data returned, (in essence that’s really all this tutorial is – making a http request from c# code!).

Now as I’m a nice guy I’ve placed an example, (and very simple!), RESTful service on the interweb for you to play with, which coincidentally is the REST API I’m using for this tutorial.

Note: The API is read only, you’ll only be able to list all items in the db, or retrieve a particular item, (adding, updating and removing actions have all be disabled).

The API Can be found here:

http://dry-cliffs-19849.herokuapp.com/

This should take you to the “home-page” of the REST API, note that this is not really anything to do with the REST API its self, it’s just a nice landing page. (I say nice, the “styling” as you can see is straight out of the early 90s).

You will see a listing of all the REST Actions (and associated HTTP verbs), that will allow you to use our User resource.

HTTP Request URI Action Purpose
GET http://<base uri>/users index List all User resources
GET http://<base uri>/users/n show Get the user resource with an id of n
POST http://<base uri>/users create Create a new User resource
PATCH http://<base uri>/users/n update Update User resource with an id of n
DELETE http://<base uri>/users/n destroy Delete User resource with an id of n

The first 2 actions are activated and by clicking on the associated links you will be presented with the JSON response. For the first request, (listing all User resources), you should see something similar in your browser:

SNAGHTML250897

What you are seeing is a list of JSON objects representing a list of users in the database. Again not wanting to “cop out”, but I won’t go into too much detail about JSON, (I’m assuming if you’re reading this you have a basic understanding at least), however it’s really not that difficult…

Using an excellent tool like “jsoneditoronline.org”, you can cut and paste the JSON our test RESTService is returning to get a better idea of its anatomy, this will be useful for later:

SNAGHTML291e3e

As you see we were returned an array, (the ‘[‘ opening bracket denotes this), of user objects. Each object starts with a ‘{‘ and ends with a ‘}’.  Within the object we then have a list of key / value pairs, e.g. :

Key Example Value
id 3
name Adam Smith
email adam@email.com
nationality Scottish

It’s fairly easy now to understand the structure, and while it can get somewhat more complex in other instances, (e.g. when the value is another array of key value pairs), it’s essentially just the same design pattern. For the purposes of this tutorial it should suffice.

With all that done, (i.e. you’ve “tested” that you can access the REST service via your browser), it’s now time to start designing our solution.

User Interface Design

This section title is probably a little grandiose for what we are doing here, but I like to follow this pattern for even the simplest apps – that being mocking up the simple interface. I tend to think more visually so it’s only when I do this that I actually start to think how things will work…

The Mock Ups

I’ve used an excellent tool called “Balsamiq” to create the following mocks that depict the client before and after  making a call to the rest service. It is this interface we’ll want to construct in Visual Studio.

mocks

The eventuation of this amazing design will look something like:

actualclient

Sequence Diagram

Using some fairly rudimentary UML, the sequencing for the application looks as follows:

blog-11 sequence diagram

Probably the only thing of note is that our RESTClient, (i.e. our c# app), makes a synchronous call to our REST API… I.e. it waits for the response payload. This is probably not how you’d want to architect this in the real world, (you’d make a asynchronous request to allow for any network latency etc..). For the purposes of the tutorial it will suffice, and making an asynchronous request can be a bit of extra credit homework!

Again this is a very simple request response model, and possibly doesn’t require the need for a UML sequence diagram, however I think it’s just good practice, (especially when you are eventually faced with more complex sequencing!).

RESTClient Class Design

Ok now we’re getting down to it!

For the purposes of this tutorial we’re going to write a custom c# class that encapsulates functionality from multiple standard .net libraries. The class we’ll build is as follows:

Blog-11 RESTCLient Class

First we use an “enumeration” to map to our list of possible HTTP Verbs, you’ll see here we’ve only mapped GET & POST, and in fact we’ll actually only be using GET in this tutorial.

The actual class its self is pretty simple, containing 2 attributes:

  • endPoint (this is the URI we’re making the request to)
  • httpMethod (as describe above this just represents our HTTP Verb)

The class then has a very simple constructor and 1 additional method:

  • makeRequest (yes you’ve guessed it this initiates the request to our REST Api!).

Coding

Ok we’re finally here! It’s time to code.

Start Visual studio and create a new c# Windows Application – call it whatever you like.

Ok now we have a nice empty Windows form, you’ll want to place the following UI elements onto it:

  • TextBox to hold the Request URI (I called mine: txtRequestURI)
  • TextBox to hold the Response Payload (I called mine: txtResponse)
    • Set Multiline Property to true
    • Set ScrollBars Property to vertical
  • Button (I called mine: cmdGo)
  • Label
    • Set name Property to Request URI:
  • Label
    • Set name Property to Response:

With the form design complete, we can now move onto the creation of our RESTClient Class.

In Visual Studio right click your project, then select: Add -> Class..

snaghtml9c71c

When the Add New Item window appears, select Class (1), give it a name (2) – I called mine RESTClient.cs then click add (3):

untitled-picture

Your solution hierarchy should look somewhat like the following:

2016-09-30_12-37-24

Now add the following code to your RESTClient class, (or whatever you called it):

UPDATED: Used a Try / Catch / Finally Block instead to Using so we capture Non-successful responses.

using System;
using System.IO;            //Needs to be added
using System.Net;           //Needs to be added
using System.Text;          //Needs to be added

namespace restClient
{
    public enum httpVerb
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    class RESTClient
    {
        public string endPoint { get; set; }
        public httpVerb httpMethod { get; set; }   

        //Default Constructor
        public RESTClient()
        {
            endPoint = "";
            httpMethod = httpVerb.GET;
            
        }

        public string makeRequest()
        {
            string strResponseValue = string.Empty;

            var request = (HttpWebRequest)WebRequest.Create(endPoint);

            request.Method = httpMethod.ToString();
            
            HttpWebResponse response = null;

            try 
            {
                response = (HttpWebResponse)request.GetResponse();
                

                //Proecess the resppnse stream... (could be JSON, XML or HTML etc..._

                using (Stream responseStream = response.GetResponseStream())
                {
                    if(responseStream != null)
                    {
                        using (StreamReader reader = new StreamReader(responseStream))
                        {
                            strResponseValue = reader.ReadToEnd();
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                //We catch non Http 200 responses here.
                strResponseValue = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
            }
            finally
            {
                if(response != null)
                {
                    ((IDisposable)response).Dispose();
                }
            }

            return strResponseValue;
            
        }
    }
}
  •  The constructor basically sets our class attributes, (and as mentioned above we are defaulting to using the GET verb).
  • The makeRequest method creates a "request" object which is basically derived from the standard c# HttpWebRequest object, we then:
    • Make a Request
    • Wait for the response, (synchronous)
    • Check to see if there was an error
    • If no error then we parse the response and return it back to the caller as a string

Debug Output

Visual Studio has a range of tools to help you debug your code, (and they're excellent), but most of the time I like to include my own little function that writes out the contents of variables, or even just where I am in the code. I also use this function to write out things like our return string for the RESTClient class, feel free to use it it's pretty self explanatory:

  • It takes the string you want to write out, and send it to:
    • The Visual Studio Debug window
    • Any other text box you like, (in this example it's called txtResponse)
  • In order that the output "scrolls" to the end of the text box, you need to "ScrollToCaret"
private void debugOutput(string strDebugText)
{
  try
  {
    System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
    txtResponse.Text = txtResponse.Text + strDebugText + Environment.NewLine;
    txtResponse.SelectionStart = txtResponse.TextLength;
    txtResponse.ScrollToCaret();
  }
  catch (Exception ex)
  {
    System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
  }
}

Wire Up the Button Click Event Handler

Finally we just need to create an instance of our RESTClient and make a call to makeRequest. To do this, simply go to the form designer and double click on the "GO!" button, this will create the default click event handler, then place the following code inside:

 private void cmdGo_Click(object sender, EventArgs e)
{
  RESTClient rClient = new RESTClient();

  rClient.endPoint = txtRequestURI.Text;
  debugOutput("RESTClient Object created.");

  string strJSON = string.Empty;

  strJSON = rClient.makeRequest();

  debugOutput(strJSON);

}

All it does is:

  • Instantiate a new instance of our RESTCLient
  • Set the end point to whatever we want to call
  • Prepare our response string
  • Make the call to the end point using our makeRequest function
  • Write the output to our text box, (and the Visual Studio debug window)

Give It A Go!

Run your project (F5) and try both of the following Request URI's:

In both cases you should get a response back from the REST service with HTML and JSON respectively.

2016-09-30_13-06-06

That's It!

Next Time...

Next time we'll tack the JSON response and work with it in c#

Advertisements

2 thoughts on “Consuming a REST API from c#

  1. Thanks a lot for the thorough explanation. Hard to find a resource which fully explains without assuming people know. I now have a working client which I can re-use to better understand REST with some real-world applications I have been planning. You’re awesome!

    Liked by 1 person

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