Chapter 9. The new SharePoint REST API

Another important introduction in Microsoft SharePoint 2013 is the REST (Representational State Transfer) API. The REST API gives any platform access to many key objects, properties, and methods that were previously available only via the Client Object Model for Microsoft .NET, Microsoft Silverlight, and JavaScript. In fact, the new API provides a rich set of REST URIs that you can access via HTTP and XML/JSON (JavaScript Object Notation) for consuming nearly every capability of the Client Object Model. All you need is a third-party technology capable of consuming REST services. In this chapter, you will learn about the architecture of this new REST API, as well as how to manage the most common tasks for everyday programming needs.

Introducing the REST API

The overall architecture of the REST API is based on the client.svc WCF service, which serves the classic Client Object Model, but implements an OData-compliant endpoint, too.

More Info

OData stands for Open Data Protocol, and you can read more about it at http://www.odata.org/.

You can access the REST API at the relative URL _api/ of any SharePoint site. For example, to access the API targeting the root site collection of a target web application, you can open your browser and navigate to a URL such as the following:

http://devbook.sp2013.local/_api/site

where devbook.sp2013.local in the example is the host name of a sample web application. The previous URL is just an alias to the real URL, which is

http://devbook.sp2013.local/_vti_bin/client.svc/site

As you can see, the real URL corresponds to client.svc, which was discussed in Chapter 7 It is just an additional RESTful endpoint that publishes the capabilities of the classic Client Object Model through the OData protocol. By browsing to such a URL, you will see that the result is an XML representation—based on the ATOM protocol—of information about the current site collection. (When using Internet Explorer, be sure to disable the feed-reading view in the browser’s content properties.) At the beginning of the ATOM response, there is a list of links targeting many additional URLs for accessing information and APIs related to the current site collection. At the end of the response, there are some properties specific to the current site collection.

Here are some other commonly used URLs of APIs, which are useful while developing on SharePoint:

  • http://devbook.sp2013.local/_api/web. Use to access the information about the target website.

  • http://devbook.sp2013.local/_api/web/lists. Use to access the collection of lists in the target website.

  • http://devbook.sp2013.local/_api/web/lists/GetByTitle(’Title of the List’). Use to access the information of a specific list instance, selected by title.

  • http://devbook.sp2013.local/_api/search. Use to access the Search query engine.

As you can see, the root of any relative endpoint is the _api/ trailer, which can be followed by many API targets (as the following section will illustrate) and correspond to the most common artifacts of SharePoint. As with many REST services, you can communicate with this REST API not only by the browser, invoking URLs with the HTTP GET method, but also by using a client capable of communicating over HTTP and parsing ATOM or JSON responses. In fact, depending on the HTTP Accept header provided within the request, the REST service will provide ATOM (Accept: application/atom+xml) or JSON (Accept: application/json;odata=verbose) answers. By default, REST service responses are presented by using the ATOM protocol, according to the OData specification.

Depending on the HTTP method and headers (X-Http-Method) you use, you can take advantage of various capabilities of the API, taking advantage of a complete CRUDQ (create, read, update, delete, and query) set of methods. The available HTTP methods and headers are:

  • GET. These requests typically represent read operations, which apply to objects, properties, or methods, which return information.

  • POST. Without any additional X-Http-Method header, this method is used for creation operations. For example, you can use POST to post a file to a library, to post an item to a list, or to post a new list definition for creation in a target website. While invoking POST operations against a target object, any property that is not required and is not specified in the HTTP invocation will be set to its default value. If you provide a value for a read-only property, you will get an exception.

  • PUT, PATCH, and MERGE. These requests are used for update operations. You can use PUT to update an object. While invoking PUT operations, you should specify all writable properties. If any property is missing, the operation could fail or could set the missing properties back to their default values. The PATCH and MERGE operations are based on the POST method, with the addition of an X-Http-Method header with a value of PATCH or MERGE. They are equivalent, and you should always use the former, because the latter is provided for backward compatibility only. Like PUT, PATCH and MERGE handle update operations. The big difference is that with PATCH and MERGE, any writeable property that is not specified will retain its current value.

  • DELETE. These requests are for deleting an item and can be implemented with POST, plus the additional X-Http-Method header with a value of DELETE. If you invoke this operation against recyclable objects, SharePoint will move them to the Recycle Bin.

A sample VBScript file for reading the title of a list instance in a target website using the REST API demonstrates how to use the new REST API. The sample is intentionally written using a legacy programming language, specifically VBScript in a .vbs file, to demonstrate that the REST APIs are available to any platform and any technology landscape. The code reads the title of a list instance in a target website.

The sample code invokes a GET method to begin creating and configuring a Microsoft.XMLHTTP object for requesting a specific list instance by title. The result will be an XML (ATOM) representation of the list information, which will look like the excerpt in An excerpt of the XML (ATOM) representation of the list information of a specific list instance. Near the end of An excerpt of the XML (ATOM) representation of the list information of a specific list instance, notice the XML node with a qualified name value of d:title. Highlighted in bold, this represents the Title property of the list, and it is associated with a namespace that has a prefix value of d. The namespace URI of that namespace is http://schemas.microsoft.com/ado/2007/08/dataservices and corresponds to the well-known ADO.NET Data Services namespace URI.

You can achieve the same goal with any other programming or scripting language capable of communicating over HTTP and managing ATOM or JSON answers. For example, consider A Windows Store app consuming the collection of lists of a site collection using the REST API, which is written in C#: the click event handler of a Button control within a Microsoft Windows Store app for Windows 8 consumes the collection of lists available in a target website, using the HttpClient class of the Windows Runtime. Notice the code for creating an HttpClient instance configured to use integrated security and to accept JSON responses (highlighted in bold).

More Info

For further information about developing Windows Store Apps for Windows 8, consult Build Windows 8 Apps with Microsoft Visual C# and Visual Basic Step by Step, by Luca Regnicoli, Paolo Pialorsi, and Roberto Brunetti (Microsoft Press, 2013).

Eventually, and for testing purposes, you can also play with tools like Fiddler Composer (http://www.fiddler2.com) in order to test the behavior and the responses provided by the REST API.

API reference

Every method offered by the REST API can be invoked using a reference URL, which is made according to the schema illustrated in Figure 9-1.

A diagram defining the tokens that compose the URL of any REST API endpoint. The tokens are hostname (the web application host name), site (an optional site collection), namespace (the API name), object, property, indexer, and method (four operation options).

Figure 9-1. The schema of the URL of any REST API published by SharePoint 2013.

The protocol moniker can be http or https, depending on the web application configuration. The {hostname} argument is clearly the host name—which will eventually include the fully qualified domain name—of the target web application. The subsequent {site} is the target site collection and is optional, because you could target the root site collection. Following the _api trailer is a {namespace} argument that corresponds to one of the target families of APIs. Table 9-1 lists some of the main available namespaces. The URL ends with a reference to an {object}, a specific {property}, an {indexer}, or a {method} call. Indexers will be followed by a numeric {index} argument, while method calls could be followed by {parameter} arguments. For some operations, the arguments can be provided as a JSON object in the HTTP POST request body, as well.

Table 9-1. The main namespaces available in URLs of the REST API

Namespace

Target

site

The current site collection. Can be used to browse site collection properties and configuration, and corresponds to the Microsoft.SharePoint.Client.Site class of the Client-Side Object Model (CSOM).

web

The current website. Can be used to browse website properties, configuration, and contents, and corresponds to the Microsoft.SharePoint.Client.Web class of the CSOM.

SP.UserProfiles.PeopleManager

The APIs for working with the User Profile service within the context of the current user, and corresponds to the Microsoft.SharePoint.Client.UserProfiles.PeopleManager class of the CSOM.

ContextInfo

Retrieves the context of the current session, which corresponds to the serialization of an object of type Microsoft.SharePoint.SPContextWebInformation.

search

The search engine of SharePoint. Can be used to search content and suggestions.

publishing

The publishing engine. Can be used to manage the publishing capabilities.

social.feed

The social capabilities. Includes operations for accessing social feeds, followers, followed contents, and so on.

The REST API offers about 2,000 classes and more than 6,000 members, which are available throughout the hierarchy of objects of the CSOM, using the preceding namespaces as root objects. The first three namespaces are easy to manage and understand, because you simply need to reference the corresponding CSOM types and compose the request URLs. For example, the Site class of the Microsoft.SharePoint.Client namespace offers a property with name Owner and type User. Using the REST API, you can invoke the GET verb to retrieve the following URL:

http://devbook.sp2013.local/_api/site/owner

Moreover, for invoking the GetWebTemplates method, which accepts the culture parameter, you can invoke the following URL:

http://devbook.sp2013.local/_api/site/GetWebTemplates(1033)

The value 1033 provided is the en-US culture. Consult the CSOM online reference (http://msdn.microsoft.com/en-us/library/ee544361.aspx) to see all the available properties, methods, and members in general.

Notice that for security reasons, all the operations that modify data will require a security form digest with a name of X-RequestDigest in the HTTP request headers. To retrieve the value needed for this header, you have a couple of options:

  • Working in JavaScript, inside a web page directly hosted in SharePoint or a SharePoint-hosted app, you can retrieve the value of the digest from a hidden INPUT field with an ID value of __REQUESTDIGEST. For example, using jQuery, you can reference the field with the following syntax: $(“# __REQUESTDIGEST”).val().

  • Working in any other context, you can invoke (using the POST method) the ContextInfo namespace and retrieve the form digest value from the ATOM or JSON response. By default, the form digest retrieved through this method will expire in 1,800 seconds.

The JSON output of the ContextInfo method invocation shows the JSON output of the ContextInfo method invocation. The form digest value is highlighted in bold.

A code excerpt for invoking the EnsureUser method of a target website via the REST API provides a code excerpt of a Windows Store app for Windows 8 that invokes the EnsureUser method of a target website, providing a value for the form digest HTTP header after extracting that value from the ContextInfo method.

The other namespaces (search, publishing, and social.feed, for instance) provide some useful operations for managing the search engine, the publishing capabilities, and the social feeds.

Querying data

Another useful capability of the new REST API is the support for OData querying. Every time you invoke an operation that returns a collection of entities, you can also provide an OData-compliant set of query string parameters for sorting, filtering, paging, and projecting that collection. For example, imagine querying the list of items available in a document library. The URL would be:

http://hostname/_api/web/lists/GetByTitle('Documents')/Items

In case you are interested in the list of files in the root folder of the library, the corresponding URL is:

http://hostname/_api/web/lists/GetByTitle('Documents')/RootFolder/Files

According to the OData specification, you can append the following querying parameters to the URL:

  • $filter. Defines partitioning criteria on the current entity set. For example, you can provide the query string argument $filter=substringof(’LINQ’,Name)%20eq%20true to retrieve documents with LINQ in their file name.

  • $select. Projects only a subset of properties (fields) of the entities in the current entity set. For example, you can provide a value of $select=Name,Author to retrieve only the file name and the author of every file in the entity set.

  • $orderby. Sorts data returned by the query. You can provide query string arguments with a syntax like $sort=TimeLastModified%20desc,Name%20asc to sort files descending by TimeLastModified and ascending by Name.

  • $top. Selects the first N items of the current entity set. Use the syntax &top=5 to retrieve only the first five entities from the entity set.

  • $skip. Skips the first N items of the current entity set. Use the syntax $skip=10 to skip the first 10 entities of the entity set.

  • $expand. Automatically and implicitly resolves and expands a relationship between an entity in the current entity set and another related entity. For example, you can use the syntax $expand=Author to retrieve the author of a file.

As you have already seen in the previous example, the arguments provided to an OData query must be URL encoded because they are passed to the query engine via REST, through the URL of the service. Space characters must be converted into %20, for example, and any other nonalphanumeric characters must be converted into their corresponding encoded values.

In the previous examples, you saw just a quick preview of the available functions and operators for filtering entities with OData. Table 9-2 provides the full list of the available logical operations defined in the OData core specification. You can also read the official core documentation of OData at http://www.odata.org/media/30002/OData.html. The operators in bold are supported by the SharePoint 2013 REST API.

Table 9-2. The logical operations available in the OData core specification

Operator

Description

Example

eq

Equal

/Suppliers?$filter=Address/City eq ’Redmond’

ne

Not equal

/Suppliers?$filter=Address/City ne ’London’

gt

Greater than

/Products?$filter=Price gt 20

ge

Greater than or equal

/Products?$filter=Price ge 10

lt

Less than

/Products?$filter=Price lt 20

le

Less than or equal

/Products?$filter=Price le 100

and

Logical and

/Products?$filter=Price le 200 and Price gt 3.5

or

Logical or

/Products?$filter=Price le 3.5 or Price gt 200

not

Logical negation

/Products?$filter=not endswith(Description,’milk’)

There are also some arithmetic operators, which are listed in Table 9-3.

Table 9-3. The arithmetic operators available in the OData core specification

Operator

Description

Example

add

Addition

/Products?$filter=Price add 5 gt 10

sub

Subtraction

/Products?$filter=Price sub 5 gt 10

mul

Multiplication

/Products?$filter=Price mul 2 gt 2000

div

Division

/Products?$filter=Price div 2 gt 4

mod

Modulo

/Products?$filter=Price mod 2 eq 0

None of the arithmetic operators defined in the OData core specification are supported by the SharePoint 2013 REST API. While defining a query, you can compose operators using parentheses—()—to group elements and define precedences. For example, you can write the following:

/Products?$filter=(Price sub 5) gt 10

Lastly, in queries for partitioning data, you can also use functions for strings, dates, math, and types. Table 9-4 provides the full list of functions available in the OData specification. Again, the operators highlighted in bold are those supported by SharePoint 2013 REST API.

Table 9-4. The functions available in the OData core specification for querying entities

Function

Description

Example

bool substringof(string searchString, string searchInString)

Returns a Boolean value stating whether the value provided in the first argument is a substring of the second argument. Can be used as a replacement for the contains method.

substringof(’Alfreds’,CompanyName)

bool endswith(string string, string suffixString)

Returns a Boolean value declaring whether the string provided in the first argument ends with the string provided in the second argument.

endswith(CompanyName,’Futterkiste’)

bool startswith(string string, string prefixString)

Returns a Boolean value declaring whether the string provided in the first argument starts with the string provided in the second argument.

startswith(CompanyName,’Alfr’)

int length(string string)

Returns an integer value representing the length of the string provided as the argument.

length(CompanyName) eq 19

int indexof(string searchInString, string searchString)

Returns an integer value representing the index of the string provided in the second argument, which is searched within the string provided in the first argument.

indexof(CompanyName,’lfreds’) eq 1

string replace(string searchInString, string searchString, string replaceString)

Replaces the string provided in the second argument with the string provided in the third argument, searching within the first string argument.

replace(CompanyName,’ ’, ’’) eq ’AlfredsFutterkiste’

string substring(string string, int pos)

Returns a substring of the string provided in the first argument, starting from the integer position provided in the second argument.

substring(CompanyName,1) eq ’lfreds Futterkiste’

string substring(string string, int pos, int length)

Returns a substring of the string provided in the first argument, starting from the integer position provided in the second argument and stopping after a number of characters provided in the third integer argument.

substring(CompanyName,1, 2) eq ’lf’

string tolower(string string)

Returns a string that is the lowercase conversion of the string provided as the string argument.

tolower(CompanyName) eq ’alfreds futterkiste’

string toupper(string string)

Returns a string that is the uppercase conversion of the string provided as the string argument.

tolower(CompanyName) eq ’alfreds futterkiste’

string trim(string string)

Returns a string trimmed of spaces, based on the string provided as the argument.

trim(CompanyName) eq ’Alfreds Futterkiste’

string concat(string string1, string string2)

Returns a string that is the concatenation of the two string arguments provided.

concat(concat(City,’, ’), Country) eq ’Berlin, Germany’

int day(DateTime datetimeValue)

Returns an integer that corresponds to the day of the datetime value provided as the argument.

day(BirthDate) eq 8

int hour(DateTime datetimeValue)

Returns an integer that corresponds to the hours of the datetime value provided as the argument.

hour(BirthDate) eq 1

int minute(DateTime datetimeValue)

Returns an integer that corresponds to the minutes of the datetime value provided as the argument.

minute(BirthDate) eq 0

int month(DateTime datetimeValue)

Returns an integer that corresponds to the month of the datetime value provided as the argument.

month(BirthDate) eq 12

int second(DateTime datetimeValue)

Returns an integer that corresponds to the seconds of the datetime value provided as the argument.

second(BirthDate) eq 0

int year(DateTime datetimeValue)

Returns an integer that corresponds to the year of the datetime value provided as the argument.

year(BirthDate) eq 1948

double round(double doubleValue)

Returns a double number that is the rounded value of the double value provided as the argument.

round(Freight) eq 32

decimal round(decimal decimalValue)

Returns a decimal number that is the rounded value of the decimal value provided as the argument.

round(Freight) eq 32

double floor(double doubleValue)

Returns a double number that is the floor value of the double value provided as the argument.

floor(Freight) eq 32

decimal floor(decimal datetimeValue)

Returns a decimal number that is the floor value of the decimal value provided as the argument.

floor(Freight) eq 32

double ceiling(double doubleValue)

Returns a double number that is the ceiling value of the double value provided as the argument.

ceiling(Freight) eq 33

decimal ceiling(decimal datetimeValue)

Returns a decimal number that is the ceiling value of the decimal value provided as the argument.

ceiling(Freight) eq 33

bool IsOf(type value)

Returns a Boolean value stating if the target entity is of the type provided as the argument.

isof(’NorthwindModel.Order’)

bool IsOf(expression value, type targetType)

Returns a Boolean value stating if the expression provided as the first argument, is of the type provided as the second argument.

isof(ShipCountry,’Edm.String’)

Based on all the information provided in previous paragraphs, you should now be able to understand the following query:

http://devbook.sp2013.local/_api/web/lists/GetByTitle(Documents')/RootFolder/Files?$expand=Author&$select=Name,Author,TimeLastModified&$sort=TimeLastModified%20desc,Name&$skip=20&$top=10&$filter=substringof('Chapter',Name)%20eq%20true

You can disassemble and decode the query string parameters with the information provided in Table 9-5.

Table 9-5. The sample query string parameters explained

Query part

Explanation

$expand=Author

Expand the related object author while retrieving the documents.

$select=Name,Author,TimeLastModified

Retrieve the fields name, author, and time last modified.

$sort=TimeLastModified desc,Name

Sort the output descending by TimeLastModified and ascending by Name.

$skip=20

Skip the first 20 items of the result set (the first two pages of 10 items).

$top=10

Retrieve only the first 10 items of the result set (the third page of 10 items).

$filter= substringof(’Chapter’,Name) eq true

Retrieve only files with a file name that contains the literal Chapter.

More Info

For quick testing and definition of OData queries, you can use LINQPad, which is a smart tool available at the following URL: http://www.linqpad.net.

If you are working with the .NET Framework, the OData client library already creates such queries for you, allowing you to write LINQ queries on the consumer side. If you are working with any other development technology, however, you do need to understand and write this kind of queries.

Managing data

Creating, updating, deleting, and otherwise managing entities using OData and the REST API is relatively simple as long as you remember a few rules. First, as you’ve already seen, you must provide the X-RequestDigest HTTP header whenever you want to change some data. Second, when managing lists and lists items, you need to avoid concurrency conflicts by specifying an additional HTTP header with the name IF-MATCH, which assumes a value called ETag. To avoid concurrency conflicts, read the ETag value by retrieving the target entity (list or list instance) with a GET method. The ETag value will be included in the response HTTP headers and in the response content, regardless of whether it is formatted in ATOM or JSON. A sample set of HTTP response headers returned while querying a list instance via the REST API includes a sample set of HTTP response headers returned by SharePoint 2013 while selecting a list instance via the REST API. The ETag header is highlighted in bold.

Note

The IF-MATCH header applies only to lists and list items and can assume a value of * for situations where you do not care about concurrency and merely want to force your action.

The code excerpt of the JavaScript function in A sample code excerpt to update the title of a list item using JavaScript and the REST API updates the title of an item using the REST API and provides a value for the ETag parameter.

Executing as soon as the DOM document is ready, A sample code excerpt to update the title of a list item using JavaScript and the REST API first configures both the app web URL and the host web URL. Then it configures a scripting file (SP.RequestExecutor.js), which will be discussed in the “Cross-domain calls” section, which follows. After startup, the sample code requests the ContextInfo via a POST request, in order to extract a valid value for the form digest. If your code runs inside a SharePoint-hosted app, you can simply read the form digest value from the current page (a hidden field with name __REQUESTDIGEST). After retrieving the form digest, the sample gets the item to update, in order to access its ETag value. Lastly, the code runs a POST request against the target item URI, providing the JSON serialization of the changes to apply, the form digest, and the ETag.

Later, in the “Common REST API usage” section, you will see many samples based on the basic concepts demonstrated here. For now, however, notice that the JavaScript code for invoking the REST API uses an object of type SP.RequestExecutor to invoke the service endpoints, instead of a classic jQuery.Ajax method. In the next section, “Cross-domain calls,” you will learn how it works.

One last thing to understand about data management is how the REST API behaves in case of a concurrency conflict. Remember, providing the ETag value simply enables you to identify and manage conflicts; it does not prevent you from experiencing them, unless you provide a value of * for the IF-MATCH header. For example, imagine that while you’re executing the code of A sample code excerpt to update the title of a list item using JavaScript and the REST API, someone else changes the same target item, confirming the updates before the execution of your code. In a real scenario, you should retrieve the ETag value as soon as the user starts editing the target item, and you should provide it back to the server while saving your changes. Thus, you could have a short-term concurrency conflict. Every time someone changes an item and saves it, the ETag value will change. It is a numeric value, and it will increment by 1 unit. If a conflict does occur, the update or delete action will fail, and your HTTP request will get back a 412 HTTP status code, which is the Precondition Failed status. Moreover, in the response body, you will find an XML or JSON representation of the error. For example, the JSON response error message will look like the following excerpt:

{"error":{"code":"-1, Microsoft.SharePoint.Client.ClientServiceException","message":{"lang":"en-US","value":"The request ETag value '"4"' does not match the object's ETag value '"5"'."}}}

You can find this object serialized inside the data argument of the function invoked if the HTTP request fails due to a concurrency conflict, and the errorCode variable will assume a value of -1002. In your custom code, you should catch this kind of exception and prompt the user with a concurrency conflict error, and eventually download the update item from SharePoint to let the user compare data and make a choice.

Cross-domain calls

When developing SharePoint apps, you typically need to make cross-domain JavaScript calls between the app web and the host web. Because the domain of the app web is always different from the domain of the host web, however, this can cause complications. Specifically, browsers prohibit this kind of behavior by default in an effort to avoid cross-domain attacks and their related security issues. Luckily, SharePoint 2013 provides a JavaScript library to help you satisfy the browsers and keep the calls flowing: the SP.RequestExecutor.js library.

Found in the _layouts/15 folder of every SharePoint site, the SP.RequestExecutor.js library provides out-of-the-box capabilities to make cross-domain calls against trusted and registered domains. When you instantiate the library’s SP.RequestExecutor type in your client-side code, it uses a hidden IFRAME element, together with some POST messages and a proxy page (AppWebProxy.aspx) to enable you to make highly secure calls—even cross-domain calls.

In A sample code excerpt to update the title of a list item using JavaScript and the REST API, the startup code adds a reference to the library for making cross-domain calls. Then it creates an instance of the SP.RequestExecutor type, providing the URL of the app web in the object constructor. Behind the scenes, the object injects an IFrame rendering the AppWebProxy.aspx page, which calls the host web. When the call to the host web completes, the client instance of the SP.RequestExecutor retrieves the result from the IFrame and provides it to the calling app. Figure 9-2 diagrams this process.

A diagram of a cross-domain call based on the SP.RequestExecutor.js library. The app web downloads the SP.RequestExecutor.js file from SharePoint. Then that JavaScript file emits an IFrame into the app, including the AppWebProxy.aspx page taken from the host web. The AppWebProxy.aspx page makes a request to the host web domain. The RequestExecutor code retrieves the result and passes it back to the app.

Figure 9-2. The steps of a cross-domain call using the SP.RequestExecutor.js library.

To use the SP.RequestExecutor.js library while invoking the REST API, you need to create an instance of the SP.RequestExecutor type. In addition, you must invoke the executeAsync method and provide the necessary arguments, including the following:

  • url. Represents the target URL of the REST API. While using the code from an app web, you can provide a reference to the host web using the SP.AppContextSite() function, as illustrated in A sample code excerpt to update the title of a list item using JavaScript and the REST API.

  • method. Defines the HTTP method to use while invoking the target URL.

  • body. Declares the content of the message body that will be posted to the target URL, just in case you will have message content to send.

  • headers. Allows defining a list of HTTP headers to provide while invoking the target URL. As you can see from A sample code excerpt to update the title of a list item using JavaScript and the REST API, here you can provide such headers as Accept, X-RequestDigest, X-HTTP-Method, IF-MATCH, and so on.

  • success. Is the pointer to a function that will be invoked in case of a successful call.

  • error. Is the pointer to a function that will be invoked in case of a failed call.

Security

By default, the REST API requires that the consumers act in an authenticated session for security purposes. The authenticated session can be gained through Windows integrated security, browser-based direct authentication (in the case of a SharePoint-hosted app), or using OAuth (in any other situation).

In the case of integrated security, you need to enable the automatic flow of integrated security credentials in the HTTP client library you will use. For example, if you’re working in JavaScript within a web browser and using SharePoint-hosted app or application pages, the flow of integrated security credentials will be automatic. On the contrary, when working in a Windows Store app for Windows 8, you must request permission for the enterprise authentication capability in the AppManifest.xml file of the app.

If you want to use OAuth—suppose you’re executing JavaScript code within a autohosted or provider-hosted app on a third-party site—you first need to retrieve and store the access token provided during the OAuth handshake. Then you must provide that access token to every request to the REST API, embedded in a dedicated Authorization HTTP header. The JavaScript code excerpt in A code excerpt for invoking the REST API with OAuth authentication configures that HTTP header using an access token stored in a hypothetical accessToken variable.

In addition, you can enable anonymous access to read-only operations of the REST API, in case you want to publish your contents to the public Internet. To configure this capability, you will need to edit the Anonymous permission of the target website. Figure 9-3 shows the configuration panel for setting this option. You can find the panel by choosing Site Settings | Site Permissions | Anonymous Access.

A screen shot of the panel for configuring anonymous users’ permissions. You can specify access to the entire site, lists and libraries, or nothing. There is an option for requiring explicit permission for accessing remote interfaces.

Figure 9-3. The UI for configuring anonymous access to the REST API.

If you turn off Require Use Remote Interfaces Permission, all anonymous users will be able to invoke the read-only operations of the REST API. Only authorized users can change this option, but they may do so from the web interface, working within PowerShell, or using the CSOM.

Common REST API usage

For the remainder of the chapter, you will learn how to use the REST API while executing common and useful tasks. All the code samples are provided in JavaScript and run in a SharePoint app that uses cross-domain calls. Thus, you will be able to reuse all the code excerpts illustrated by simply copying and pasting the code and adapting the values of the arguments and HTTP headers provided to the methods.

Important

The code samples come from a SharePoint-hosted app, so they do not need to provide an OAuth access token. Please refer to the “Security” section earlier in the chapter if you need to use the code sample from an autohosted or a provider-hosted app.

For the sake of simplicity, all the code samples also assume that you have the set of global and predefined variables illustrated in A code excerpt for the startup phase of the code samples illustrated in the current section, together with some common startup code.

All the code samples illustrated in the next sections will behave as event handlers for HTML Button input elements.

Creating a new list

To create a new list instance via the REST API and JSON, you first need to prepare a JSON representation of the list to create. Then you must send it through AJAX, including the X-RequestDigest HTTP header. A JavaScript function for creating a list instance using the REST API provides a function for this.

Notice that A JavaScript function for creating a list instance using the REST API creates the list in the host web; your app will need specific permissions to accomplish this task.

Creating and updating a list item

Now imagine that you want to add one or more items to the list you just created. The code will be similar to A JavaScript function for creating a list instance using the REST API, but you will need to define the JSON structure of a list item. Moreover, you will need to change the URI of the operation in order to map to the collection of items of the target list. A JavaScript function for creating a list item in a list instance using the REST API shows the necessary code.

Notice the value assigned to the type property of the __metadata of the target item. It defines the data type name corresponding to a list item of the current list. A JavaScript function for creating a list item in a list instance using the REST API assumes a value of SP.Data.RESTCreatedListListItem.

Updating an already existing item is almost the same as creating a new one, except that you need to provide the ETag value in the request headers and to synchronize the execution of parallel operations. A JavaScript function for updating a list item in a list instance using the REST API shows an example that changes the title property of an existing list item.

Note that A JavaScript function for updating a list item in a list instance using the REST API uses a nested SP.RequestExecutor instance, which will run just after successful completion of the external operation invocation.

Deleting an existing list item

What if you want to recycle one or more of the items you created in the previous examples? One more time, you need to provide the ETag value of the current item, as shown in A JavaScript function for deleting a list item in a list instance using the REST API.

A JavaScript function for deleting a list item in a list instance using the REST API uses an HTTP POST method, along with an X-HTTP-Method header with a value of DELETE. If you want to force the deletion, however, you can provide a value of * for the ETag header.

Querying a list of items

A common and useful operation is querying of a list of items. As shown in the ”Querying data” section earlier in the chapter, you simply need to invoke an endpoint providing an OData query as a set of query string parameters. If you’re working in JavaScript on the client side, however, the result will be a collection of items presented in JSON format. A JavaScript function for querying a list of contacts using the REST API demonstrates how to query the items in a hypothetical list of contacts.

The HTTP request for querying items is a GET; it does not require a form digest, and it will suffice that the app and the current user both have permissions to read the target list. The response is a JSON serialized array of items that is browsed by code.

Creating a new document library

Most SharePoint solutions use documents and document libraries; A JavaScript function for creating a document library via the REST API shows you how to create a document library via the REST API.

The procedure is almost identical to that for creating a custom list. The only difference is that here you provide a BaseTemplate value compliant with a document library. The example provides a value of 101, which corresponds to a generic document library. When you successfully create the library, you will get back a JSON serialization of its definition in the success event.

Uploading or updating a document

Once you have one or more document libraries, you can use the REST API to upload documents into them. A JavaScript function for uploading a document into a document library via the REST API uploads an example XML file into a document library. The URL of the operation for adding the new file is highlighted in bold, as well as the HTTP headers that are required for the correct and secure execution of the operation.

If you want to update an already published file, you can use a procedure like the one illustrated in A JavaScript function for updating a document into a document library via the REST API.

As you can see, the REST endpoint for the operation is the $value of the file, and the file will be overridden by what it will be posted by the page.

Document check-in and checkout

Another vital component of many business-level solutions is the ability to control document versioning through the check-in and checkout capabilities of SharePoint. A JavaScript function for checking out a document from a document library via the REST API shows you how to check out a document, while A JavaScript function for checking in a document into a document library via the REST API handles check-in.

The checkout phase simply requires an operation URI to be invoked via HTTP POST. On the contrary, the check-in phase requires posting some arguments, which in the current example are presented as a JSON object. This posted JSON object represents the arguments for the classic and standard CheckIn method of the CSOM.

Deleting an existing document

The last action related to management of single files is the deletion of a document. As shown at the beginning of this chapter, to delete a document, you need to make an HTTP POST request to the service, providing an ETag for security validation rules and an HTTP header of type X-HTTP-Method with a value of DELETE. A JavaScript function for deleting a document from a document library via the REST API demonstrates the process.

Notice that A JavaScript function for deleting a document from a document library via the REST API retrieves the file itself as an SP.File object, instead of the bare content ($value) of the file. The code then deletes that file without performing a concurrency check.

Querying a list of documents

Querying a list of documents from a document library is almost the same as querying a list of items. The main difference is the URL of the endpoint, which targets the Files collection instead of the Items collection. Furthermore, every file of a document library is an object of type SP.File, not SP.ListItem.

Notice also that the HTTP query uses an HTTP GET method and provides only the Accept HTTP header, without requiring any other extended header or information.

More Info

For further details about the types and members available in the REST API, consult the official reference of the SP namespace of the Client-Side Object Model for JavaScript (JSOM). You can find the official reference at http://msdn.microsoft.com/en-us/library/ee557057.aspx.

Summary

In this chapter, you learned about the new REST API introduced in SharePoint 2013. You examined the architecture and the capabilities of this new tool, which can be consumed either by .NET or SharePoint apps, as well as from any third-party platform. In addition, you learned how to implement the REST API in real projects with JavaScript, addressing a set of common scenarios.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset