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. 

 

Leave a Reply

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