Monthly Archives: November 2014

RESTful Web Services with Web API – Part 3 – Query String Params

we are working through a series on WebAPI and RESTful services. In the last post I worked through implementing the verbs associate with REST. We often find ourselves in a situation where we need a little more flexibility that just Get all items or get one item by id. Sometimes we want to search for a group of items or filter. With WebAPI that is as simple as adding in a query string param to our get method. Lets check it out….

 

In our example we have been working on a “Post” service for a blog site. At this moment, our Post service has a get method that looks like this..

        public IEnumerable<Post> Get()

        {

            return dm.posts;

        }

Just a quick reminder about how the posts look. 

        public List<Post> posts =newList<Post>(newPost[] {

            new Post {ID = 1, Author = “Jon”, Title = “Blogging For Dummies”

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

            new Post {ID = 2, Author = “Lee”, Title = “Blogging For Smart People”

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

        });

I would like to have an option to filter my posts by Tag. So, if I query /api/Posts/?Tag=Expert I would only get Lee’s smart people post… To make this work, we will rely on the magic of WebAPI to pass the query string into a param for our method. 

So, lets add that option to our get post. 

 public IEnumerable<Post> Get(string tag null)

  

We are making it an optional parameter by adding a default value of null. So when we have tag == null then nothing has been passed in and we just pass back the list… Like this…

            if (tag == null)

            {

                return dm.posts;

            }

Yep, that part is easy. Now, if a query string param is present, WebAPI will match it up with the method params and plug them in. So in this case, /api/Posts/?Tag=Expert, WebAPI will set the tag param to Expert in our method. So the only part left here is is to query the repository for all the posts matching the tag that was passed in. It should end up looking like this…

        public IEnumerable<Post> Get(string tag null)

        {

            if (tag == null)

            {

                return dm.posts;

            }

 

            return (from p in dm.posts where p.Tags.Contains(tag) select p).ToList();

        }

Thats it, it is just that easy to add query string support to your API.

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.