SPA Series: SharePoint REST versus SharePoint CSOM
Using REST to access data within SharePoint has advantages over using CSOM, the Client-side SharePoint Object Model. One important reason for me is a way smaller footprint in required libraries. For CSOM we need to use a bulky set of proprietary libraries provided by SharePoint. With REST we can use any library to do http requests. A good must read blog post on SharePoint CSOM versus REST is written by Andrew Connell, and he has a lot of good reasons in favor of REST. Another reason is that with REST we can use sp-rest-proxy, but that will be the topic of the next blog post.
In the first post of our SPA Series we described a simple web app that displayed the title of the hosting SharePoint site using CSOM.
The file index.aspx using CSOM has the following content:
End code of file index.aspx using CSOM.
We can also use REST to display the title of the hosting SharePoint site. When using SharePoint REST almost all examples use the jQuery Ajax functions. I prefer to use the new web standards like fetch() in combination with ES6 promises. Because not all browsers support fetch() and promises yet I included polyfills for these web standards. In the future we do not even have to include these polyfills anymore.
The file index.aspx using REST has the following content:
End code of file index.aspx using REST.
There are a few interesting things to notice in the above REST example:
- The code is hard-coding the API on path http://localhost:8081. This is the url I configured for sp-rest-proxy, a proxy tool I use for local development while accessing real SharePoint data. more on this in the next blog post.
- We need to configure a header Accept with the value application/json; odata=verbose. This was the only json output format that gave (almost) the same results through sp-rest-proxy and on the real SharePoint.
- In the point above I said "almost" the same value... the proxy returns a json containing an extra level body. See the issue I posted on the sp-rest-proxy repository.
- I included a helper function sp_api_get_json() that return the correct json content in a promise.
- In the fetch call we need to configure to include credentials, otherwise we get an authentication error on real SharePoint. It works without it on the sp-rest-proxy, because sp-rest-proxy handles the proxy and authentication.