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.

Leave a Reply

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