TH3 Office 365 REST APIs Peter Carson
Peter Carson President, Envision IT SharePoint MVP peter@envisionit.com http://blog.petercarson.ca www.envisionit.com Twitter @carsonpeter VP Toronto SharePoint User Group
Agenda Envision IT Background API Background Documents Search Authentication Q&A
Envision IT Services Focused exclusively on SharePoint Web Content Management public web sites, Intranets, Extranets Portals and Collaboration document management, forms, BI
Products
Who needs an API? Custom Web Parts Console Applications Workflows PowerShell SharePoint Apps Client Side Code (JavaScript)
How Are You Calling? C# On the SharePoint Server (Full trust code) Web Parts Workflows Console Apps Another Server (High Trust Apps) Provider Hosted Apps Remote Event Receivers Console Apps JavaScript SharePoint or Cloud Hosted Apps Client side code
Full Trust Code Runs on the SharePoint Server Has access to the full server object model Traditional way SharePoint customizations were developed Not supported for Office 365 Microsoft is not going to let you run your code on their multi-tenant farms
Calling from Outside SharePoint SOAP Web Services Supported back to MOSS 2007 Difficult to work with, particularly through JavaScript Client Side Object Model (CSOM) Introduced in SharePoint 2010, expanded in 2013 Libraries for C#, JavaScript, and Silverlight REST Introduced in SharePoint 2010, expanded in 2013 At SPC 14 Vegas, Microsoft indicated this is the direction going forward Ideal for JavaScript
What is REST? Representational State Transfer Designed as an alternative to SOAP Simpler and easier to understand Architectural style, not a standard Client-Server, Stateless, Cacheable, Layered, Uniform Interface
Office 365 REST APIs Documents Search People Social Mail Calendar Bing Microsoft Dynamics
HTTP Verbs Verb GET POST PUT MERGE DELETE Purpose Read from SharePoint Creates new objects Updates an existing object Any properties not set explicitly are overwritten to their default values Updates an existing objects Preserves any existing properties not being set Deletes the object
Envision Shakespeare Company Reference project to demonstrate the features and capabilities of SharePoint 2013: Adaptive design for PC, tablet, and mobile Populated content including the complete works of Shakespeare Extensive use of catalogs and content search web parts SharePoint search with refiners and preview Image renditions, rotators, and galleries Video support PowerShell build of full site Site columns, content types, and branding with adaptive design packaged in Visual Studio Metadata navigation, friendly URLs, and import/export of the term store Available at www.envisionit.com/shakespeare
Shakespeare Package All design files (MindMap, Axure Wireframes, Word specification, Adobe and HTML mockups) Visual Studio 2012 solution Site columns and content types Branding (master page, page layouts, display templates, CSS, JavaScript) Term store navigation control Term store export/import tool with full support for 2013 navigation features Site content, including the complete works of Shakespeare tagged for the site PowerShell scripts for automated creation of the site, including site collection, features, and content This package can be easily deployed to a Cloudshare SharePoint 2013 test environment, or an onpremise farm.
Retrieving List Data Top level site http://shakespeare.labvm12.envisionit.com Retrieve all lists http://shakespeare.labvm12.envisionit.com/_api/lists Get fields from a list by list GUID http://shakespeare.labvm12.envisionit.com/_api/lists(guid'893525ab- 6d50-425c-8858-c6294230aa75')/Fields Get list items from a list by Title http://shakespeare.labvm12.envisionit.com/_api/lists/getbytitle('ne ws')/items
Turn off feed reading view Provides the native XML back in the browser
Data Format By default data is returned as XML Easy to consume in C# Alternatively you can specify JSON as the form JavaScript Object Notation Much easier to manipulate in JavaScript or jquery
List REST Call http://shakespeare.labvm12.envisionit.com/pages/news-rest-list.aspx var url = _sppagecontextinfo.webabsoluteurl + '/_api/lists/getbytitle(\'news\')/items'; var deferred = $.ajax({ url: url, method: "GET", headers: { "accept": "application/json;odata=verbose", }, success: function (data) { var results = data.d.results, $table = $('<table></table>'); $table.append('<tr><td>title</td><td>summary</td><td>article Date</td></tr>'); $.each(results, function (i, item) { $table.append('<tr><td>' + results[i].title + '</td><td>' + results[i].escsummary + '</td><td>' + results[i].articlestartdate + '</td></tr>'); }); $('#RESTDemo').html($table); }, error: function (err) { // handle error alert('error getting the News: ' + err); } });
Search Driven Apps Read from the search index rather than directly from lists Can pull content from across multiple lists, sites, site collections, web applications, even farms News query for the browser http://shakespeare.labvm12.envisionit.com/_api/search/query?querytext=%2 7(path:"http://shakespeare.labvm12.envisionit.com/lists/News") (IsDocument:"True" OR contentclass:"sts_listitem")%27&selectproperties=%27title,owsescsummary, ArticleStartDateOWSDATE%27 %27 is a single quote http://shakespeare.labvm12.envisionit.com/pages/news-rest-search.aspx
Search Rest Call var newsitems = []; var url = _sppagecontextinfo.webabsoluteurl + '/_api/search/query?querytext=' + '%27(path:"' + _sppagecontextinfo.webabsoluteurl + '/lists/news") (IsDocument:"True" OR contentclass:"sts_listitem")%27' + '&selectproperties=%27title,owsescsummary,articlestartdateowsdate%27'; var deferred = $.ajax({ url: url, method: "GET", headers: { "accept": "application/json;odata=verbose", }, success: function (data) { var results = data.d.query.primaryqueryresult.relevantresults.table.rows.results for (var i = 0; i < results.length; i++) { var fields = results[i].cells.results; var title = '', summary = '', articledate = null; for (var j = 0; j < fields.length; j++) { if (fields[j].key == 'Title') title = fields[j].value; else if (fields[j].key == 'owsescsummary') summary = fields[j].value; else if (fields[j].key == 'ArticleStartDateOWSDATE') articledate = fields[j].value; } } newsitems.push({ 'Title': title, 'ESCSummary': summary, 'ArticleStartDate': articledate}); var $table = $('<table></table>'); $table.append('<tr><td>title</td><td>summary</td><td>article Date</td></tr>'); $.each(newsitems, function (i, item) { $table.append('<tr><td>' + newsitems[i].title + '</td><td>' + newsitems[i].escsummary + '</td><td>' + newsitems[i].articlestartdate + '</td></tr>'); }); $('#RESTDemo').html($table); }, error: function (err) { // handle error alert('error getting the News: ' + err); } });
Christie Medical Business Case Christie Digital is a World Leader in Visual Solutions for World-Class Organizations Christie Medical s web site was a subsite of Christie Digital, at www.christiedigital.com Marketing was looking for a distinct brand and URL for the Medical division
Christie Medical Site Build Net new site build Completely independent site with its own URL and identity New branding and creative Built from the ground up to leverage SharePoint 2013 Live at www.christiemed.com Dev site is at https://christiemedical.envisionit.com/ Extensive leveraging of the Content Search Web Part
Bing Maps Integration
CSWP Challenges CSWP is a very powerful web part Enterprise CAL only or E3/E4 in Office 365 Not an issue on an anonymous site, full Enterprise features are included Limits results to a maximum of 50 Paging is supported for going beyond this This obviously doesn t work for the Bing Maps mashup
REST Challenges By default the REST API is not available anonymously Should only minimally relax security for it to work Done through the queryparametertemplate.xml file Placed in a document library in the root site collection Requires the farm, site, and web IDs, and what search capabilities should be turned on anonymously Waldek Mastykarz (MVP) has an excellent post describing this http://www.mavention.com/blog/configuring-sharepoint-2013- search-rest-api-anonymous-users
REST Implementation var localsite = _sppagecontextinfo.webabsoluteurl; var url = localsite + '/_api/search/query?querytext=' + '%27(path:"' + localsite + '/lists/distributors") (IsDocument:"True" OR contentclass:"sts_listitem")%27' + '&selectproperties=%27title,workaddressowsmtxt,workcountryowstext,primarynumberow STEXT,LogoImageOWSIMGE,UrlOWSTEXT,LatitudeOWSNMBR,LongitudeOWSNMBR%27' + '&QueryTemplatePropertiesUrl=%27spfile://webroot/queryparametertemplate.xml%27' + '&rowlimit=500';
Simcoe County District School Board 50,000 students Over 6,000 employees Board office in Barrie Bordered by the Holland Marsh in the south, the Trent-Severn Waterway in the east, Grey County in the west and Muskoka in the north
Simcoe County District School Board 119 schools and centres 87 elementary 16 secondary 6 learning centres 10 alternative Each needs their own web site Being built on SharePoint 2013 Elementary panel first Each has their own unique URL Content authored both at the school and centrally from the board www.scdsb.on.ca Pre-existing SharePoint 2010 site Future goal is to rebuild in SharePoint 2013
Forest Hill Public School First pilot school Located in Midhurst, Ontario Local school content author training completed Launch content loaded Going through final QA Launch end of April 2014 http://for.scdsb.on.ca
Site Features Fully adaptive design SharePoint 2013 host named site collection Template makes it easy to bring up new school sites News and events can be targeted by the board to any number of school sites Target by panel, weather zone, trustee, language Presented in a blended view with the school news and events Home page rotator, links, hours, content pages all managed by the school staff SEO-friendly URLs term store navigation
Desktop
Tablet and Smartphone
Events Fully adaptive calendar REST search driven jquery and Twitter Bootstrap adaptive design
Authentication Examples so far have been reading and displaying information Calls are coming from SharePoint hosted JavaScript Security is less onerous APIs just need to make sure results are security trimmed Updating requires one additional item
Posting When posting, you need to provide the form digest value Prevents replay attacks Your master page should have it <SharePoint:FormDigest runat= server /> Time expiring, so refresh if you re staying on one page for a long time UpdateFormDigest(_spPageContextInfo.webServerRelative Url, _spformdigestrefreshinterval)
POST Sample function addlistitem(url, listname, metadata, success, failure) { // Prepping our update var item = $.extend({ " metadata": { "type": getlistitemtype(listname) } }, metadata); // Executing our add $.ajax({ url: url + "/_api/web/lists/getbytitle('" + listname + "')/items", type: "POST", contenttype: "application/json;odata=verbose", data: JSON.stringify(item), headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("# REQUESTDIGEST").val() }, success: function (data) { success(data); // Returns the newly created list item information }, error: function (data) { failure(data); } }); }
DELETE Sample function deletelistitem(url, listname, id, success, failure) { // getting our item to delete, then executing a delete once it's been returned getlistitem(url, listname, id, function (data) { $.ajax({ url: data.d. metadata.uri, type: "POST", headers: { "Accept": "application/json;odata=verbose", "X-Http-Method": "DELETE", "X-RequestDigest": $("# REQUESTDIGEST").val(), "If-Match": data.d. metadata.etag }, success: function (data) { success(data); }, error: function (data) { failure(data); } }); }); };
OAuth Standard way for apps to authenticate to web sites Not just for SharePoint Facebook, Twitter In SharePoint it requires Windows Azure Access Control Services (ACS)
OAuth Authentication Process User Provider App Windows Azure AD Browse app No Token Redirect to SP Redirect to App Request Access Token Save Token in session REST call with Token Request Auth Code Return Auth Code ReturnToken Return JSON data Return page
High Trust Apps Server to server trust Uses digital certificates to establish a trust between the remote web application and SharePoint 2013 Can only be installed to on premises SharePoint, not to Microsoft SharePoint Online User security is up to the app. SharePoint trusts the app implicitly
Common Consent Framework Enables web applications to access multiple workloads and resources across Office 365 Can create web applications that access Microsoft OneDrive for Business files, SharePoint Lists, Exchange Calendars using Single-Sign On and an OAuth Provider. Windows Azure Active Directory implements common consent All user accounts, application registrations, and permissions are stored in Windows Azure AD It implements the OAuth protocol for authorizing access from your web application to Office 365 resources Once your web application is registered in Windows Azure AD, administrators can grant it access to Office 365 resources or users can grant access to their own resources in Office 365.
One Authentication to Office 365 APIs Sign-On experience using Organizational Account Combined Consent Across all Office 365 APIs
Basic Auth Protocol Flow with Office 365 App AAD OAuth2 server Authorization/Token Issuing endpoints Office 365 Exchange API endpoint Office 365 SharePoint API endpoint Authorization Request User Code User Login & Consent Use Code to get Exchange API Token Token Response Call API with Token Use refresh token to get SharePoint API Token Token Response Call API with Token
Graph API Part of Azure AD Provides a REST interface to query and update Window Azure AD (WAAD) Create and manage users, groups Assign subscriptions for Office 365 Changing quickly over the last several months
Provider App Challenge No way to programmatically install apps on new sites and pages App model expects that a user will install and trust the app Not appropriate for many business apps
Roll Your Own REST Visual Studio WebAPI Build your business logic on the server (but not on SharePoint) Field level security Business rules Reading and writing from multiple data sources Create a REST interface for your client side code Use Server to Server Trust to communicate with SharePoint
Alternative Authentication Process with JWT User Client Side Code Provider App Thinktecture Browse app App trusts IP No JWT Redirected to IP Return JWT Security Token JWT JWT Save Token in session JWT REST call with Token Return page Return JSON data
Frameworks Great open source community jquery is a given when working with REST HandlebarJS is a templating engine for formatting the results KnockoutJS and AngularJS for building single page apps Microsoft is investing heavily in supporting AngularJS, including Visual Studio support
Questions and Answers
Links http://blog.petercarson.ca www.envisionit.com www.envisionit.com/shakespeare www.christiemed.com for.scdsb.on.ca Get started with the SharePoint 2013 REST service www.plusconsulting.com/blog/2013/05/crud-on-list-itemsusing-rest-services-jquery How to: Create high-trust apps for SharePoint 2013