SPCSEA 2013 - Setting up SharePoint 2013: Tips and Tricks and PowerShell Scripts
SharePoint 2013 REST API tips & tricks
-
Upload
giuseppe-marchi -
Category
Technology
-
view
1.018 -
download
4
description
Transcript of SharePoint 2013 REST API tips & tricks
1 | SharePoint Saturday Italy – Rome – 25 January 2014
25 January 2014
2 | SharePoint Saturday Italy – Rome – 25 January 2014
Grazie ai nostri Sponsor!
3 | SharePoint Saturday Italy – Rome – 25 January 2014
SharePoint 2013 REST APIs tips and tricks
Giuseppe Marchi – Founder – Dev4Side S.r.l. – SharePoint [email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
4 | SharePoint Saturday Italy – Rome – 25 January 2014
Who I am Co-founder of Dev4Side S.r.l. 4 years Microsoft SharePoint MVP Speaker in Microsoft and Community events in Italy MCP, MCPD Web applications, MCTS ASP.NET 4, WSS
3.0, MOSS 2007 and SharePoint 2010 "SharePointer" from 2005 Father of www.peppedotnet.it Author of the book «Pocket C#», Apogeo Active member, speaker and promoter of
SharePointCommunity.it First, in Italy, with an App in the Office Store One of the TOP 25 SharePoint Influencers in Europe
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
5 | SharePoint Saturday Italy – Rome – 25 January 2014
Agenda SharePoint 2013 API changes
What’s new with REST interface New REST APIs syntax
Basic operators and actions Advanced actions Tips for survivors
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
6 | SharePoint Saturday Italy – Rome – 25 January 2014
SharePoint 2013 API changes
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
7 | SharePoint Saturday Italy – Rome – 25 January 2014
MOSS 2007 SOAP services
SharePoint 2010 Client Object Model
Direct access to client.svc service Request always in XML Must use a proxy Supports only .NET, Silverlight and Javascript
REST interface (ListData.svc) Only for lists!
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
What we had in the past
8 | SharePoint Saturday Italy – Rome – 25 January 2014
SharePoint 2013 REST APIs Direct access to client.svc service (using _api alias)
You can access to a lot of features of the Client Object Model through an HTTP request!
Access HTTP GET, PUT, Merge, POST Requests OData implementation* Atom XML or JSON as data type Supports any application, language or platform that enables you to
do a HTTP request
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
What’s new in REST interface
9 | SharePoint Saturday Italy – Rome – 25 January 2014
Demo
Hello REST world!
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
10 | SharePoint Saturday Italy – Rome – 25 January 2014
Entry pointsREST service includes several access points that enable developers to navigate to specific functionality of SharePoint 2013. The table below lists some of these access points.
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
Feature area Entry point
Context http://server/site/_api/contextInfo
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
Excel services (new and only on SharePoint Online)
http://server/site/_vti_bin/ExcelRest.aspx
11 | SharePoint Saturday Italy – Rome – 25 January 2014
OData implementation* OData = Open Data Procotol
Is a data access protocol, built on the AtomPub protocol and JSON, that uses the REST model for all requests
Each REST command is a POST, GET, PUT, PATCH, or DELETE HTTP request (mapping to CRUD) where the specifics of the command are in the URL READ -> GET HTTP request CREATE -> HTTP POST request UPDATE -> HTTP POST PUT or HTTP POST MERGE
request DELETE -> HTTP DELETE request
OData specifications != SharePoint REST implementation
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
12 | SharePoint Saturday Italy – Rome – 25 January 2014
In order to use the new REST interface in SharePoint 2013, you have to create an HTTP request using these parameters: URL – URI of the resource you want to manage Request type – GET/POST Data - parameters for POST queries ContentType – Content type of Data (XML/JSON), default: XML Headers
Accept – Content type of the response (XML/JSON), default: XML X-RequestDigest – Security token X-HTTP-Method – PUT/MERGE/DELETE IF-MATCH – To manage concurrency
Note: you can do this HTTP request from every platform or programming language!
How to compone a query
13 | SharePoint Saturday Italy – Rome – 25 January 2014
New REST syntax A request to the new REST interface shall use an URL
composed in the following way: Part 1 - Service root URI
Es: http://siteurl/_api/ Part 2 - Resource path
Es: web, site collection, list, file, sql table, user, namespace, method, etc…
Part 3 - Query strings options Es: $filter, $select, etc…
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
Full documentation on MSDN: http://msdn.microsoft.com/en-us/library/office/dn292556.aspx
14 | SharePoint Saturday Italy – Rome – 25 January 2014
New REST syntax – Resource path How to find resource path?
Start from /_api/web! Client object model reference
List of assemblies: 15/config/clientcallable xml files SPRemoteAPIExplorer Visual Studio Extension REST Navigator
(http://sprest.architectingconnectedsystems.com/navigator.aspx)[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
RESOURCE PATH
Client Object Model APIs
1 ~ 1
15 | SharePoint Saturday Italy – Rome – 25 January 2014
Demo
Hello REST world!
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
16 | SharePoint Saturday Italy – Rome – 25 January 2014
http://siteurl/_api/web http://siteurl/_api/web/lists http://siteurl/_api/web/lists?$filter=BaseTemplate eq 101 http://siteurl/_api/web/lists?$orderby=Title asc http://siteurl/_api/web/lists?$top=5&$skip=5 http://siteurl/_api/web/lists?$filter=startswith(Title, 'Shared') http://siteurl/_api/web/lists/getByTitle('Contacts') http://siteurl/_api/web/lists/getByTitle('Contacts')/items http://siteurl/_api/web/lists/getByTitle('Contacts')/items(1) http://siteurl/_api/web/lists/getByTitle('Contacts')/items(1)/Title http://siteurl/_api/web/lists/getByTitle('Contacts')/items(1)?$select=Title http://siteurl/_api/web/lists/getbytitle('shared documents')/rootfolder/folders?$select=Name http://siteurl/_api/web/getFolderByServerRelativeUrl('/Shared documents/Folder1/Folder2') http://siteurl/_api/web/getFolderByServerRelativeUrl('Shared documents')/Folders/add(url=''New
folder') http://siteurl/_api/Web/getFolderByServerRelativeUrl('Shared
documents')/Files/add(url='NewFile.txt', overwrite=true) http://siteurl/_api/web/currentuser/email
Sample URLs
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
17 | SharePoint Saturday Italy – Rome – 25 January 2014
OPTION 1
var formDigest = '';$.ajax({ url: http://siteurl/_api/contextinfo type: 'POST', contentType: 'application/json;odata=verbose', headers: { 'Accept': 'application/json;odata=verbose'}, success: function (data) { formDigest = data.d.GetContextWebInformation.FormDigestValue; }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); }, async: false });
OPTION 2
var formDigest = $(‘__REQUESTDIGEST’).val();
Get digest
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
18 | SharePoint Saturday Italy – Rome – 25 January 2014
$.ajax({ url: '/_api/web/lists/getByTitle(\'LIST NAME\')/items', type: 'POST', data: JSON.stringify(JSON OBJECT), contentType: 'application/json;odata=verbose', headers: { 'content-type': 'application/json;odata=verbose', 'Accept': 'application/json;odata=verbose', 'X-RequestDigest': 'DIGEST VALUE' }, success: function (data) { //... }, error: function (jqXHR, textStatus, errorThrown) { //... }});
Create new item
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
19 | SharePoint Saturday Italy – Rome – 25 January 2014
Edit an item
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
$.ajax({ url: 'http://siteurl/_api/web/lists/getByTitle(\'LIST NAME\')/items(ITEM ID)', type: 'POST', data: JSON.stringify(JSON MODIFIED OBJECT), contentType: 'application/json;odata=verbose', headers: { 'content-type': 'application/json;odata=verbose', 'Accept': 'application/json;odata=verbose', 'X-RequestDigest': 'DIGEST VALUE', 'X-HTTP-Method': 'MERGE', //or PUT 'IF-MATCH': '*' }, success: function (data) { //... }, error: function (jqXHR, textStatus, errorThrown) { //... }});
Note: For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property. For PUT requests, if you do not specify all required properties in object updates, the REST service returns an exception.
20 | SharePoint Saturday Italy – Rome – 25 January 2014
$.ajax({ url: 'http://siteurl/_api/web/lists/getByTitle(\'LIST NAME\')/items(ITEM ID)', type: 'POST', contentType: 'application/json;odata=verbose', headers: { 'content-type': 'application/json;odata=verbose', 'Accept': 'application/json;odata=verbose', 'X-RequestDigest': 'DIGEST VALUE', 'X-HTTP-Method': 'DELETE', 'IF-MATCH': '*' }, success: function (data) { //... }, error: function (jqXHR, textStatus, errorThrown) { //... }});
Delete an item
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
21 | SharePoint Saturday Italy – Rome – 25 January 2014
Demo
Tips for survivors
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
22 | SharePoint Saturday Italy – Rome – 25 January 2014
Limit response length! Request only data that you want to use,
with the $select parameter Paginate response where you can Use JSON (you get a smaller payload)
Limit the number of requests Remember that you are a client and that
the request comes from a server Request data in async way Take care of concurrency (using IF-MATCH
header)
General tips
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
23 | SharePoint Saturday Italy – Rome – 25 January 2014
Methods and resources are NOT case-sensitive
OData operators are case sensitive
Tips for survivors (0)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
24 | SharePoint Saturday Italy – Rome – 25 January 2014
Use an helper class to concat URLs
SharePoint 2013 REST Js helperhttps://www.nuget.org/packages/d4s.sp2013.rest/
Tips for survivors (1)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
self.webUrl() .SPItemsFromList('Rubrica') .SPSelect('EMail', 'Title', 'FirstName', 'Id') .SPFilterStartsWith('FirstName','Peppe') .SPOrderBy('FirstName','asc') .SPTop(1) IS BETTER THAN...
http://siteurl/_api/web/lists/getByTitle('Rubrica')/items?$select=EMail,Title,FirstName,Id&$filter=startsWith(FirstName, ‘Peppe')&$orderby=FirstName asc&$top=1
25 | SharePoint Saturday Italy – Rome – 25 January 2014
How to specify multiple filters with $filter parameter
Using OData logical operators Ex: and, or, not, all http://www.odata.org/documentation/odata-v3-
documentation/url-conventions/#512_Filter_System_Query_Option
Tips for survivors (2)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
$.ajax({ url: 'http://siteurl/_api/web/lists?$filter=(BaseTemplate eq 101) and (startswith(Title,\'Shared\'))', type: 'GET',
//... },});
26 | SharePoint Saturday Italy – Rome – 25 January 2014
Manage lookup values using the "slash syntax" Both in filter and select statements
Also for "users and groups" columns
Tips for survivors (3)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
http://siteurl/_api/web/lists?$expand=LookupColumn/Id&$select=Title,LookupColumn/Id$filter=LookupColumn/Id eq 1
http://siteurl/_api/web/lists?$select=Title,Author/Title&$expand=Author/Title
27 | SharePoint Saturday Italy – Rome – 25 January 2014
Use __next property, instead of $top and $skip parameters, to paginate list items
Tips for survivors (4)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
28 | SharePoint Saturday Italy – Rome – 25 January 2014
Cross-domain queries
Tips for survivors (5)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
var executor = new SP.RequestExecutor(appWebUrl);executor.executeAsync({ url: appWebUrl + "/_api/SP.AppContextSite(@target)/web/lists?$select=Title&@target='" + hostWebUrl + "'", method: 'GET', headers: { 'Accept': 'application/json; odata=verbose' }, success: function (data) { var jsonObject = JSON.parse(data.body); var lists = jsonObject.d.results; $.each(lists, function (index, list) { //never use this append!! it's only for demoing... $('#hostWebListsREST').append('<li>' + list.Title + '</li>'); }); }, error: function (data, errorCode, errorMessage) { alert(errorMessage); }});
29 | SharePoint Saturday Italy – Rome – 25 January 2014
Update digest if you’re using SPA (Single Page Applications)
Tips for survivors (6)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
$.ajax({ url: '/api/contextinfo', method: "POST", headers: { 'Accept': 'application/json; odata=verbose' }, success: function (data) { $('#__REQUESTDIGEST').val(data.d.GetContextWebInformation.FormDigestValue) }, error: function (data, errorCode, errorMessage) { alert(errorMessage) }});
30 | SharePoint Saturday Italy – Rome – 25 January 2014
Files management The property BinaryStringResponseBody Patch for SP.RequestExecutor.js
Tips for survivors (7)
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
var fileContentUrl = "/_api/web/GetFileByServerRelativeUrl('/docLib/file.docx')/$value"; var executor = new SP.RequestExecutor(appweburl);executor.executeAsync({ url: fileContentUrl, method: "GET", binaryStringResponseBody: true, success: function (data) {
//binary data available in data.body var result = data.body; }});
31 | SharePoint Saturday Italy – Rome – 25 January 2014
Demo
Tips for survivors
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
32 | SharePoint Saturday Italy – Rome – 25 January 2014
Operations are a subset of the Client Object Model Client Object Model is a subset of the
Server Object Model… No request batching No elevation of privilegies OData is not fully implemented 256 characters for URLs Items pagination with $top and $skip it’s
bugged
Limits
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
33 | SharePoint Saturday Italy – Rome – 25 January 2014
Q&A
[email protected] - @PeppeDotNet – peppedotnet.it – dev4side.com
34 | SharePoint Saturday Italy – Rome – 25 January 2014
Bella!www.peppedotnet.itwww.dev4side.com
35 | SharePoint Saturday Italy – Rome – 25 January 2014
Session Feedback
SharePoint 2013 REST API tips and trickshttp://www.surveymonkey.com/s/NVDDR52