2013/04/13

Implementing a Web API in .Net

This article explains how to implement a basic Web API in .Net using Microsoft Visual Studio 2012. Before continuing you should be familiar with the following concepts:

  • What is a Web API
  • Routing from an HTTP request to a controller class and method
  • What are actions and resources

Step 1 – Create the project


Create a new ASP.NET MVC 4 Web Application and select the Web API template.

Description: cid:image001.png@01CE3698.58B41990




Step 2 – Create some models


Models are classes that represent resources on the server. For example, if your Web API has an /api/products collection of resources you should have a model class called Product, like this:

namespace MyWebApp.Models
{
    [DataContract]
    public class Product
    {
        [DataMember]
        public int ProductId { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
}

Models will be returned by some of the methods on the controllers and finally serialized into XML or JSON before being sent back to the client.


Note the use of the [DataContract] and [DataMember] attributes in this class. They are used to indicate the class and properties/fields that should be serialized. If I were to remove the [DataMember] attribute above the Name property the serialized version of this class will not contain a Name field.

These attributes are not required for simple classes that have no constructors or additional fields that cannot be serialized. However, if I remove all the attributes in the example above the serializer will try to serialize the constructor as well and throw a nasty exception. So as a matter of consistency I recommend adding them even when not required.

Models go in a folder called “Models”:






Step 3 – Create some controllers



A controller is a class that will handle actions that are being performed on server resources. For example, if your Web API has an /api/products collection of resources you should have a controller class called ProductsController, like this:


namespace MyWebApp.Controllers
{
    public class ProductsController : ApiController
    {
        public IEnumerable GetAllProducts()
        {
            MyWebAppDao dao = new MyWebAppDao();
            return dao.FindAllProducts();
        }
    }
}

For routing to work correctly pay special attention to the names of the class, methods and parameters.

You can add a controller class manually or right-click on the Controllers folder and select Add->Controller to bring up the following menu:



Controllers go in a folder called Controllers:





Step 4 – Test the Web API in your browser:

Compile the project. You should now be able to hit the following URL: http://MyWebServer/MyWebApp/api/products and get an XML list of products back.

2013/04/12

Web API concepts

This article explains the basic concepts behind a Web API. The article is not meant to be an exhaustive explanation of the technology on an academic level, but rather to explain the basics of what you should know before using it. Most of the concepts are generally applicable to the technology, but some of the details may be more tailored to the .Net implementation of a Web API.


What is a Web API?


A Web API is an interface to a system which is exposed over raw HTTP and accessed using standard HTTP methods. In practical terms this means that methods residing in classes in a web application is made directly accessible via URLs.

An example:

Suppose we had a data access object (which in the example below has been hard coded with some data) which returns some data objects (the Product class below as an example):

namespace MyWebApp.DataAccess
{
    public class MyWebAppDao
    {
        public IEnumerable<Models.Product> FindAllProducts()
        {
            List<Models.Product> products = new List<Models.Product>();
            products.Add(new Models.Product{ ProductId = 1, Name = "Soap" });
            products.Add(new Models.Product{ ProductId = 2, Name = "Baked beans" });
            products.Add(new Models.Product{ ProductId = 3, Name = "Cat food" });
            return products;
        }
    }
}

namespace MyWebApp.Models
{
    [DataContract]
    public class Product
    {
        [DataMember]
        public int ProductId { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
}
and we browse to:

http://MyWebServer/MyWebApp/api/products
then Web API may call the GetAllProducts method in the ProductsController class shown below:

namespace MyWebApp.Controllers
{
    public class ProductsController : ApiController
    {
        public IEnumerable<Models.Product> GetAllProducts()
        {
            MyWebAppDao dao = new MyWebAppDao();
            return dao.FindAllProducts();
        }
    }
}
and return some XML representing a collection of products which the browser will display:

<ArrayOfProduct xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyWebApp.Models">
  <Product>
    <Name>Soap</Name>
    <ProductId>1</ProductId>
  </Product>
  <Product>
    <Name>Baked beans</Name>
    <ProductId>2</ProductId>
  </Product>
  <Product>
    <Name>Cat food</Name>
    <ProductId>3</ProductId>
  </Product>
</ArrayOfProduct>



How does it know which controller/method to call?


The process of mapping the URL of an HTTP request to a controller class and a method is called routing. This process happens automatically when the web application hosting your Web API service receives an HTTP request so you don’t have to code this manually. You do however need to understand how it works.

Routing uses the names of controller classes, methods and parameters together with the details of the HTTP request.

Routing starts by looking at the following two items:
  1. The URL of the HTTP request, e.g. http://MyWebServer/MyWebApp/api/products/1
  2. The action contained in the header of the HTTP request, e.g. GET, POST, PUT or DELETE
It then tries to match this to the correct method by investigating:
  1. The names of the controller classes
  2. The names of the methods on the controller classes
  3. The parameter names of the methods on the controller classes
By default Web API request URLs take the following forms:
  1. http://MyWebServer/MyWebApp/api/{controller}
  2. http://MyWebServer/MyWebApp/api/{controller}/{id}
  3. http://MyWebServer/MyWebApp/api/{controller}?parm1=val1&parm2=val2...
The first part, http://MyWebServer/MyWebApp, is simply the path to your web application.

The /api part tells the web application that this is a request that should be routed to a Web API controller.

The /{controller} part indicates which controller the request should be routed to. It matches this value to the name of a controller class. So if the request is for /api/products it will try to find a class named ProductsController that inherits from the ApiController base class.

The next step in the routing process is to choose a method to call on the controller class. This is done using:
  1. The action: GET, POST, PUT or DELETE
  2. Either the /{id} part or the query string part, e.g. ?parm1=val1&parm2=val2...
A method name must always start with the name of the action, e.g. GetProducts, PutProduct, PostProduct or DeleteProduct. This part of the method name will be matched with the action of the HTTP request.

The /{id} part is an integer and will be matched to a method with an int parameter named id, e.g. GetProduct(int id), PutProduct(int id) or DeleteProduct(int id).

The query string parameters will be matched by name to methods that have parameters with the same names, e.g. ?parm1=val1&parm2=val2 will be matched to GetFilteredProducts(string parm1, int parm2).




What are actions and resources?


Resources in the context of making a Web API call essentially refers to the controller part of the URL, e.g. making a request to /api/products means that the resource being addressed is the products resource. Think of it as a collection of products that reside on the server.

Actions are things that can be done with resources and serve as a way of signalling the intent of the client when it is addressing a resource.

Resources and actions together describe a communication interface between the server and the client. For example performing a GET action on the products resource means that the client intends to get one or more products from the collection of products that resides on the server.

The four basic actions in HTTP requests are:
  • GET – Tells the server that the client is expecting to get one or more items back from the server
  • DELETE – Tells the server that the client intends to delete an item from a resource on the server
  • POST – Tells the server that the client intends to send it a new item to be saved in a resource on the server and that the client expects the server to send it back an id for that item
  • PUT – Tells the server that the client intends to send it an item to save on the server

It is worth noting the difference between PUT and POST as this can be confusing. The following link explains the difference quite well: http://stackoverflow.com/questions/630453/put-vs-post-in-rest.



Further reading


If you are interested in the related subject of RESTful web services you can read more about it here: http://kellabyte.com/2011/09/04/clarifying-rest/.