SharePoint 2013 REST APIs

31
#CDays14 – Milano 25, 26 e 27 Febbraio 2014 SHA02 – Le REST API di SharePoint 2013 Giuseppe Marchi Dev4Side S.r.l. – SharePoint MVP [email protected] - @PeppeDotNet http://www.peppedotnet.it http://www.dev4side.com

description

Introduction to this new level of APIs in SharePoint 2013.

Transcript of SharePoint 2013 REST APIs

Page 1: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

SHA02 – Le REST API di SharePoint 2013

Giuseppe MarchiDev4Side S.r.l. – SharePoint MVP

[email protected] - @PeppeDotNet

http://www.peppedotnet.ithttp://www.dev4side.com

Page 3: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 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

Page 4: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Agenda• What’s REST?

• What’s REST in SharePoint

• SharePoint 2013 API changes What’s new with REST interface

• New REST APIs syntax

• Basic operators and actions

• General tips

• Known limits

Page 5: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

What’s REST?• REST = Representational State Transfer

It’s an architecture style for designing networked applications RESTful applications use HTTP requests to post data (create and/or

update), read data (e.g., make queries), and delete data. Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operations.

REST is a lightweight alternative to Web Services

• It’s an architectural style, awesome for cross-platform apps

• Easier and smaller than SOAP

• Easy to use with Javascript, than C#

Page 6: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

What’s REST in SharePoint?

Page 7: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

What’s REST in SharePoint?• It’s another way to consume data, use all the advanced

services and functionalities exposed by SharePoint from your own client applications

• in a secure way

• … all done with a simple HTTP request!

Page 8: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

What we had in the past?• MOSS 2007

SOAP Services

• SharePoint 2010 SOAP Services 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!

Page 9: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

What we have now – New 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

Page 10: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

demoOur first call to SharePoint 2013 REST APIs

Page 11: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 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.

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

Page 12: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

URL syntax for REST calls• 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 (default entry point + resource)

Es: web, site collection, list, file, sql table, user, namespace, method, etc… Part 3 - Query strings options (OData operators)

Es: $filter, $select, etc…

Full documentation on MSDN: http://msdn.microsoft.com/en-us/library/office/dn292556.aspx

Page 13: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Allowed HTTP methods• Each REST command is a POST, GET, PUT, MERGE or DELETE

HTTP request (mapping to CRUD) where the specific resource is in the URL and into request data READ -> GET HTTP request CREATE -> HTTP POST request UPDATE -> HTTP POST PUT or HTTP POST MERGE request DELETE -> HTTP DELETE request

Page 14: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

demoLet’s play with _api

Page 15: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Sample URLshttp://siteurl/_api/webhttp://siteurl/_api/web/listshttp://siteurl/_api/web/lists?$filter=BaseTemplate eq 101http://siteurl/_api/web/lists?$orderby=Title aschttp://siteurl/_api/web/lists?$top=5&$skip=5http://siteurl/_api/web/lists?$filter=startswith(Title, 'Shared')http://siteurl/_api/web/lists/getByTitle('Contacts')http://siteurl/_api/web/lists/getByTitle('Contacts')/itemshttp://siteurl/_api/web/lists/getByTitle('Contacts')/items(1)http://siteurl/_api/web/lists/getByTitle('Contacts')/items(1)/Titlehttp://siteurl/_api/web/lists/getByTitle('Contacts')/items(1)?$select=Titlehttp://siteurl/_api/web/lists/getbytitle('shared documents')/rootfolder/folders?$select=Namehttp://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

Page 16: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

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)

RESOURCE PATH

Client Object Model APIs

1 ~ 1

Page 17: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

How to compone a query• 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!

Page 18: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

demoHow to compone a query

Page 19: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations – Read (Javascript)$.ajax({ url: '/_api/web/lists/getByTitle(\'LIST NAME\')/items', type: 'GET', headers: {

'Accept': 'application/json;odata=verbose', }, success: function (data) { $.each(data.d.results, function(index, items) {

//... } }, error: function (jqXHR, textStatus, errorThrown) { //... }});

Page 20: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations – Read (C#)//urlstring url = "http://sp2013/_api/web/lists?$select=Title";

//credenzialiCredentialCache credentials = new CredentialCache();credentials.Add(new Uri(url), "NTLM", CredentialCache.DefaultNetworkCredentials);

//richiesta HTTPHttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);request.Credentials = credentials;request.Method = "GET";request.Accept = "application/atom+xml;odata=verbose";request.ContentLength = 0;

//lettura risposta HTTPStream postStream;HttpWebResponse response = (HttpWebResponse)request.GetResponse();string results = GetHTTPResponse(response, out postStream, out results);XmlDocument doc = new XmlDocument();doc.LoadXml(results);XmlNamespaceManager namespaces = new XmlNamespaceManager(new NameTable());namespaces.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");var lists = doc.SelectNodes("//d:Title", namespaces);foreach (XmlNode list in lists) Console.WriteLine(list.InnerText);

Page 21: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations - Insert$.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) { //... }});

Page 22: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations - Insert$.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) { //... }});

Page 23: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

The digest• It’s a token that enables SharePoint to validate current user

session

• It’s required for every POST call to REST APIs in which you change data (INSERT, UPDATE, DELETE) and shall be the value of the HTTP header: X-RequestDigest

• Where we can find this value?

Page 24: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

The digest – How to find it?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();

Page 25: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations - Update$.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.

Page 26: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Basic operations - Delete$.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) { //... }});

Page 27: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

General tips• 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)

Page 28: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Known limits• 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

Page 29: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

BELLA! www.peppedotnet.itwww.dev4side.com

Page 30: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Do you SharePoint?• SharePoint & Office Conference 2014

27-28 Maggio 2014

• http://www.sharepointconference.it/

• Perché non puoi mancare I migliori speaker italiani ed internazionali 30 sessioni tecniche + video registrati Roundtable Ask the Expert

• Super Early Bird fino al 28 Marzo 2014!

Page 31: SharePoint 2013 REST APIs

#CDays14 – Milano 25, 26 e 27 Febbraio 2014

Q&ATutto il materiale di questa sessione su

http://www.communitydays.it/

Lascia il feedback su questa sessione,

potrai essere estratto per i nostri premi!

Seguici su

Twitter @CommunityDaysIT

Facebook http://facebook.com/cdaysit

#CDays14