As a freelance software developer I get thrown into many different kinds of projects. They include a variety of different technologies (although I favour the Microsoft stack) and they are on a wide spectrum of “project approachability”. But that I mean they vary widely in terms of how well maintained they are, how well the code is written (which is another completely different discussion for another time), how well it is documented and how easily you can jump in as an outsider and start contributing.

Invariably I have gotten reasonably good at a couple of things when it comes to new projects: identifying risks in the tasks to complete and questioning the decisions made before my involvement. Part of why people hire me is to get a fresh perspective, so if I don’t give them a non-sugar coated opinion I feel they are missing out. Not all clients like to hear an honest opinion, but most appreciate it. The reason I bring this up in an article talking about Web API, is that the “new” way of building software is with micro services, which often paves the way into lots of API endpoints, which in turn can be built with the Web API framework. Sometimes it is a software manager that has been told that he has to be more “lean” in his approach and “fast paced”. Buzz words that can mean vastly different things to different people. Hence my point of giving an honest opinion. Because sometimes there really is no need to build brand new shiny things, even if it is the latest and greatest. The cheapest and most efficient option is very often to keep what you’ve got and improve on it. With that in mind I have been working on Web APIs on and off for the last while, and I want to give you a bit of a leg up when creating your very first Web API, because I have seen some ways that, granted, are very easy, but also leaves you with a code mess that is hard to clean up later. I am talking vanilla project without any fat, but all the power.

It is tempting to do this:

New Project

But don’t! A “clean” Web API template in Visual Studio 2015 means getting a full MVC app included with, and tangled into, your Web API. You also get sample controllers that you most likely won’t need, as well as “resources”, such as images. Instead, create an empty app and we will add the bits we need as we go. It means you not only have a lighter and nimbler project, but you also know what is included and what you have to work with. Instead, choose the empty ASP.NET template. If you want to add a test project, you can do that as well.

Image alternative text

This will get you a bare bones solution with pretty much nothing included. Perfect.

Image alternative text

The first thing to do is to fire up NuGet and get those sweet Web API references brought in. Right click the project and select “Manage NuGet Packages”.

Image alternative text

This will bring up the NuGet Package Manager where you can search for “web api” then install the core libraries for Web API.

Image alternative text

That will add the necessary references to your project in order to use the Web API framework. Now, let’s build our first RESTful API endpoint. Add a new folder “Controllers” to the project, right click it and then add controller

Image alternative text

Then choose the scaffold “Web API 2 Controller – Empty”. Again we don’t want any of the “free” stuff that the other templates are including for now. We are setting up a light weight bare bones API.

Image alternative text

Name the controller whatever is appropriate, but you must adhere to the naming convention of ending the name with “Controller”. Also bear in mind that if you follow standard industry convention, then the name of your controller is also the name of your endpoint. If you want to have an endpoint accepting restful requests at http://api.batmanrocks.com/protect, then you would call your controller “ProtectController”.

You now have a controller, but it doesn’t do anything. There are no endpoints defined. The standard for a RESTful client is to use HTTP verbs such as GET, POST, PUT and DELETE to get data, provide data, insert data and delete data respectively. That makes it very easy to create your API endpoints for the appropriate action. The convention is to call your endpoint accepting GET requests for “Get”. Simple.

First we need something to return from the API though, so let’s create another project level folder called “Models”. This will hold all our data models used in the API. Create a class in the folder and call it “MyFirstModel”. You can copy the code below to help you along.

~~~csharp public class MyFirstModel { public string Magic { get; set; } public int Wizardy { get; set; } public bool IsFairy { get; set; } } ~~~ The models will hold all the data that is return, and the Web API framework will serialize the data for you into JSON or XML.

Next fill in the Controller code

~~~csharp public class MyFirstController : ApiController { public IHttpActionResult Get() { // Create mock object var model = new MyFirstModel { IsFairy = true, Magic = "Very much", Wizardy = 99 };

return Ok(model);

} } ~~~

There is an action method called Get, which is going to be our GET endpoint. Usually GET will have none or one parameter (to accept an ID for example), and in this case we have none. It is an action to return a pre-determined set of data.

The return type of IHttpActionResult is an Interface that defines an HttpResponseMessage, which is a well formed response to be sent back over Http. The Ok call is a wrapper that creates a response with HTTP code 200 (success) and including the response body being the model.

Alright, we now have an API, but we are still missing the routing part of the equation. You need to tell the application how incoming requests are routed, so they can find your new shiny controller. In other words, we need a configuration setup for the API.

I like using the OWIN (Open Web Interface for .NET) middleware that defines a standard between web servers and web applications. I won’t go into more detail on OWIN in this article, but to use it you just need to add two NuGet packages: Microsoft.Owin.Host.SystemWeb and Microsoft.AspNet.WebApi.Owin.

Image alternative text

These will add the OWIN middleware to your Web API project and enable the routing we are after. Now you just have to configure it. Add a folder to your project called “App_Start” and add a class file called WebApiConfig.cs into the new folder. Copy the code below into it.

~~~csharp public class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "GetMagic", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } ~~~

This configures our routes to hit the prefix “api” followed by the controller name and then an optional id. You can add as many routes as you like, but keep in mind that the first route to match will be used. If you have very specific narrow routes, you’d want to put those first. In a later part of this series we will also look at how you can configure routes in different ways.

Then we need the OWIN entry point, which is similar to the Global.asax in a standard ASP.NET application. By convention this entry point is a class called “Startup” and it must be in the root of your project and it must be spelled that exact way “Startup”. The Startup class must contain a method called Configuration that takes an IAppBuilder object.

~~~csharp public class Startup { public void Configuration(IAppBuilder appbuilder) { var httpConfiguration = new HttpConfiguration(); WebApiConfig.Register(httpConfiguration); appbuilder.UseWebApi(httpConfiguration); } } ~~~

And that is it. Hit F5 in Visual Studio and IIS Express will fire up and serve your new Web API. If you take a tool like Postman and hit the endpoint we just created you get something like this:

Image alternative text