left-icon

SharePoint 2013 App Model Succinctly®
by Fabio Franzini

Previous
Chapter

of
A
A
A

CHAPTER 8

REST/OData Service

REST/OData Service


Besides letting us access the SharePoint Client.svc service through the CSOM, SharePoint 2013 introduces the possibility of accessing it directly using REST mode, as shown in Figure 29.

SharePoint client API

  1. SharePoint client API

The REST interface gives us access to all objects and all transactions that are made available through the CSOM.

This allows us to open the SharePoint API to potentially all technologies that support the HTTP protocol and allows us to interpret strings.

Note: REST-based applications use HTTP requests to send data (create and/or update), read data (query) and delete data using HTTP verbs to make these operations (GET, POST, PUT and DELETE/MERGE).

For REST access to SharePoint 2013, we must make HTTP calls directly to the address Client.svc or service using the new alias _api.

The SharePoint REST service implements the specifications of OData to make queries with sorts, filters, etc.

Run REST Calls in SharePoint Apps

The easiest way to test a called REST in SharePoint is using the browser.

For example, if we go to this URL
https://sp2013appdevsuccinctly.sharepoint.com/_api/web/lists through the browser, we will see a result like the one shown in Figure 30:

Call REST API from browser

  1. Call REST API from browser

Of course, we can use a browser to test a call’s GET, but it is easier to use a tool like Fiddle to test our REST calls and see what data is sent and received. This is the best way to work with REST.

When we use the SharePoint REST interface, we must be careful about how we use it. There can be much difference between making calls from C# code instead of JavaScript, and it also makes a difference in the type of application that we are achieving and what type of hosting that the app will have. Furthermore, we must ensure that our app is authenticated to access data from SharePoint.

If our app is hosted on SharePoint, it then performs the client-side code in a context that allows a previously authenticated user to access it.

jQuery.ajax({

    URL: "http://<site URL>/_api/web/lists/GetByTitle('Test')",

    type: "GET",

    headers: {

        "accept": "application/json;odata=verbose",

        "content-type": "application/json;odata=verbose",

    },

    success: successFunction,

    error: successFunction

});

If the app is a self-hosted provider type, then run the server-side code (.NET or other). In this case, we should use OAuth in order to pass the access token each time we want to make a REST call to SharePoint:

var site = "http://site/";

var accessToken = "";

HttpWebRequest endpointRequest =

    (HttpWebRequest)HttpWebRequest.Create(site + "/_api/web/lists");

endpointRequest.Method = "GET";

endpointRequest.Accept = "application/json;odata=verbose";

endpointRequest.Headers

    .Add("Authorization", "Bearer " + accessToken);

HttpWebResponse endpointResponse =

    (HttpWebResponse)endpointRequest.GetResponse();

This is an example of C# code that does the same thing; it retrieves the lists on a SharePoint site. To make calls properly, we must also pass authentication information, passing the AccessToken authentication.

Regardless of the type of language/platform that we use, we need to understand how to create URLs that allow us to achieve the resources with which to operate.

As mentioned at the beginning of the book, the SharePoint REST API is based on the OData Protocol to define the syntax with which to create URLs. But how does OData do this?

Introduction to OData in SharePoint

OData is an HTTP-based web protocol that allows us to query and manipulate data. OData defines operations on resources using the REST paradigm and identifies those resources using a standard URI syntax. The data is transferred using AtomPub or JSON standards. Also, the OData Protocol defines some standard conventions to support the exchange of information and query schema.

Each query is submitted with a unique URL, and the results can be cached by proxy servers that increment the performance.

Table 3: OData maps CRUD operations to HTTP verbs

HTTP Verb

Operations

GET

Used to read data.

POST

Used to insert new data. Any properties that are not required are set to their default values. If you attempt to set a read-only property, the service returns an exception.

PUT and MERGE

Used for updates.

MERGE is used when you want to update to some properties of an object and you want other properties to maintain their current values.

PUT is used when you want to replace an item. All properties that are not specifically mentioned in the call are set with default values.

DELETE

Used to delete the object and, in the case of recyclable objects, this results in a Recyclable operation.

Moreover, the methods of CSOM will be mapped into:

  • GET for Navigator operations (e.g., web.getByTitle)
  • POST, PUT, MERGE or DELETE for Service operations

Take, for example, this URL:

http://server/_api/web/lists/?$orderby=title

This URL, if invoked by calling GET, allows us to return a list of the lists in a website, sorted by title.

As all URLs in OData, this one consists of three basic parts:

  • Service root URI: URL of Service (http://server/_api)
  • Resource path: Identifies the resource on which you want to operate (web/lists)
  • Query string options: These are the options for queries (?$orderby=title)

Now take, for example, a different URL:

http://server/_api /web/lists/getByTitle('Announcements')

Let's look at how the resource is not changed in the URL (../lists), but is changed after the resource has been added. A part of the path, in this case indicating an operation to be performed, getByTitle, passes the title of the list to which you want find information.

Table 4: Examples of Resource Paths

Resource Path

Operations

web/title

Title of current site.

 web/lists(guid'<list id>')

List with guid.

web/lists/getByTitle('Task')/items

The items in the Task list.

web/lists/getByTitle('Task')/fields

The fields in the Task list.

web/GetFolderByServerRelativeUrl('/Shared Documents')

The root folder of the “Shared Documents” library.

web/GetFolderByServerRelativeUrl('/Shared Documents')/Files('todo.txt')/$value

The content of todo.txt file from the “Shared Documents” library.

By default, the data is returned as XML in AtomPub format as extended by the OData format, but you can retrieve the data in JSON format by adding the following accept header to the HTTP request: “accept: application/json;odata=verbose”.

Through query string parameters we can apply filters, sort, and indicate the number of items to return:

Table 5: Query string options

Query String Option

Operations

$select

Specifies which fields are included in the returned data.

 $filter

Specifies which members of a collection, such as the items in a list, are returned.

$orderby

Specifies the field that’s used to sort the data before it’s returned.

$top

Returns only the first n items of a collection or list.

$skip

Skips the first n items of a collection or list and returns the rest.

$expand

Specifies which projected fields from a joined list are returned.

Here are some examples:

  • Select the column Title:

_api/web/lists/getByTitle('MyList')/items?$select=Title

  • Filter by column Author:
    _api/web/lists/getByTitle('MyList')/items?$filter=Author eq 'Fabio Franzini'
  • Sort by the column Title ascendingly:
    _api/web/lists/getByTitle('MyList')/items?$orderby=Title asc
  • Get the first five items by jumping 10 items:

_api/web/lists/getByTitle('MyList')/items?$top=5&$skip=10

  • Select the column Title and column Title for a LookUp, stating explicitly to expand the item LookUp:
    _api/web/lists/getByTitle('MyList')/items?$select=Title,LookUp/Title&$expand= LookUp

So far, the examples we have seen have always taken GET calls into consideration to perform the query.

In case we want to instead insert or modify data, as well as change the HTTP verb for the request, we must pass a value called Form Digest, which can be found in two ways:

  • By calling the URL _api/contextinfo always using an HTTP GET call.
  • By using a hidden field called __REQUESTDIGEST contained in all SharePoint pages.

Usage Examples in JavaScript

Reading a List

jQuery.ajax({

    URL: "http://<site URL>/_api/web/lists/GetByTitle('Test')",

    type: "GET",

    headers: {

        "accept": "application/json;odata=verbose",

        "content-type": "application/json;odata=verbose",

    },

    success: successFunction,

    error: successFunction

});

Creating a New List

jQuery.ajax({

    URL: "http://<site URL>/_api/web/lists",

    type: "POST",

    data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' },

        'AllowContentTypes': true,

        'BaseTemplate': 100,

        'ContentTypesEnabled': true,

        'Description': 'My list description',

        'Title': 'Test' }),

    headers: {

        "accept": "application/json;odata=verbose",

        "content-type": "application/json;odata=verbose",

        "content-length": <length of post body>,

        "X-RequestDigest": $("#__REQUESTDIGEST").val()

    },

    success: successFunction,

    error: successFunction

});

Editing a List

jQuery.ajax({

    URL: "http://<site URL>/_api/web/lists/GetByTitle('Test')",

    type: "POST",

    data: JSON.stringify({

        '__metadata': { 'type': 'SP.List' },

        'Title': 'New title'

    }),

    headers: {

        "X-HTTP-Method": "MERGE",

        "accept": "application/json;odata=verbose",

        "content-type": "application/json;odata=verbose",

        "content-length": <length of post body>,

        "X-RequestDigest": $("#__REQUESTDIGEST").val(),

        "IF-MATCH": "*"

    },

    success: successFunction,

    error: successFunction

});

The value of the IF-MATCH key in the request headers is where you specify the etag value of a list or list item. This particular value applies only to lists and list items, and it is intended to help you avoid concurrency problems when you update those entities. The previous example uses an asterisk (*) for this value, and you can use that value whenever you don’t have any reason to worry about concurrency issues. Otherwise, you should obtain the etag value or a list or list item by performing a GET request that retrieves the entity. The response headers of the resulting HTTP response will pass the etag as the value of the ETag key. This value is also included in the entity metadata. The following example shows the opening <entry> tag for the XML node that contains the list information. The m:etag property contains the etag value.

Summary

REST is much simpler to use compared to CSOM. Always use the most convenient technology for what you are doing.

If you are using .NET code, for example, because the app is provider-hosted, it will be more convenient to use the CSOM because it is a strongly typed model that is suitable to be used with managed code.

If you are writing JavaScript code, it may be more convenient, for example, to use REST because we can reuse any experience in AJAX calls with jQuery and also because the result there is already provided, using JSON in JavaScript objects.

This is not to say that REST is for use only with JavaScript and that CSOM is for use only with .NET. Rather, you should always evaluate the scopes of use before choosing a method to work with.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.