REST AND ODATA

REpresentational State Transfer (REST) is a prevalent pattern for designing easily consumed data APIs over the Internet. You might hear an API described as RESTful if it is designed to be used over HTTP protocols and is in line with the principles of REST. These principles are as follows:

  • Client-Server: The client is unaware of how the server stores or manages the data and doesn’t need to know in order to use the API.
  • Stateless: The server does not store any context or state about the calling client.
  • Cacheable: The results of the calls to the API define themselves as being cacheable, or not.
  • Layered: The client does not mind whether the call to the API is transmitted via common Internet technology such as load balancers.
  • Uniform Interface: This provides a simple and known way to access data through standard URI addressing and self-describing so that a client can discover how to access data.

Many services offer REST-based APIs to ease access to their systems in a commonly understood manner. SharePoint 2013 builds on this foundation to offer access in a “RESTful” way to allow remote systems to interact with it in a platform agnostic and open way. For developers this means that using other helper libraries and frameworks for working with REST is a viable method, and the time to become proficient in a proprietary API is decreased.

OData or Open Data Protocol is a protocol definition for querying, finding, and updating data over HTTP. It offers defined methods for specifying common query operations and defines the format in which data is returned. SharePoint 2013 uses WCF Data Services v5.0 which implements the OData v3 specification. For more information on OData you can visit: http://www.odata.org.

Combining a RESTful Web API with OData gives a powerful combination of simple and easy-to-use APIs that have a well-defined interface and interaction model. In practical terms, having access to a RESTful OData-based API means the following for SharePoint developers:

  • Standard URIs for addressing data
  • Simple use of GET, POST, PUT/MERGE, and DELETE HTTP methods
  • JSON or XML (ATOM) responses
  • Simple query/filter semantics

The following sections describe each of the preceding points with simple-to-follow examples of how they are addressed in SharePoint 2013’s implementation of its REST/OData Web API endpoints.

Getting Started with REST and OData

You can find SharePoint’s REST/OData APIs in the _API URL space under each SharePoint site. For example:

https://servername/sitename/_api/

_api is the root URI for all REST/OData calls. SharePoint also supports calls to the _vti_bin/client.svc/ URI to maintain backward compatibility with the previously available but more limited REST API in SharePoint 2010.

To query for data, issue a GET request. To update data you use either a PUT or MERGE request passing the data you want to update. But first you must specify which namespace it belongs in, such as Web, Site, or Search. Other groups include:

  • _api/web
  • _api/site
  • _api/search
  • _api/publishing

After you specify a namespace you must address an object, method, indexer, or property on it. Figure 9-8 depicts the URI address system.

To retrieve the list of lists on a SharePoint site simply issue a GET request to the following:

https://servername/sitename/_api/web/lists

To retrieve the details about a list simply make a GET request to that list’s URI indicated in the previous response’s id property. For example:

https://servername/sitename/_api/Web/Lists(guid'f57d3ddc-4522-4145-a0fe-72abbd6ea8fc')

This example uses the Lists method with a parameter to specify the ID of the list. You could also use the list’s entity name; for example:

https://servername/sitename/_api/Web/Lists/MoviesList

Additionally, you can address a list by name using the getbytitle function as follows. This addresses the list with its name versus its entity name:

https://servername/sitename/_api/Web/Lists/getbytitle('movies')/items

To access the items within a list add /items to the URI:

https://servername/sitename/_api/Web/Lists/MoviesList/Items

By default you will receive an ATOM feed XML response containing the lists in your site. If you want to receive a JSON payload instead, set the HTTP Accept header to application/json;odata=verbose. This signals that you want JSON instead of the default ATOM payload. JSON is typically lighter weight and better suited to mobile scenarios where speed is important.

Filtering and Selecting

When you query for data it’s important to ask for only the data you really need. This keeps payload sizes down and speeds up delivery of the data. _Api uses OData semantics to let you do this by filtering records and selecting properties you want. The common operators you can use for manipulating the result set include the following:

  • $filter, for filtering results
  • $select, for selecting properties to return
  • $expand, for expanding properties to return
  • $orderby, for ordering results
  • $top, for taking the top X results

The simplest way to learn about these operations is to try them out for yourself, as shown in the following exercise.


TRY IT OUT: OData Operations on Data
In this exercise you try out querying and filtering for data using the REST/OData _Api in SharePoint 2013.
1. Create a new list in your SharePoint 2013 site by clicking Site Contents from the Quick Launch navigation.
2. Click Add an App.
3. Choose Custom List and call it Movies.
4. After the list is created, add some list items to it of your favorite movie titles.
5. Modify the URL to navigate to the following URI. Review the payload XML that is returned:
https://servername/sitename/_api/Web/Lists/MoviesList/Items
6. Modify the URL by adding (1) on the end (shown in the following code). This returns the first item in the list:
https://servername/sitename/_api/Web/Lists/MoviesList/Items(1)
7. Modify the URL and add a $filter parameter like the following, specifying the title of one of the movies you added earlier:
?$filter=Title eq 'Aliens'
8. Add a $select parameter to just select the Title property of the list item:
https://servername/sitename/_api/Web/Lists/_api/Lists/ /Items?
$filter=Title eq 'Aliens'&$select=Title
You should see a payload similar to the following:
<?xml version="1.0" encoding="utf-8" ?> 
<feed xml:base="https://servername/sitename/_api/" 
xmlns="http://www.w3.org/2005/Atom" 
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" 
xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">
<id>0d01b697-f8f4-496a-bc66-81e4ab7d8208</id> 
<title /> 
<updated>2012-11-03T07:07:21Z</updated> 
<entry m:etag=""2"">
<id>f6126125-fddb-4651-bedd-d797c6ef06f4</id> 
<category term="SP.Data.MoviesListItem" 
scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" /> 
<link rel="edit" 
href="Web/Lists(guid'f57d3ddc-4522-4145-a0fe-72abbd6ea8fc')/Items(1)" /> 
<title /> 
<updated>2012-11-03T07:07:21Z</updated> 
<author>
<name /> 
</author>
<content type="application/xml">
<m:properties>
<d:Title>Aliens</d:Title> 
</m:properties>
</content>
</entry>
</feed>
Notice that only the Title property is returned.
9. Modify the querystring as follows to order your movie titles alphabetically:
?$select=Title&$orderby=Title
10. Modify the querystring as follows to just retrieve the first movie:
?$select=Title&$orderby=Title&$top=1
How It Works
In this exercise you queried SharePoint list data using the REST/OData API. When a request is made to SharePoint via this API, SharePoint uses WCF Data Services support for OData to parse and interpret the query on the URL. It then uses that information to translate the query into an internal SharePoint list query (called a CAML query) and executes the query. By adding OData support parameters to the URL you are able to refine the query you make to SharePoint and just return the data you specifically need.

Creating, Updating, and Deleting

The REST endpoints also accept requests to create, update, and delete data using POST, PUT, and PATCH commands.

  • POST is used for creating data
  • PUT is used for updating (all property values specified)
  • PATCH is used for updating (specified properties only)

When using any of the preceding commands from JS running on a SharePoint page, you also must include the form digest from the page in the appropriate HTTP header:

X-RequestDigest: formDigest

You can get the formDigest from the object returned from a POST call to /_api/contextinfo, or if you are building a SharePoint-hosted app then you can simply get the value of the formDigest with this JQuery function:

$('#__REQUESTDIGEST').val()

You are then ready to send your create, update, or delete command to SharePoint. To practice doing so, take a look at the following activity.


TRY IT OUT: Creating a New List in the Host Web
In this example you use a SharePoint-hosted app using the Napa Office 365 Development Tools and use the REST/OData API to create a new list in the host Web. You must have the Napa application installed from the Office 365 marketplace prior to starting this exercise. The full JavaScript source for this exercise is available in the code download in the MyODataJavaScriptApp.js file.
1. Ensure you have Napa Office 365 Development Tools installed in your development site in Office 365.
2. Click Site Contents in your site navigation to see a list of all apps installed in your site.
3. Locate “Napa” Office 365 Development Tools in the list and click it, as shown in Figure 9-9.
4. Click Add New Project in the screen that appears.
5. Select App for SharePoint and enter MyODataJavaScriptApp in the Project name box. Click Create to continue. Napa creates a set of template files and folders for you. Explore the structure and get familiar with the layout of the application.
6. In the lower left of the window click the wrench icon to open the Property panel for your application as shown in Figure 9-10.
7. Click the Permissions tab and set the permissions for Web under Content to Full Control.
8. Open the Scripts folder and then open the App.js file. This default file contains the JavaScript for your application.
9. Add the following code to the bottom of the file. This helps you get the various parameters that were passed to the page from the querystring:
function getParams() {
    var params = {};
    location.search.split('?')[1].split('&').forEach(function (param) {
        var key = param.split('=')[0],
            val = decodeURIComponent(param.split('=')[1]);
        params[key] = val;
    });
    return params;
}
10. Replace the sharePointReady() function with the following. This code loads the SP.RequestExecutor.js JavaScript file that helps with cross-domain calls. The app needs this to call into the host Web because it’s on a different domain name:
var params;
var scriptbase;
 
function sharePointReady() {
    context = new SP.ClientContext.get_current();
         params = getParams();
    scriptbase = params.SPHostUrl + "/_layouts/15/";
         $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
}
11. Add the following new function. This uses a POST command to post a JSON payload with the new list information to the host web’s REST API:
function execCrossDomainRequest()
{
    var executor;
    executor = new SP.RequestExecutor(params.SPAppWebUrl);
 
    var data = JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 
        'AllowContentTypes': true, 'BaseTemplate': 100, 
        'ContentTypesEnabled': true, 'Description': 'My list description',
        'Title': 'My New List' });
 
    var requestUri = params.SPAppWebUrl + 
        "/_api/SP.AppContextSite(@target)/web/lists?@target='"         + params.SPHostUrl + "'";
 
    executor.executeAsync(
        {
            url: requestUri,
            method: "POST",
            body: data,
            headers: { 
                "accept": "application/json;odata=verbose",
                "content-type":"application/json;odata=verbose",
                "content-length": data.length, 
                "X-RequestDigest": $('#__REQUESTDIGEST').val()
            },
            success: successHandler,
            error: errorHandler
        }
    );
}
 
function successHandler(data) {
    alert('success'),
}
 
function errorHandler(data, errorCode, errorMessage) {
    alert("Failed :( Error:" + errorMessage);
}
12. Click the Run Project button in the bottom left of the window to test out the application. When it completes a message appears like the one shown in Figure 9-11.
13. Right-click the launch link and open your app in a new window to start your application. When you are prompted to trust your app, click Trust It to continue.
14. A JavaScript alert message appears, stating “Success.” The app has created the list in the host Web.
15. Navigate to the host website by clicking the title of your site in the navigation.
16. Click Site Content to see a list of the apps/lists in your site. You can see the new list called My New List that your app created, as shown in Figure 9-12.
How It Works
In this exercise you created a SharePoint-hosted app that created a new list in the host or parent Web. To do this it used the REST/OData API and a POST command to post the creation information as a JSON payload in the request. Because the request was from one domain to another, you used the SP.RequestExecutor framework to proxy the call via the app Web to the host Web. This step was necessary due to the cross-domain security boundary browsers put on JavaScript.
The JSON payload consisted of a JSON representation of an SP.List object, along with the properties needed for creation such as the BaseTemplate ID and the Title.
By making a POST request along with this JSON to the /_api/SP.AppContextSite(@target)/web/lists URI, SharePoint proxies the request to the host Web for you along with the JSON. Because the request is a POST SharePoint knows you want to create something. SharePoint knows you want to create a list because the URI specifies the /web/list REST endpoint. SharePoint looks in the body of the request for the details on the list you want to create and creates it.


WATCH THE JAVASCRIPT CSOM AT WORK WITH FIDDLER
If you are interested in seeing the underlying API calls to SharePoint from the JavaScript CSOM you can do so with a tool called Fiddler. You can download Fiddler from: http://www.fiddler2.com. Using Fiddler you can see all the HTTP traffic between your computer and another such as Sharepoint.com, where Office 365 is hosted. When watching Fiddler look for requests to URLs with paths that end in: /_vti_bin/client.svc/ProcessQuery. You will see XML payloads being sent to SharePoint along with JSON responses.

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

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