Tag Archives: WebApi

RESTful Web Services with Web API – Part 2 – Verbs

In my last post, we began work on a ReSTful API using WebAPI in .Net. If you have not followed along with that post yet, head over there and run through it. What we ended up with was a simple API dealing with BlogPosts that only worked with the Get verb. In this post we will work through the other verbs that are used with ReST. 

Get      /api/Posts/:id    Get a single BlogPost

Post    /api/Posts         Add a new BlogPost

Put      /api/Posts/:id     Update a single BlogPost

Delete /api/Posts/:id     Delete a single BlogPost

 

Ok, so the data handling we have right now will rapidly fall apart when we try adding and updating blog posts. To keep it simple for learning purposes, we are going to institute some quick and dirty data management using a singleton repository. That will get us through for now so you can continue to see these routes in action. You can pick up the full code for the repository on https://github.com/jonathanfmills/WebApiBlog but if you are just reading through, don’t worry about that too much right now.  

Lets start with the Get verb to return a single BlogPost. Right now your PostsController should look like this:

    public class PostsController : ApiController

    {

        repository dm = repository.GetModelInstance();

 

        public IEnumerable<Post> Get()

        {

            return dm.posts;

        }

 

What we want to add next is a new method that will return an individual Post from the array based on a variable being passed in. So, to do that, we add a new method under the current one that returns  Post and takes an int param. It should look something like this. our repository returns an instance of posts that implements iQueryable so we can query it directly. 

public Post Get(int id)

        {

            return dm.posts.Where(x => x.ID == id).First();

        }

With this in place, WebApi will look for a route like /api/posts/2 and pass the 2 into this get method. Just that simple. No, really…

Ok, lets add a new Post to our list. We will do that by using the “Post” verb. So we will create a new method called Post. We need a parameter that will hold the new BlogPost so we take a parameter of type Post. WebApi will look at the input from the post and fit it into the object type that we are expecting. As if by magic…. But just go with it.  Now, we don’t want to just return void. We want to let the calling application to know that it was successful. So we set it up with an HttpResponseMessage as the return type. The method will look like this.

public HttpResponseMessage Post(Post p)

        {

            dm.AddBlogPost(p);

            return new HttpResponseMessage(HttpStatusCode.OK);

        }

So, when you post to /api/posts with a form or json payload, WebApi will automatically parse the payload and load it into a Post object. (Or whatever object type you use as a param for the function. Super easy. 

Now, how do you test this…. I use fiddler to make this happen. Its super easy to do and its free…. If you don’t have it already, go download it… http://www.telerik.com/fiddler

Fire up fiddler and go to the compose tab. Send a JSon doc to localhost/api/posts. It should look like this…

Screen Shot 2014 11 07 at 8 38 10 AM

 

 

Now, in your browser, a quick get to /api/posts should return three posts. 

[
    {
      ID: 1,
      Author: “Jon”,
      Title: “Blogging For Dummies”,
      Body: “A very short blog post”,
      Tags: [
         “soft skills”,
         “beginner”
      ]
   },
   {
      ID: 2,
      Author: “Lee”,
      Title: “Blogging For Smart People”,
      Body: “A shorter blog post”,
      Tags: [
         “soft skills”,
         “Expert”
      ]
   },
   {
      ID: 3,
      Author: “Jon”,
      Title: null,
      Body: “This is a new Post”,
      Tags: null
   }
]

And a get to /api/posts/3 should just return the new post….

Ok, so we can get and post. Lets do a put now… Remember, a “Put” will update a specific BlogPost so we will need to create a method called Put that will take 2 params. The first one will be the Id of the BlogPost, same as the Get. The second param will be the full BlogPost object that we want to update. In the body of the method, we will want to pull the original BlogPost and update only the fields we allow. We wouldn’t want to update the ID for instance. 

The Put method will end up looking like this…

public HttpResponseMessage Put(int id, Post p)

        {

            dm.UpdateBlogPost(id, p);

            return new HttpResponseMessage(HttpStatusCode.OK);

 

        }

 

The Update method looks like this… 

public void UpdateBlogPost(int id, Post p)

        {

            Post post = posts.Where(x => x.ID == id).First();

            post.Author = p.Author;

            post.Body = p.Body;

            post.Title = p.Title;

        }

 

3 down, 1 to go. Delete is just as easy as all the rest. We simply create a method called “Delete” and pass in the id… Done..

public HttpResponseMessage Delete(int id)

        {

            dm.DeleteBlogPost(id);

            return new HttpResponseMessage(HttpStatusCode.OK);

 

        }

The DeleteBlogPost method looks like this… 

 public void DeleteBlogPost(int id)

        {

            Post p = posts.Where(x => x.ID == id).First();

            posts.Remove(p);

        }

Thats it, The 4 common ReST verbs implemented in WebApi. In the next post, we will start talking about query string params as well. 

 

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…