RVP

Creating your own REST Service with MVC WebAPI

On June 21, 2013, in MVC, Web Services, WebAPI, by admin

The trend for writing web services in the .Net community is moving from SOAP to REST. There are many reasons for this, but the most compelling may be the difference in “weight.” When using SOAP you must wrap everything in an envelope before sending, with the REST protocol you basically just send it. There are very few restrictions on what you can send over.

Consuming these new REST services is very simple and very well understood, and it turns out that writing them using MVC is extremely easy as well. Starting with MVC4 you can use the WebAPI to create a REST service very quickly and using a model that you are familiar with.

The Employee Service

For the purposes of this demo I am going to be creating a service to pull employees. In order to do that I need to create an empty EmployeesController,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
 
namespace ODataTest.Controllers
{
    public class EmployeesController : ApiController
    {
 
    }
}

As well as an Employee Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace ODataTest.Models
{
    public class Employee
    { 
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ManagerName { get; set; }
    }
}

In the EmployeesController class you can see that I am inheriting from ApiController instead of the normal MVC Controller class. And in a nutshell that is pretty much all you need to do in order to create a REST Service. I told you this was easy right?

My First Call – Get All

This class doesn’t have anything in it so if you were to call this you wouldn’t get anything back, so let’s implement the default call and return all employees. I am not going to create a data access, this is just a demo so I am going to create all my employees in my “Get” method and just return them there.

        [HttpGet]
        public Employee[] Get()
        {
            return new[]
                {
                    new Employee{Id = 1, FirstName = "Tony", LastName = "Stark", ManagerName = "Nick Fury"} ,
                    new Employee{Id = 2, FirstName = "Bruce", LastName = "Banner", ManagerName = "Nick Fury"} ,
                    new Employee{Id = 3, FirstName = "Bruce", LastName = "Campbell", ManagerName = "Bruce Campbell"} ,
                    new Employee{Id = 4, FirstName = "Peter", LastName = "Parker", ManagerName = "Aunt May"}  
                };
        }

There isn’t much here. We have a method named Get that is decorated with the HTTPGet attribute. This is telling the parser that you can call a post against this method. If I call this method I will receive a JSON representation of the Employee object back. I didn’t have to “stringify” this, the MVC parser will take care of all of that for you.

If we wanted to consume this method we would call a URI that matches the following pattern http://<yoururl>/api/Employees and from this call we would receive the following JSON back

JSON from service call

Get Single Employee

That is a pretty simple case, so let’s expand on that. If we wanted a specific employee we would need to add the following method

        public Employee Get(int id)
        {
            var employeeList =  new List<Employee>
                {
                    new Employee{Id = 1, FirstName = "Tony", LastName = "Stark", ManagerName = "Nick Fury"} ,
                    new Employee{Id = 2, FirstName = "Bruce", LastName = "Banner", ManagerName = "Nick Fury"} ,
                    new Employee{Id = 3, FirstName = "Bruce", LastName = "Campbell", ManagerName = "Bruce Campbell"} ,
                    new Employee{Id = 4, FirstName = "Peter", LastName = "Parker", ManagerName = "Aunt May"} 
                };
 
            var emp = employeeList.FirstOrDefault(x => x.Id == id);
            return emp ?? new Employee();
         }

The MVC framework will parse your URI, which should look like http://<yoururl>/api/Employees/1, and then find the correct Get method. This is all done by convention so if the last bit of your URI isn’t an integer this will fail. When I call this service I should get a JSON object back that represents Tony Stark. You may have noticed that I didn’t put the HttpGet attribute on this method. I could put in on there and everything would work fine. It turns out that because the method is named Get, the parser realizes that it is a get method and won’t try to post against it.

Summary

This was a very quick scratching the surface of the WebAPI. I will be posting more about the WebAPI in the coming weeks covering more in depth topics such as posting back to the service to insert data and then using the ODataController to do some neat stuff with sorting and filtering.

To quickly recap what we learned today:

  • Creating REST services with MVC4 and the WebAPI is very simple
  • Instead of using Controller use ApiController to create a REST service
  • Just like using base MVC the WebAPI is very convention based, so things are very easy to follow
Tagged with:  
RVP

Getting Some REST with SharePoint 2013

On March 25, 2013, in Sharepoint, Web Services, by admin

There are many options out there for programming against the SharePoint object model. You can use all sever side code using the server side object model, everything client side using JavaScript and the CSOM (client side object model). You can even use Silverlight to access your SharePoint objects. One of the newest methods, and one that I’m excited about, is using the new SharePoint REST API. Making RESTful service calls is now available using SharePoint 2013, which makes creating pages and web parts very simple.

You can access most of your SharePoint objects via REST, but I am just going to look at lists for the moment. I will show you how to first read something from a list and then how to insert an item into that list.

The Model

For this example we are going to have a list already created named ‘Employees’ that has 5 fields.

  1. Title (I changed the display Name to Name)
  2. Address
  3. Department
  4. Salary
  5. Manager

Selecting From a List

The whole basis for RESTful queries is the URL and SharePoint makes this very easy for you. In this example let’s assume that our employees list is at the root of our site. In order to select all items from this list we would simply query the following URI:

https://mysite.com/_api/web/lists/getByTitle('employees')/items.   

The ‘_api’ tells SharePoint that this is going to be a REST query, and the rest of the string tells it where to find this list. A normal REST query would look like this:

https://mysite.com/_api/web/lists/employees/

But since this is SharePoint things are always a little bit different. Instead of referencing the list directly in the URI you must find the list by title. There is also an option to find by GUID, but using the title is a bit simpler to read in my opinion.

That query will give you every property of every item in your list. Sometimes this might by OK, but I would assume that most of the time this is going to be overkill. I queried my list with Fiddler and this is the first entry of the result set that came back.

full query set

You can see all of my custom properties in there, but the rest of the stuff I really don’t care about. Let’s trim this list a little bit by adding a query string to the end of my URI I can tell SharePoint to only give me back certain items.

 https://mysite.com/_api/web/lists/getByTitle('employees')/items?$select=Address,Department,Manager,Title,Salary

simplified query

This is the same record that I selected from above and obviously this is a lot lighter than my first query, so you would want to make sure you trim down the items you are returning to only the items you actually need. Also note that in the Model section above that I renamed the default Title field to Name, however that is just a display name. So when you are querying the list you must give the static name which is Title in this case. You can use most of the ODATA protocol in order to page through the list or do some filtering but I will leave that as an exercise for you.

Inserting a List Item

Inserting an item is just as easy as selecting an item and in fact we are going to be using the same URI and just change our HTTP verb from GET to POST.
We start with https://mysite.com/_api/web/lists/getByTitle(‘employees’)/items just like before, but this time we are going to need a payload to send along with this query so SharePoint knows to insert it. My payload data looks like the following.

 { '__metadata': { 'type': 'SP.Data.EmployeesListItem' }, 
    'Title':  'Tony Stark',
    'Department' : 'Research', 
    'Salary':  '2,000,000', 
    'Manager':  'Pepper Potts',
    'Address':  '23 Ironman Way, New York, NY'
 };

We are telling SharePoint what type of object we are inserting, in this case SP.Data.EmployeesListItem. Then we just pass along as a JSON string representation of everything that we want to fill out about the item. Just that simple.

We POST against this URL and SharePoint takes care of the rest.

Summary

  • SharePoint 2013 exposes a RESTful service to access lists and other elements
  • RESTful queries are quickly becoming the standard for web services instead of the older SOAP standard
  • Using RESTful queries in SP 2013 allows developers to access SharePoint elements without having to write any complex code

This post is also over on my company site

Tagged with: