A comparison of JSOM and REST

INtroduction to JSOM and REST
With the launch of the app-model in SharePoint 2013 Microsoft and his small brother from Office 365 have started to make programming safer and more standarized. The programming of apps and especially SharePoint hosted apps is mostly done with JavaScript and JSOM (JavaScript Object Model) API. The article should clarify the advantages and disadvantages for this approach. This is shown exemplarily in a search driven app approach.

Authors:
Sebastian Schütze (sschuetze@fum.de) is a SharePoint Consultant of the company Fritz & Macziol and was working more than 6 years as a web developer.

and

Chris Spettmann (cspettmann@fum.de) is s SharePoint Consultant of the company Fritz & Macziol and has more than 7 years experience in the .NET framework and web development.

JavaScript is used by many developers and has been given a lot of names (but it’s not known as a good programming language… some would be insulted by calling JavaScript a programming language). Most developer have a “workaround” habit when it comes to JavaScript code. But with the introduction of REST [1] (Representational State Transfer) – and JSOM-APIs [2] for SharePoint, Microsoft is giving us big tools at hand to build complex apps (although the APIs are far from perfect). In situations where you have a wide variety of requirements you have mostly to choose between REST or JSOM. Several questions come into my mind, which need to be answered:

1. Which Technologies / Plattforms are used?
2. How important is Performance
3. How good is the skill of the Developer (JavaScript etc.)
Before those Questions are answered examples are presented how to create a search driven SharePoint hosted app with REST services and JSOM.

Search with JSOM

Depending if you come from the SharePoint corner (SharePoint 2010 and earlier) or if you have no SharePoint experience will like the structure of the JSOM-API or not. JSOM has a very similar structure like SSOM (the Server Side Object Model) and is using CAML for example to query data from SharePoint lists. This is the reason why many SharePoint developer will find it easier to use this API.

Create a search Request

Without further explanation a code snippet is presented in Listing 1 which shows a search request. Before a search can be start we need a KeywordQuery object where the search text is assigned. The KeywordQuery object is then delivered to the SearchExecutor, who is preparing the search request. At this point no request is send because a second search request in variable keywordQueryDoc is prepared. This request is using another source. The results of the asynchronous search requests will be handed over to the variables resultsJsom and resultsJsomDoc. Since those requests are sent to the app web and host web (depending if the correct app permissions are set) a search result source can be specified to limit the search results. The people result source is used in the first search request by setting the property set_sourceid (in this case the guid of the result source is used, which is the same in every SharePoint 2013 farm). The second request is limited by using the id of a content type.
Furthermore only the WorkEmail from the List is returned.
Only at the end by calling the function executeQueryAsync both search requests are send at once.

Listing 1
var query = Microsoft.SharePoint.Client.Search.Query;
var personQuery = new query.KeywordQuery(context);

personQuery.set_sourceid = ‘B09A7990-05EA-4AF9-81EF-EDFAB16C4E31’);
personQuery.set_queryText(‘*Any searchable information from a sharepoint profile*’);

var keywordQueryDoc = new query.KeywordQuery(context);
keywordQueryDoc.set_queryText(‘ContentTypeId:*here ContentTypeId*’);
var docProperties = docListQuery.get_selectProperties();
docProperties.add(‘WorkEmail’);

var searchExecutor = new query.SearchExecutor(context);
resultsPerson = searchExecutor.executeQuery(keywordQuery);
resultsDoc = searchExecutor.executeQuery(keywordQueryDoc);

context.executeQueryAsync(onQuerySuccess, onQueryFail);
End

SharePoint REST Services

The REST Services in SharePoint offer nearly the same functionality like JSOM. Furthermore it is easier to use for Developer not coming from the SharePoint world since REST interfaces are standardized. This makes the choice of technology easier than for JSOM.

The REST Services in SharePoint use the Open Data Protocol, which is developed and afterwards standardized by the OASIS (Advancement of Structured Information Standards). ODATA is a protocol for data access and introduces the so called CRUD (Create, Read, Update and Delete) operations. In addition ODATA defines query operations in queries in URL syntax. With that developers get the consistency to develop solutions which work always the same no matter if it’s a 3rd party solution or a SharePoint hosted app. There are several REST endpoints [4] for example search, site, web, user profiles or publishing.

REST services can be used either with POST by using header or by GET method with URL parameter. Data can be returned in JSON or XML format where JSON is the preferred format when using JavaScript. I other situations XML can still be used without any problem.

JSOM AND REST

RestSPArchitektur.gif
Abb. 2: REST Service [4]

Make a call with SharePoint REST Services

The REST Services in SharePoint 2013 are not used like in SharePoint 2010. Even though the interfaces in the path vti_bin can still be used it is not recommended to use them in your applications. REST interfaces lie within the _api path and if you want to query a list for example the URL call can look as follow:

http://sp2013/mySite/_api/lists/getbytitle(‘Employees’)
This URL consists of several parts which work the same for all REST Services in SharePoint.
server, site, query object, method und method parameter.

The first two parameter define the site or the web followed by the object we want to query (in this case lists). In the interface for lists a method is called which gets a list instance by the title of the list.

Search with SharePoint Rest Services

Now Listing 2 concentrates on making a REST search request for a SharePoint hosted app.

Listing 2
var peopleSearch = “B09A7990-05EA-4AF9-81EF-EDFAB16C4E31”;
function searchButton_Click(txt) {
// Querystring zusammensetzen
var spAppWebUrl = decodeURIComponent(getQueryStringParameter(‘SPAppWebUrl’));
var queryUrl = spAppWebUrl + “/_api/search/query?querytext='” + txt + “‘&sourceid='” + peopleSearch + “‘”;
// REST service aufrufen
$.ajax({ url: queryUrl, method: “GET”, headers: { “Accept”: “application/json; odata=verbose” }, success: onRestQuerySuccess, error: onRestQueryError });
}
End

First the URL must be built before the request can be send. The AppWeb URL is retrieved by filtering the corresponding parameter in the current browser URL. Like described before the _api and the query object is used. Because search is used we utilize the search endpoint. Further parameter like querytext and the source ID for people search are used to make the search call. The final URL can look like this:

https://sp2013/SearchDrivenJsomVsCsomApp/_api/search/query?querytext=’Chris’&sourceid=’B09A7990-05EA-4AF9-81EF-EDFAB16C4E31′

In the last code line of Listing 2 the search query is fired with jQuery. The Headers are important to make sure that we get JSON. To get XML you just need to send xml instead of json in the string application/json.

If we analyze the XML and JSON response messages with a tool like Fiddler [3] you can see that the structures semantically are nearly the same. For example the results can be found in the path query/PrimaryQueryResult/RelevantResults. Also notice that the size of the response message is significantly different.

The result is then processed in the success (onRestQuerySuccess) and error (onRestQueryError) function which we defined. The next code snippet shows how to access the returned results with JavaScript and followed by the custom code to render the GUI for the results. In the snippet the second search query (equal to the JSON approach) is fired, represented by the function searchDocuments. This function searches for Documents which are edited by the user with the email assign to the variable workEMail.

Listing 3
function onRestQuerySuccess(data) {
var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
//…render some custom GUI here
searchDocuments(workEMail); }
End

After the user has been retrieved (with the given email) the documents of the user are queried over the REST interface again. The method is similar to the people search, but this time we do not limit this to the people search results source (Listing 4). By giving the content type we want to get and the email of the user we only get documents of a specific list filtered by workEMail. The results are rendered into the HTML document.

Listing 4
function searchDocuments(workEMail) {
var spAppWebUrl = ecodeURIComponent(getQueryStringParameter(‘SPAppWebUrl’));
var queryUrl = spAppWebUrl + “/_api/search/query?querytext=’ContentTypeId:0x0100b19ae5b3c1f54d35a51cf2c95e2090c5* WorkEmail:” + workEMail + “‘”;
$.ajax({ url: queryUrl, method: “GET”, headers: { “Accept”: “application/json; odata=verbose” }, success: onRestDocQuerySuccess, error: onRestQueryError });
}
End

This approach give the same results like making search request with JSOM.

3 Question – not only 3 Answeres

After we know how to place search request with JSOM and REST we can give some tips and answers to the questions we asked in the beginning.

Technology and Plattforms
Which API can and should be used depends upon several requirements. Firstly the platform to use is important. Mainly there are Microsoft .NET framework compatible and non-managed code platforms. If we are in the Microsoft world which uses the .NET framework and an application with .NET is developed then CSOM (Client Side Object Model) written in C# or VB.NET can be used. For that the Microsoft.SharePoint.Client and Micrsoft.SharePoint.Client.Runtime assemblies must be referenced in the project. To use the .NET libraries are a comfortable way to query SharePoint since we do not need to handle request and response messages. The advantages is the object oriented approach with SharePoint and also all the adnvanteges that come with Visual Studio like compilation, debugging and all the features of the .NET framework.

Of course for pure SharePoint Solution we can still use SSOM, which gives the full power of SharePoint. But remember: “With great power comes great responsibility”.

If you do not have CSOM or SSOM available in you platform (like Java or PHP) you can still use REST Services or JSOM.
But one word to JSOM. JSOM is more technology dependent than REST. JSOM is mostly used and works perfectly fine for SharePoint hosted apps. The approach here is similar to CSOM where you are still able to use the object model of SharePoint over an abstraction layer in between without worrying about request handling. Even though it is possible to use JSOM outside of SharePoint but you probably can get stuck easily.

REST services in the contrary can be used from every client and every programming language who support HTTP request. REST endpoints can be used directly inside of the browser. The free choice between JSON and XML makes it also easier to use with non-Microsoft technologies.

Performance
When it comes to performance criteria like number of requests, the amount of data and the time for a round trip must be taken into account. Those metrics can define if a JavaScript application is fast or slow. Intuitively the usability depends very strongly on the response time of the server. No user like to use a software which is running too slow and it doesn’t matter if the interface looks great or how good the results are.

The time for a server round trip depends on the architecture of the used API, the quality of the internet connection (ping and bandwidth) and the performance of the server to handle the requests. Because developer do not have control over all the named criteria the reason for slow performance is not always easy to manage.

But when it comes to the number of requests the JSOM API definitely has a solution for that. A main feature of JSOM is that you can make dozens of request (search request, query list, create a page) with just one HTTP request. So JSOM supports batch processing which REST cannot provide. Basically it is defined for REST-APIs but in the current implementation there is not batch processing in SharePoint. In our code example JSOM only needs one server round trip to make that request, but REST needs two. If you have apps which for example have to create several of list items for a SharePoint list the number of request can easily raise for the REST service.

On the other hand if we compare the requests with Fiddler you can see that JSOM has a great data overhead for every request because it consist XML. But REST only makes simple URL calls with some POST headers. What we want to retrieve is mainly given with the URL.

So basically it come down to the question: What do I want to achieve with my code? Does my application have to make a lot of request which I want to handle in one server round trip or are there only a few HTTP requests to make?
Long story short: Do I have a chatty app, take JSOM. Is my app more silent, REST services are my choice.

Experience and Conclusions

The last question to ask is: What are my experience as a developer? People not coming from SharePoint find it much easier to use REST. They do not have to handle CAML-Queries or cope with the structure of the JSOM API. But if you are used to SSOM, JSOM will be easier to use.

The fact that JSOM is derived from the proprietary SSOM code and REST is a widely known standard makes it generally easy to get access into the SharePoint app world.

So in short choice of API depends on the following points:
• Number of server round trips
• Experience with SharePoint and your time resources
• Range of non-SharePoint technologies used

Links & Literature
[1] http://msdn.microsoft.com/en-us/library/office/jj860569.aspx
[2] http://msdn.microsoft.com/en-us/library/office/jj193034.aspx
[3] http://www.telerik.com/fiddler
[4] http://msdn.microsoft.com/en-us/library/office/fp142380.aspx

CSOM And REST API In Share Point 2013 By Sahil Malik

About the authors Sebastian Schütze & Chris Spettmann;

Chris Spettmann photoChris Spettmann (cspettmann@fum.de, @cspettmann) is working as a SharePoint consultant at the Fritz & Macziol Group. He got longstanding expertise in SharePoint und .Net projects. Beside consulting and development of SharePoint solutions and apps he got wide interessts in Windows Phone and Windows 8 app development.

Sebasitan _schuetzeSebastian Schütze (sschuetze@fum.de, @RazorSPoint) is working as a SharePoint consultant at the Fritz & Macziol Group. He dedicated his passion to web development and with that SharePoint development. Since more than seven years he is also working as web developer and tries to spread the word about best practices for development in general and web development in particular.

Check out last years European SharePoint Conference video:

European SharePoint Conference 2015 takes places in Stockholm Sweeden from 9-12 November 2015. View Programme>>

Share this on...

Rate this Post:

Share: