4 out of 5 rated this helpful - Rate this topic

Programming using the SharePoint 2013 REST service

SharePoint 2013

Published: July 16, 2012

Conceptual overview topic

Learn about the SharePoint 2013 REST service, which provides a REST programming interface comparable to the existing SharePoint client object models.

SharePoint Foundation 2010 introduced the client object models, which enabled developers to perform remote communication with SharePoint by using the web programming technology of their choice: .NET Framework, Microsoft Silverlight, or JavaScript. SharePoint 2013 introduces a Representational State Transfer (REST) service that is fully comparable to the client object models. In SharePoint 2013, nearly every API in the client object models will have a corresponding REST endpoint. Now, developers can interact remotely with the SharePoint object model by using any technology that supports REST web requests.

In SharePoint Foundation 2010, the client object models provide APIs that enable developers to interact with SharePoint sites from script that executes in the browser, from code (based on Microsoft .NET Framework 3.5 or later) that executes in a .NET Framework managed application, or from code that executes in a Microsoft Silverlight application. The proxy .js files and managed .dll files that compose the client object models are built upon the client.svc web service, and handle the effective batching, serialization of requests, and parsing of replies. Figure 1 shows a high-level view of the SharePoint client model architecture.

Figure 1. SharePoint client object model architecture

SharePoint client object model request, response

Because of the functionality and ease of use that client object models provide, they remain the primary development option for communicating with SharePoint sites by using .NET Framework managed code, Silverlight, or JavaScript.

However, SharePoint 2013 adds the ability for you to remotely interact with SharePoint sites by using REST. Now, you can interact directly with SharePoint artifacts by using any technology that supports standard REST capabilities.

To use the REST capabilities that are built into SharePoint 2013, you construct a RESTful HTTP request, using the Open Data Protocol (OData) standard, which corresponds to the desired client object model API. The client.svc web service handles the HTTP request and serves the appropriate response in either Atom or JSON (JavaScript Object Notation) format. The client application must then parse that response. Figure 2 shows a high-level view of the SharePoint REST architecture.

Figure 2. SharePoint REST service architecture

SharePoint REST service architecture

HTTP operations in SharePoint 2013 REST services

The endpoints in the SharePoint 2013 REST service correspond to the types and members in the SharePoint client object models. By using HTTP requests, you can use these REST endpoints to perform typical CRUD (Create, Read, Update, and Delete) operations against SharePoint artifacts, such as lists and sites.

Typically, endpoints that represent Read operations map to HTTP GET commands. Endpoints that represent update operations map to HTTP POST commands, and endpoints that represent update or insert operations map to HTTP PUT commands.

In SharePoint 2013, use POST to create artifacts such as lists and sites. The SharePoint 2013 REST service supports sending POST commands that include object definitions to endpoints that represent collections. For example, you could send a POST command that included a new list object definition in ATOM to the following URL, to create a SharePoint list:

http://server/site/_vti_bin/client.svc/web/lists

For POST operations, any properties that are not required are set to their default values. If you attempt to set a read-only property as part of a POST operation, the service returns an exception.

Use PUT , PATCH, and MERGE operations to update existing SharePoint objects. Any service endpoint that represents an object property set operation supports both PUT requests and MERGE requests. For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property. For PUT commands, however, any properties you do not explicitly set are set to their default properties. In addition, if you do not specify all settable properties in object updates when using HTTP PUT commands, the REST service returns an exception.

Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object represented by that endpoint. In the case of recyclable objects, such as lists, files, and list items, this results in a Recycle operation.

SharePoint REST service response formatting

By default, the SharePoint 2013 REST service responses are formatted by using the Atom protocol, according to the OData specification. In addition, the REST service supports HTTP Accept headers that enable you to specify that the response is returned in JSON format.

Requests for collections are returned as OData entity sets.

Note Note

Request batching according to the OData protocol standards is not available in the SharePoint 2013 REST service. Request batching is available in the client object models.

The SharePoint 2013 REST service does not support the exception or conditional scope functionality that is available in the client object models.

Most client object model APIs have, or are planned to have, a corresponding REST endpoint; whenever possible, the URI for these REST endpoints closely mimics the structure of the API signature. In some cases, however, the endpoint URI must be adapted to account for REST or OData conventions. This section describes general guidelines for determining REST endpoint URIs from the signature of the corresponding client object model API.

Figure 3 displays the general syntax structure of SharePoint REST URIs. The following sections discuss each of the main segments, and several other URI structure alternatives, in detail.

The REST endpoints deviate from this syntax structure in two major areas:

  • In the case of a REST endpoint where the corresponding client object model method requires that complex types are passed as parameters, the REST endpoint may deviate from this syntax construction to account for REST limitations.

  • REST endpoints deviate from this syntax structure for URIs that are specified for static methods and properties.

Figure 3. SharePoint REST URI syntax structure

SharePoint REST request syntax

Namespaces and entry points for the SharePoint 2013 REST service

The main entry points for the REST service represent the site collection and site of the specified context. In this way, these entry points correspond to the SPContext.Current.Site property and SPContext.Current.Web property in the SharePoint server-side object model, or the ClientContext.Site property and ClientContext.Web property in the client object models.

To access a specific site collection, use the following construction:

http://server/site/_api/site

To access a specific site, use the following construction:

http://server/site/_api/web

In each case, server represents the name of the server, and site represents the name of, or path to, the specific site.

From this starting point, you can then construct more specific REST URIs by ''walking" the object model, using the names of the APIs from the client object model separated by a forward slash (/). Table 1 shows examples of client object model calls and their REST equivalents.

Table 1. Client object model calls and their REST equivalents

Client object model

REST equivalent

ClientContext.Web.Lists

http://server/site/_api/web/lists

ClientContext.Web.Lists[guid]

http://server/site/_api/web/lists(‘guid’)

ClientContext.Web.Lists.GetByTitle("Title")

http://server/site/_api/web/lists/getbytitle(‘Title’)

In the SharePoint REST service, API names are case-insensitive. In the previous list, for example, you would use /getbytitle to specify the REST equivalent of the GetByTitle method in the client object models.

The previous examples use _api to denote the SharePoint 2013 REST service. As mentioned earlier, the REST service is part of the client.svc web service. However, to make REST URI construction easier and to shorten the base REST URI path, the REST service uses _api to abstract away the need to explicitly reference the client.svc web service. The REST service still recognizes and accepts URIs that reference the client.svc web service. For example, you can use http://server/site/_vti_bin/client.svc/web/lists instead of http://server/site/_api/web/lists. However, using _api is the preferred convention. URLs have a 256 character limit, so using _api shortens the base URI, leaving more characters for use in constructing the rest of the URL.

In addition to /site and /web, the REST service includes several other access points that enable developers to navigate to specific functionality. Table 2 lists these access points.

Table 2. SharePoint 2013 REST service access points

Area

Access point

Site

http://server/site/_api/site

Web

http://server/site/_api/web

User Profile

http:// server/site/_api/SP.UserProfiles.PeopleManager

Search

http:// server/site/_api/search

Publishing

http:// server/site/_api/publishing

Specifying parameters for REST service URIs

SharePoint 2013 extends the OData specification to enable you to use parentheses to specify method parameters and index values, as shown earlier in Table 1. This prevents potential disambiguation issues in URIs that contain multiple parameters with the same name. For example, the following two URIs contain parameters that have the same name:

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

http://server/site/_api/web/lists('<guid>')/fields/getById('<guid>')

To specify multiple parameters, include the parameter as a name-value pair, and separate the parameters with commas. For example:

http://server/site/_api/web/getAvailableWebTemplates(lcid=1033, includeCrossLanguage=true)

Figure 4 shows the SharePoint REST parameter syntax.

Figure 4. SharePoint REST parameter syntax

SharePoint REST service method parameter syntax

Complex types as parameters for the REST service

Some methods in the client object model require a large payload as a parameter. For some REST endpoints to maintain functionality parity with their corresponding client object model APIs, the endpoints must accept a complex type as a parameter. In these cases, the REST service extends the existing OData protocol to enable these REST endpoints to accept a single complex type as a parameter. This applies to POST operations only, and you have to pass the complex type in Atom format or JSON format, according to OData standards.

For example, the ListCollection.Add method takes a Microsoft.SharePoint.Client.ListCreationInformation object as a parameter. To add a list to a specified site, construct the appropriate REST endpoint as follows:

http://server/site/_api/web/lists/add

Then, pass the complex type in the request body, formatted here by using JSON.

{ "d" : {
   "results": {
     "__metadata": {
       "type": "SP.ListCreationInformation"
     }, 
     "CustomSchemaXml": "…large payload…/", 
     "Description": "desc", 
     "DocumentTemplateType": "1", 
     "TemplateType": "101", 
     "Title": "Announcements"
   }
} 
}

Using parameter aliases in REST service calls

You can use the "parameter aliasing" semantic in OData for passing parameters to a SharePoint REST endpoint. In parameter aliasing, the parameter value is identified with an alias in the parameter call, and the actual value is specified in the query string of the URI. This enables you to support more types of characters and consistent formatting by using the query string.

For example, the following two REST URIs are equivalent; the first specifies the parameter value directly, while the second example uses a parameter alias, @template, and then specifies the actual parameter value in the query string of the URI:

http://server/site/_api/web/applyWebTemplate("STS#0")

http://server/site/_api/web/applyWebTemplate(title=@template)?@template="STS#0"

However, the SharePoint REST service does not support passing complex types via parameter aliasing. For example, the following URI, which contains a complex type in the parameter alias, is not supported:

http://server/site/_api/userProfiles/People(7)/GetWorkplace(@address)?@address={"__metadata":{"type: "ODataDemo.Address"},"Street":"NE 228th", "City":"Sammamish","State":"WA","ZipCode":"98074","Country": "USA"}

Figure 5. SharePoint REST service parameter aliasing syntax

SharePoint REST service parameter aliasing syntax

Specifying dictionaries as parameter values

For REST endpoints that correspond to methods that take Dictionary<String, String> dictionaries as parameters, pass the dictionary as a series of comma delimited name-value pairs in the query string.

Figure 6. REST service syntax for Dictionary parameters

REST service syntax for Dictionary parameters

A Dictionary<String, object> is represented as a multi-value object, named KeyedPropertyValue, with the following string properties:

  • Key  The key of the multi-value object.

  • Value  The value of the object

  • ValueType  The value type of the object. For simple value types that map to existing Entity Data Model (EDM) types, the REST service returns the appropriate EDM type string; for example, "Edm.String." If not, the REST service returns the value type returned by the Type.ToString function.

Specifying parameter values in the query string

If your REST URI terminates in a method call, you can use query string syntax to specify the parameter values of the method. For example:

http://<server>/<site>/_api/web/applyWebTemplate?template=”STS#0”

Figure 7 shows the REST service syntax for parameters in query string.

Figure 7. REST service syntax for parameters in query string

REST service syntax for parameters in query string

Specifying static methods and properties as REST service URIs

To construct URIs that correspond to static methods or properties, use the corresponding API name from the ECMAScript object model, starting with the namespace declaration and using dot notation. For example, SP.Utilities.Utility.getImageUrl(imageName) in the ECMAScript client object model would have the following REST equivalent:

http://server/site/_api/SP.Utilities.Utility.getImageUrl('imageName')

However, static properties can be accessed only directly, and are not allowed as part of a larger URI composition. For example, directly accessing the SP.Utility.AssetsLibrary method in REST is allowable, as follows:

http://server/site/_api/SP.Utility.assetsLibrary/id

However, using that resource location as a parameter for a more complex URI, as shown in the following example, is not allowed:

http://server/site/_api/getList(~SP.Utility/assetsLibrary/id)

Figure 8 shows the SharePoint REST service static member syntax.

Figure 8. SharePoint REST service static member syntax

SharePoint REST service static member syntax

OData query operator support

The SharePoint REST service supports a wide range of OData query string operators that enable you to select, filter, and order the data you request.

Selecting fields to return

Use the $select query option to specify which fields to return for a given list, list item, or other SharePoint object represented by an entity set. You can use $select=* to return all available fields.

Note Note

In general, if you do not specify the $select query option, the REST service returns all available fields by default. However, in a few cases, some SharePoint objects include properties that are very resource intensive to retrieve; to optimize REST service performance, these properties are not included in the default query, and must be explicitly requested.

For example, the SPWeb.EffectiveBasePermissions property is not returned by default, and must be explicitly requested using the $select query option.

In addition, you can specify that the request returns projected fields from other lists and the values of lookups. To do this, specify the field name in both the $select and $expand query options. For example:

http://server/site/_api/web/lists('guid')/items?$select=Title,Products/Name&$expand=Products/Name

Bulk expansion and selection of related items is not supported.

Selecting items to return

Use the $filter query option to select which items to return. Table 3 lists the filter query comparison options and functions supported by the SharePoint REST service.

Table 3. OData query operators

Supported

Not supported

Numeric comparisons

  • Lt

  • Le

  • Gt

  • Ge

  • Eq

  • Ne

  • Arithmetic operators
    (Add, Sub, Mul, Div, Mod)

  • Basic math functions
    (round, floor, ceiling)

String comparisons

  • startsWith

  • substringof

  • Eq

  • Ne

  • endsWith

  • replace

  • substring

  • tolower

  • toupper

  • trim

  • concat

Date and time functions

  • day()

  • month()

  • year()

  • hour()

  • minute()

  • second()

  • DateTimeRangesOverlap operator

  • Querying as to whether a date time falls inside a recurrent date time pattern

Figure 9 shows the supported OData query options.

Figure 9. Supported OData query options

SharePoint REST service query option syntax

Queries for single value lookup fields

Single value lookup fields are represented by two separate fields in the SharePoint REST service: one field representing the actual field value, and another representing the field name. You can perform queries against the lookup field value as you would any other field of that data type. For example, if the lookup field value is a string, you can use string comparison options in your query.

Queries for users

In the SharePoint REST service, users are represented by the user's friendly (display) name, and not their alias or domain\alias combination. Therefore, you must construct user queries against users' friendly names.

Note Note

Membership-based user queries are not supported.

Usage of the Current operator to do queries using the ID of the current user is not supported.

Queries for multi-value lookup fields and users

Because multi-value lookup fields are returned as a string of multiple values, there is no way to query for them (for example, the equivalent of an Includes element or NotIncludes element is not supported).

Sorting returned items

Use the $orderby query option to specify how to sort the items in your query return set. To sort by multiple fields, specify a comma-separated list of fields. You can also specify whether to sort the items in ascending or descending order by appending the asc or desc keyword to your query.

Paging through returned items

Use the $top and $skip query options to select a subset of the items that would otherwise be returned by your query.

The $top option enables you to select the first n items of the return set for return. For example, the following URI requests that only the first ten items in the prospective return set actually be returned:

http://server/site/_api/web/lists('<guid>')/items$top=10

The $skip option enables you to skip over the specified number of items and return the rest.

Note Note

When using these query options, take into account that paging in OData is ordinal. For example, suppose you are implementing a next page button to display SharePoint list items. You use the REST service to enable the button to return items 1 through 20 when clicked, then items 21 through 40, and so on. However, suppose another user deletes items 4 and 18 between clicks of the next button. In such a case, the ordinal positioning of the remaining items is reset, and displaying items 21 through 40 actually skips over two items.

Errors and exceptions in the SharePoint 2013 REST service

In the case of errors or exceptions, the REST endpoint returns the appropriate HTTP error code: for example, error code 400 for bad requests, code 404 for REST endpoints that do not exist, and code 500 for internal server errors. The body of the response contains the same error information that would be returned from the corresponding client object model API, and the correlation ID, as specified by the OData protocol.

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.