RESTful Web Services with Web API

Web API is a very nice clean way to get a very robust RESTful web service set up. If you have not had a chance to look at it yet, now is your chance. In this post, I will set up a simple RESTful web service using Web API. I am using VS 2013. You can accomplish the same thing in 2012 using NuGet to download the Microsoft ASP.NET Web API package. 

 

Alright, since this is  blog post, lets build a blog api… We will set up the basic CRUD services for BlogPosts. Start by Creating a new project…. 

Screen Shot 2014 10 28 at 9 11 32 AM

For the purposes of this post, we are going to create an empty project. So select empty and then add the WebAPI references.

Screen Shot 2014 10 28 at 9 13 38 AM

Ok, so some stuff has happened as if by magic, so lets look around for a minute at the important stuff. 

Look in App_start and open WebApiConfig.cs. This has the routing config for your API. You will see a chunk of code that looks like this…

            config.Routes.MapHttpRoute(

                name: “DefaultApi”,

                routeTemplate: “api/{controller}/{id}”,

                defaults: new { id = RouteParameter.Optional }

            );

 

This is the routing rules that your API will follow. In this case, to access your API, you would would start in http://localhost/api. The next piece is the controller. WebAPI will look in the controllers folder for a controller that matches what is passed in here. So, http://localhost/api/posts will look in the controller folder for a PostsController and route to that. The id field is declared optional. We will do something with that in a minute…. 

Ok, so lets go over to the models folder for a minute and get a model created so we have a framework for what a post looks like. Right click on models and select add – > class… Lets call it Post

Screen Shot 2014 10 28 at 9 27 31 AM

 

For the purposes of this post, lets keep it fairly simple. We will add a few fields to Post so we have some data. Lets do Author, Title, Body, and an Array of Tags. Posts should look like this when added…

 public class Post

    {

        public string Author { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public string[] Tags { get; set; }

    }

Ok, now that we know what a Post looks like, lets get some api routes built. Lets start by building a controller. Right click on the controllers folder and click add -> Controller. You will get a box with lots of options. You can have one created with the gets and posts already set up, but what is the fun in that. Just select an empty controller for now. 

Screen Shot 2014 10 28 at 10 04 23 AM

 

name it PostsController and click ok… Now you have an empty controller all ready to go. Lets start out first with some data to pass around. Lets create an array of posts to return. Drop in something like this…

public class PostsController : ApiController

    {

        Post[] posts = new Post[] {

            newPost {Author =“Jon”, Title =“Blogging For Dummies”,

                     Body =“A very short blog post”, Tags new string[] {“soft skills”, “beginner”}}, 

             newPost {Author =“Lee”, Title =“Blogging For Smart People”,

                      Body =“A shorter blog post”, Tags new string[] {“soft skills”, “Expert”}}

        };

 

Now that we have some data, lets set up our get route. This is where WebAPI really shines. For the generic “Get” on our API, all we need to do is create a method called get… yep, thats it. because we are returning a list of Posts, we set it up with a return type of IEnumerable<Post> and WebAPI will deal with all the rest. Your method will look like this…

public IEnumerable<Post> Get()

        {

            return posts;

        }

 

Yea, thats it… Web API will worry about all the rest. With that done, click run and lets get started.  

If you get a screen that looks like everything is broken, that means you did it right…. 

Screen Shot 2014 10 28 at 10 24 53 AM

Thats because you are pointing to just http://localhost… Remember that the controller is at /api/Posts. so update your url to localhost:<port>/api/posts and you should be set…

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfPost xmlns:i=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://schemas.datacontract.org/2004/07/BlogPost.Models”>
    <Post>
        <Author>Jon</Author>
        <Body>A very short blog post</Body>
        <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
             <d3p1:string>soft skills</d3p1:string>
             <d3p1:string>beginner</d3p1:string>
         </Tags>
         <Title>Blogging For Dummies</Title>
     </Post>
     <Post>
         <Author>Lee</Author>
         <Body>A shorter blog post</Body>
             <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
                  <d3p1:string>soft skills</d3p1:string>
                  <d3p1:string>Expert</d3p1:string>
            </Tags>
            <Title>Blogging For Smart People</Title>
     </Post>
</ArrayOfPost>

But wait, why is this XML, I want JSON… Don’t worry, WebAPI returns the data type that is being requested by the client. So if your client sends application/json it will get JSON back. But, I know you want to see JSON when you do it this way so here is a quick fix. add this line to your WebApiConfig and you will see json in the browser

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

Ok, so just like that, we have a working basic API for Posts. In the next post, We will add the other verbs, and then get more complicated with repositories and dependency injection. Stay tuned… 

Leave a Reply

Your email address will not be published. Required fields are marked *