Gigi Labs

Please follow Gigi Labs for the latest articles.

Friday, August 1, 2014

ASP .NET Web API: A Gentle Introduction

Hello! :)

Last year, we saw how to intercept HTTP requests in Wireshark, and also how to construct them. As you already know, HTTP is used mainly to retrieve content from the Web; however it is capable of much more than that. In this article, we will learn how HTTP can be used to expose an API that will allow clients to interact with back-end services.

Ideally, you should be using Visual Studio 2013 (VS2013) or later. If you're using something different, the steps may vary.

Right, so fire up VS2013, and create a new ASP .NET Web Application. In VS2013, Microsoft united various different kinds of web projects under a single banner, which is what people mean when they refer to something called "One ASP .NET". So there isn't that much choice in terms of project types:


You are given some sort of choice once you click "OK", however:


At this stage there are various web project types you can choose from, and in this case you need to select "Web API". You'll notice that the "MVC" and "Web API" checkboxes are selected and you can't change that. That's because Web API is somewhat based on the ASP .NET MVC technology. Web API is sort of MVC without the View part, so discussing MVC is beyond the scope of this article; however just keep that in mind in case you ever dive into MVC.

Once you click "OK" and create your project, you'll find a whole load of stuff in your Solution Explorer:


This may already seem a little confusing. After all, where should we start from? Let's ignore the code for a moment and press F5 to load up our web application in a browser. This is what we get:


You'll notice there is an "API" link at the top. Clicking it takes you to this awesome help page, where things start to clear up:


It turns out that the Web API project comes with some sample code that you can work with out of the box, and this help page is telling you how to interact with it. If you look at the first entry, which says "GET api/Values", that's something we can point the browser to and see the web application return something:


And similarly, we can use the second form ("GET api/Values/{id}") to retrieve a single item with the specified ID. So if you point your browser to /api/Values/1, you should get the first one:


That's all well and good, but where are these values coming from? Let's go back to the code, and open up the Controllers folder, and then the ValuesController in it:


You can see how there is a method corresponding to each of the items we saw in the help page. The ASP .NET Web API takes the URL you enter in the web browser and tries to route the request to a method on a controller. So if you're sending a GET request to /api/Values/, then it's going to look for a method called Get() in a controller called ValuesController.

Notice how the "Controller" part is omitted from the URL. This is one of many things in Web API that you're expected to sort of take as obvious - Web API uses something called "convention over configuration", which is a cool way of saying "it just works that way, and by some kind of magic you should already know that, and good luck trying to change it". If you've read my article about Mystery Meat Navigation, part of which addresses the Windows 8 "content over chrome" design, you'll notice it's not very different.

And since, at this point, we have digressed into discussing big buzzphrases designed to impress developers, let's learn about yet another buzzword: REST. When we use HTTP to browse the web, we mainly use just the GET and POST request methods. But HTTP supports several other request methods. If we take four of them - POST, GET, PUT and DELETE, these map quite smoothly to the CRUD (Create, Read, Update and Delete) operations we know so well from just about any business application. And using these four request methods, we can build APIs that allow us to work with just about any object. That's what is meant by REST, and is the idea on which the ASP .NET Web API is built. "How I Explained REST to My Wife" is a really good informal explanation of REST, if you want to learn more about it. The irritating thing is that the concept is so simple, yet it's really hard to find a practical explanation on the web on what REST actually means.

To see this in action, let's rename our ValuesController to BooksController so that it's less vague. We'll also need a sort of simple database to store our records, so let's declare a static list in our BooksController class:

        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"

        };

Now we can change our Get() methods to return items from our collection. I'm going to leave out error checking altogether to keep this really simple:

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];

        }

We can test this in the browser to see that it works fine:


Great! We can now take care of our Create (POST), Update (PUT) and Delete (DELETE) operations by updating the methods accordingly:

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);

        }

Good enough, but how are we going to test these? A browser uses a GET request when you browse to a webpage, so we need something to send POST, PUT and DELETE requests. A really good tool for this is Telerik's FiddlerPostman, a Chrome extension, is also a pretty good REST client.

First, make sure that the Web API is running (F5). Then, start Fiddler. We can easily send requests by entering the request method, the URL, any HTTP headers, in some cases a body, and hitting the Execute button. Let's see what happens when we try to POST a new book title to our controller:


So here we tried to send a POST request to http://localhost:1817/api/Books, with "The Art of War" in the body. The headers were automatically added by Fiddler. Upon sending this request, an HTTP 415 response appeared in the left pane. What does this mean? To find out, double-click on it:


You can see that HTTP 415 means "Unsupported Media Type". That's because we're sending a string in the body, but we're not specifying how the Web API should interpret that data. To fix this, add the following header to your request in Fiddler:

Content-Type: application/json

When you send the POST request with this header, you should get an HTTP 204, which means "No Content" - that's because our Post() method returns void, and thus nothing needs to be returned. We can check that our new book title was added by sending a GET request to http://localhost:1817/api/Books, which now gives us the following in response:


We can similarly test PUT and DELETE:

  • Sending a PUT request to http://localhost:1817/api/Books/1 with "The Prince by Niccolo' Machiavelli" in the body updates that entry.
  • Sending a DELETE request to http://localhost:1817/api/Books/0 deletes "How to Win Friends and Influence People", the first book in our list.
  • Sending a GET request to http://localhost:1817/api/Books again shows the modified list:

Fantastic! In this unusually long article, we have learned the basics of working with the ASP .NET Web API. Lessons learned include:
  • The ASP .NET Web API is based on the REST concept.
  • The REST concept simply means that you use HTTP POST, GET, PUT and DELETE to represent Create, Read, Update and Delete operations respectively.
  • For each object you want to work with, you create a Controller class.
  • Appropriately named methods in this Controller class give you access to the CRUD operations mentioned above.
  • Use Fiddler or Postman to construct and send HTTP requests to your Web API in order to test it.
  • Add a content type header whenever you need to send something in the body (POST and PUT requests).
Thanks for reading, and please share this with your friends! Below is the full code of the BookController class for ease of reference.


    public class BooksController : ApiController
    {
        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }

    }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.