+1-888-365-2779
Try Now
More in this section
Categories
Bloggers
Blogs RSS feed

Getting started with RESTful services in Sitefinity

by Svetla Yankova

Sitefinity 4.x exposes a full set of Web Services. These services follow the RESTful pattern. Most simply explained this means that you are able to access and modify Sitefinity resources(think pages, news, events, blogs, users, permissions, workflows, anything). The way you are able to do that is by making a simple HTTP request to the specific URL of the web service. This can be done through any application. In addition to this by using different HTTP methods you are able to perform different CRUD operations. HTTP POST for Create, GET for Retrieve, PUT for Update and DELETE for … you guessed it.

You can find a great introduction to RESTful services in Sitefinity in this blog post by Gabe Sumner.

A logical question may arise. If I want to implement a simple client that accesses those services and modifies content through them, where do I start? What is the “Hello World” of creating applications that integrate with Sitefinity? 

In this blog post I’m going to look at the steps that you need to take and the resources that you have at hand with Sitefinity. The code sample provided with this post is a Windows Forms Application that communicates with a Sitefinity website, however with the web services you are not limited to a choice of programming language or platform for your client.

Sample scenario:

“I have a Desktop /Android/Web application that I want to integrate with Sitefinity. I would like to view and manage the pages/news/events/content of my Sitefinity based website”

Solution:

Make use of the web services exposed by Sitefinity. Analyze the provided RESTful API and make the corresponding HTTP request, then read the XML or JSON response and deserialize it into objects that your application can work with. 

The code sample provided with this blog post is a desktop application that populates a listbox with all the news items from a Sitefinity website. The user is also able to select some of these news items and delete them remotely.

How-to:

There are 5 major questions that you may have to answer prior to getting started

  1. Which Sitefinity Service do I need to call / which URL do I need to use?
  2. Which HTTP Method should I use and how to specify response format?
  3. How do I authenticate?
  4. How this all fits together in making the call?
  5. How to read the JSON or XML response in the context of my application?

Let’s look into those questions in more detail:

Question 1: Where are those services, where to find the API reference?

The different services can be found in the ~/Sitefinity/Services folder.

Here the list of services is arranged in a folder structure depending on the type of content you can modify with them or the resource they expose. You can find a list with more detailed description of the functionality of different services here

In our case we need to find information on how to work with the news items. In most cases a simple GET request to the URL of the service with no additional parameters will return a collection of all resources exposed by this service. You can immediately check this out by typing this service URL into a web browser, however if you’re not logged in, the response wouldn’t contain much useful information. It will look something like this: 

No authentication service image

This all means that by being logged into the system I can simply call the service from the web browser and get the formatted response with all the data that is needed(in JSON or XML).

Service call in browser

As expected this particular request gets a collection of all news items in JSON format by using an HTTP GET request. However getting the collection of news items is not the only method supported by this service.

If you want to see the full reference what Sitefinity can do with a specific resource, you can use the help pages. This is the most important reference you have at hand when it comes to using services. In order to view a help page, all you need to do is append /help to the service URL.

In our case requesting the help page of NewsItemService.svc gives us long list of all CRUD operations that you are able to perform by calling the service. The UriTemplate and HTTP Method are the most important things to look at right now, since we want to know how to construct the specific call from a remote application. Have in mind that only IE and the newer versions of Firefox display the help pages in a human-friendly format.

Question 2 – Which HTTP method to use and where to set the response format?

As I already mentioned, the basic concept of RESTful services is that resources can be accessed using different HTTP methods. The help pages specify exactly which HTTP method should be used in which case. You may notice that getting a specific news item and deleting a specific news item is achieved using the exact same URL, the only difference is the HTTP method.

Specifying the response format is also straightforward. By default Sitefinity returns the data in JSON format, however you can also request an xml response by appending /xml to your service call.

Question 3 – What about Authentication?

One of the very important steps here is handling authentication. If you want to manage Sitefinity content through the back-end you have to log in. Much in the same way, if you want to manage Sitefinity through a third party application you have to authenticate. A remote application can authenticate with Sitefinity by calling the corresponding service that is responsible for this and passing on the user credentials. The service URL used for this is /Sitefinity/Services/Security/Users.svc/authenticate

How authentication happens

When you authenticate successfully Sitefinity returns a token in the form of a cookie. You can then pass this cookie in the ongoing requests that you have between the client and Sitefinity.

Service calls

Question 4: How this all fits together in making the call?

Now the idea of making the service call is simple. There are a few parameters that a service call takes into account

  • The URL of the Sitefinity website 
  • The URL of the Web Service that we’re going to access (/sitefinity/services/content/NewsItemsService.svc)
  • The HTTP Method
  • The parameters defined by the service – for example if we want to fetch a particular news item we have to provide it’s ID in the service call. This is added to the URL as a parameter.
  • The body of the request (if we are performing Create or Update operations using HTTP POST and HTTP PUT we will need to put the parameters in the body of the request, again using JSON or XML formatting)

All of the information on how to format this is found in the UriTemplate. For PUT and POST requests a request schema and request example are provided in the help pages. Additionally every time we make the requests have to pass cookies. Taking all of this into account it’s best to create a method that wraps all the logic around making the service call - the HTTP requests and cookie handling. Then calling a service can simply look like this:

Var result = InvokeRequest(url, serviceURL, urlParams, httpMethod, data);

Here InvokeRequest is the method that we’ve created. The parameters passed to it are the ones we need for the resource that we want to access and the result here is a simple JSON formatted string.

Question 5 – What do I do with all this JSON/XML?

It all sounds great but I want to manipulate objects in my application - not JSON or XML. This leads to another important step - deserializing the response. This means extracting the response from a series of bytes in a specific format(JSON or XML) into a data structure. If we are reading data from Sitefinity we would like to construct objects with the data received from the service call as properties. If we want to create or update Sitefinity resources we can serialize our objects into json/xml and pass them to Sitefinity as the body of the HTTP request. This all leads to designing a simple class that represents a Sitefinity resource.

What you can do to get started with this is to use the browser to call the services directly and see the response, or analyze the example response and response schema from the /help pages. That way you can get names and types of the properties you will need in your class. The thing that I use with my Chrome browser is an extension called JSON Formatter that gives the JSON response in a more readable manner. Here are the first few lines of the response:

{
 
"Context": null,
 
Items":
 
[
 
{"Author": "Stanislav Padarev",
 
"AvailableLanguages": ["","en","es"],
 
"CommentsCount": 0,
 
"DateCreated": "/Date(1313481422110)/",
 
"Title": "An open letter to Quantum customers and partners",
 
………

This essentially is a collection of news items and all the properties are serialized in key:value pairs. The keys represent the names of different properties that a news item has in Sitefinity. So when I write my class I would have to add only the properties that I need. If I simply want to manipulate the title of the News Items, then in C# my class would look like this:

//a collection of news items
public class NewsItems
{
    public NewsItem[] Items { get; set; }
}
                
//A single News Item
public class NewsItem
{
   public string Title { get; set; } //the title as a string
}

In Java, Python or any other language it may look a little different, however the basic principle remains the same.

The final step is using some sort of a helper to deserialize the data into objects or serialize objects in a specific format. In my case I use System.Runtime.Serialization.Json.DataContractJsonSerializer provided by the .NET framework and the code looks something like this:

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(response)))
{
    DataContractJsonSerializer newsSerializer = new DataContractJsonSerializer(typeof(NewsItems));
    NewsItems newsItems = (NewsItems)newsSerializer.ReadObject(ms);
     
    foreach (NewsItem item in newsData.Items)
    {
         //add your logic here
    };
}

How it all fits together?

This concludes the basics of how to use services in client-side development. The code sample provided is a very simple RESTful client that allows you to fetch all news items. You also have a delete button to illustrate another HTTP method that can be used with the service. Be careful and use the delete button only for dummy news items and not for actual content on a live site. You can download the code to see how all of this is handled programmatically and get started. From then on the sky is the limit. You can design, develop or extend any type of application to access and modify Sitefinity content remotely. 

Warning: If you are still logged in the Sitefinity back-end, logout before attempting login through a service. Otherwise you will receive a 412 HTTP error.

Special thanks to Falafel Software for helping out with this sample.

Downloads

Footnotes

  • For familiarity's sake I have used the term URL in this blog post. However the more correct term in the context of RESTful services would be URI

 

10 comments

Leave a comment
  1. Tim Jan 23, 2012
    Great example - thanks for sharing it!

    Do you always need to authenticate, even to view publicly-available data?

    Thanks
  2. David Lively Jan 27, 2012
    I found a convenient way to convert the JSON results to a C# class that can be helpful when parsing results from the various services: see http://json2csharp.com/
  3. David Lively Jan 27, 2012
    Also, there's a desktop version at http://jsonclassgenerator.codeplex.com/
  4. Marc Feb 06, 2012
    This is good as a starter to understand the basic interaction needed, but the more complex pieces are the inserting a new module item and updating an existing item.  A simple walk through on that would be nice to see as well as multiple calls need to be made and pumping the content into the body of the message with the pieces that need to be updated would be good to understand.   
  5. Svetla Mar 08, 2012
    @Tim - yes, you have to authenticate for most services. There are a couple of  exceptions - some services will allow anonymous access - the Shopping Cart Summary for example. For now the workaround for this is to create your own service and expose the data that you want. 

    @David  This is an awesome tip, thank you for this!

    @Marc I will be prepping a second post on this some time soon and I really appreciate the feedback. Will make sure to include samples for what you mentioned. In the meantime there's a trick I like to use - open up the network tab in Firebug or Chrome Element Inspection and click around in the back-end for the same actions that I want to achieve through a service. Since the Sitefinity back-end itself is essentially a giant RESTful client for Sitefinity, that gives the best reference on what to call and how in order to achieve a specific result. (It will also give you some valid GUIDs to experiment with)
  6. Jerome Jun 09, 2012
    This code doesn't work with SF 5.0.  Can you please provide an update since the authentication changed in the web services in 5.0?

    Thanks
  7. Svetla Jun 12, 2012
    Hi Jerome,
    Until the official blog post is out, here you can find a working sample for this with support for both authentication modes(Claims and Forms)

  8. Drupal Hosting Dec 17, 2012
    Buy one get one free.
  9. Jonathan Dec 29, 2012
    Was an update for this ever created for SF 5.x? The current sample code doesn't work for my local SF deployment (v5.2).
  10. Svetla Dec 31, 2012
    Hi Jonathan,
    I have updated the code linked above on GitHub and it includes the update to work with claims authentication introduced with 5.x.  I tested it with 5.2 and didn't run into any issues. Blog post  is also coming up shortly, but for now the most notable change in the sample is that it supports both Claims and Forms and you can change the mode you would like using the dropdown menu.

    Cheers and have a Happy New Year!
    Svetla

    Leave a comment