Getting started with RESTful services in Sitefinity

Getting started with RESTful services in Sitefinity

November 01, 2011 0 Comments
Getting started with RESTful services in Sitefinity

The content you're reading is getting on in years
This post is on the older side and its content may be out of date.
Be sure to visit our blogs homepage for our latest news, updates and information.

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
progress-logo

The Progress Team

View all posts from The Progress Team on the Progress blog. Connect with us about all things application development and deployment, data integration and digital business.

Comments
Comments are disabled in preview mode.
Topics
 
 
Latest Stories in
Your Inbox
Subscribe
More From Progress
New_Mobile_Dev_Ebook_Progress_Website_Thumbail
The New Mobile Development Landscape
Download Whitepaper
 
IDC Spotlight Sitefinity Thumbnail
Choosing the Right Digital Experience Platform to Improve Business Outcomes
Download Whitepaper
 
TheFastestWayToBuildMobileAppsArtboard-2
The Fastest Way to Build Mobile Apps With Cloud Data
Watch Webinar