Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | spssthlm |
View: | 1,124 times |
Download: | 3 times |
Understanding the REST API of SharePoint 2013
#SPSSTHLM17Paolo Pialorsi – [email protected] 25th, 2014
SharePoint Saturday
Stockholm
Thanks to our sponsors!
SharePint
Silver
Bronze
Raffle
Platinum
Gold
Something about me Consultant, project manager and trainer since
1996 Company of my own: www.pialorsi.com
More than 40 Microsoft certification exams passed Microsoft Certified Solution Master – Charter SharePoint
Focused on SharePoint since 2002 Author of 10 books about XML, SOAP, .NET, LINQ
and SharePoint Microsoft SharePoint 2010 Developer Reference, Microsoft Press Microsoft SharePoint 2013 Developer Reference, Microsoft Press Build Windows 8 Apps with Microsoft Visual C# and
Visual Basic Step by Step, Microsoft Press
Speaker at main IT conferences
Agenda• _api Architecture• Querying data• Managing data• Cross domain calls• Security
_API architectureLet’s see how it works
JavaScript Library
Silverlight Library
.Net CLR Library
Custom Client Code
Client
Server
_api is new alias for _vti_bin/client.svc
_api Architecture
RESTODataJSON
CSOM
_api Consumers
DEMOSome sample URI endpoints
Sample URLs _api/web/lists _api/web/lists/getByTitle(‘Documents') _api/web/Lists/getByTitle('Documents')/Items _api/web/Lists/getByTitle('Documents')/Items(4) _api/web/CurrentUser _api/web/SiteUsers _api/web/getAvailableWebTemplates(lcid=1033) _api/web/RoleAssignments/GetPrincipalId(1)/Member
Living in a REST-ful world REST = Representational State Transfer Main capabilities and features
Lighter than SOAP Easier to consume from jQuery/JavaScript
Can leverage either JSON or ATOM for data representation Cross-platform URL based Securable through OAuth or HTTP security
Supported HTTP methods GET: read operations POST: creation operations PUT: data modification (update)
All the required fields are mandatory
PATCH, MERGE: POST + X-Http-Method header MERGE for backward compatibility only Use PATCH, instead
DELETE: POST + X-Http-Method header
DEMOConsuming REST API from a developer perspective
_api Reference
http(s)://{Host Name}/{site}/_api/{namespace}/
{object}{property}{indexer(index)}{method({parameter},{parameter},…)}
Web Application Hostname
Site Collection (Optional)
API Namespace
Operation
Main namespaces site web SP.UserProfiles.PeopleManager ContextInfo search publishing social.feed
Querying dataLet’s read some real data …
_api is OData compliant Available query string arguments
$filter $select $orderby $top $skip $expand
Logical OperationsOperator Description Example
eq Equal /Suppliers?$filter=Address/City eq 'Redmond'
ne Not equal /Suppliers?$filter=Address/City ne 'London'
gt Greater than /Products?$filter=Price gt 20
ge Greater than or equal /Products?$filter=Price ge 10
lt Less than /Products?$filter=Price lt 20
le Less than or equal /Products?$filter=Price le 100
and Logical and /Products?$filter=Price le 200 and Price gt 3.5
or Logical or /Products?$filter=Price le 3.5 or Price gt 200
not Logical negation /Products?$filter=not endswith(Description,'milk')
Arithmetic Operators
Operator Description Example
add Addition /Products?$filter=Price add 5 gt 10
sub Subtraction /Products?$filter=Price sub 5 gt 10
mul Multiplication /Products?$filter=Price mul 2 gt 2000
div Division /Products?$filter=Price div 2 gt 4
mod Modulo /Products?$filter=Price mod 2 eq 0
Functions (1/3)Function Description Example
bool substringof(string searchString, string searchInString)
Returns a boolean value stating if the value provided in the first argument is a substring of the second argument. Can be used as a replacement for the contains method.
substringof('Alfreds',CompanyName)
bool endswith(string string, string suffixString)
Returns a boolean value declaring if the string provided in the first argument ends with the string provided in the second argument.
endswith(CompanyName,'Futterkiste')
bool startswith(string string, string prefixString)
Returns a boolean value declaring if the string provided in the first argument starts with the string provided in the second argument.
startswith(CompanyName,'Alfr')
int length(string string)Returns an integer value representing the length of the string provided as argument.
length(CompanyName) eq 19
int indexof(string searchInString, string searchString)
Returns an integer value representing the index of the string provided in the second argument, which is searched within the string provided in the first argument.
indexof(CompanyName,'lfreds') eq 1
string replace(string searchInString, string searchString, string replaceString)
Replaces the string provided in the second argument with the string provided in the third argument, searching within the first string argument.
replace(CompanyName,' ', '') eq 'AlfredsFutterkiste'
string substring(string string, int pos)
Returns a substring of the string provided in the first argument, starting from the integer position provided in the second argument.
substring(CompanyName,1) eq 'lfreds Futterkiste'
Functions (2/3)Function Description Example
string substring(string string, int pos, int length)
Returns a substring of the string provided in the first argument, starting from the integer position provided in the second argument and stopping after a number of characters provided in the third integer argument.
substring(CompanyName,1, 2) eq 'lf'
string tolower(string string)Returns a string that is the lowercase conversion of the string provided as the string argument
tolower(CompanyName) eq 'alfreds futterkiste'
string toupper(string string)Returns a string that is the uppercase conversion of the string provided as the string argument
tolower(CompanyName) eq 'alfreds futterkiste'
string trim(string string)Returns a string trimmed from spaces, based on the string provided as argument.
trim(CompanyName) eq 'Alfreds Futterkiste'
string concat(string string1, string string2)Returns a string that is the concatenation of the two string arguments provided.
concat(concat(City,', '), Country) eq 'Berlin, Germany'
int day(DateTime datetimeValue)Returns an integer that corresponds to the day of the datetime value provided as argument.
day(BirthDate) eq 8
int hour(DateTime datetimeValue)Returns an integer that corresponds to the hours of the datetime value provided as argument.
hour(BirthDate) eq 1
int minute(DateTime datetimeValue)Returns an integer that corresponds to the minutes of the datetime value provided as argument.
minute(BirthDate) eq 0
int month(DateTime datetimeValue)Returns an integer that corresponds to the month of the datetime value provided as argument.
month(BirthDate) eq 12
Functions (3/3)Function Description Example
int second(DateTime datetimeValue)Returns an integer that corresponds to the seconds of the datetime value provided as argument.
second(BirthDate) eq 0
int year(DateTime datetimeValue)Returns an integer that corresponds to the year of the datetime value provided as argument.
year(BirthDate) eq 1948
double round(double doubleValue)Returns a double number that is the rounded value of the double value provided as argument.
round(Freight) eq 32
decimal round(decimal decimalValue)Returns a decimal number that is the rounded value of the decimal value provided as argument.
round(Freight) eq 32
double floor(double doubleValue)Returns a double number that is the floor value of the double value provided as argument.
floor(Freight) eq 32
decimal floor(decimal datetimeValue)Returns a decimal number that is the floor value of the decimal value provided as argument.
floor(Freight) eq 32
double ceiling(double doubleValue)Returns a double number that is the ceiling value of the double value provided as argument.
ceiling(Freight) eq 33
decimal ceiling(decimal datetimeValue)Returns a decimal number that is the ceiling value of the decimal value provided as argument.
ceiling(Freight) eq 33
bool IsOf(type value)Returns a boolean value stating if the target entity is of the type provided as argument.
isof('NorthwindModel.Order')
bool IsOf(expression value, type targetType)
Returns a boolean value stating if the expression provided as the first argument, is of the type provided as the second argument.
isof(ShipCountry,'Edm.String')
DEMOQuerying data
Sample Queryhttp://devbook.sp2013.local/_api/web/lists/GetByTitle(Documents')/RootFolder/Files?$expand=Author&$select=Name,Author,TimeLastModified&$orderby=TimeLastModified%20desc,Name&$skip=20&$top=10&$filter=substringof('Chapter',Name)%20eq%20true
Query Part Explanation
$expand=Author Expands the related object Author, while retrieving the documents.
$select=Name,Author,TimeLastModified Retrieves the fields Name, Author, and TimeLastModified.
$sort=TimeLastModified desc,Name Sorts the output descending by TimeLastModified, and ascending by Name.
$skip=20 Skips the first 20 items of the resultset (i.e. the first two pages of 10 items).
$top=10 Retrieves only the first 10 items of the resultset (i.e. the third page of 10 items).
$filter= substringof('Chapter',Name) eq true Retrieves only files with a file name that contains the literla "Chapter".
Managing dataBecause life changes …
How it works Leverages JSON requests
Plus some specific HTTP headers
Uses HTTP methods POST/PUT Plus X-Http-Method header
Be careful of cross-domain calls
Common Rules HTTP header IF-MATCH with ETag value
Only for lists and list items ETag returned as HTTP header while querying data
Returned also in JSON/ATOM responses
HTTP header X-RequestDigest See next slide …
User session validation Required X-RequestDigest HTTP header
Available as INPUT hidden: __REQUESTDIGEST jQuery: $("# __REQUESTDIGEST").val();
Available through: _api/ContextInfo JSON response includes: FormDigestValue
Sample ContextInfo in JSON format{
"d": { "GetContextWebInformation": { "__metadata": { "type":"SP.ContextWebInformation" }, "FormDigestTimeoutSeconds":1800, "FormDigestValue":"0x8B48E76BAF6C86A17CCEC50F9A29E7CBB85816B883417C52C10C67 FB19760517B774CD71E43517635386DE585E92A0262779824E5E0C7ECA905436A048AC85AC, 08 Jan 2013 01:11:57 -0000", "LibraryVersion":"15.0.4420.1017", "SiteFullUrl":"http://devbook.sp2013.local", "SupportedSchemaVersions": { "results": [ "14.0.0.0", "15.0.0.0" ] }, "WebFullUrl":"http://devbook.sp2013.local" } }}
DEMOEditing data
Cross-domain callsCrossing the river …
Cross-domain CSOM/JSOM calls from app web to host web
Are cross-domain calls app web site domain != host web site domain
Modern browser deny cross-domain calls We need to work around this … JSOM provides: SP.RequestExecutor
App Web Host Web
SP.RequestExecutor.js
IFrame(AppWebProxy.ASP
X)
1) Download .js library
2) Emit IFrame
3) Download proxy page
4) Make REST/CSOM call
5) Get response data
6) Get data back to app
Cross-Domain Call Flow
SP.RequestExecutor Arguments accepted
url: target URL method: HTTP method body: request body (JSON), optional headers: HTTP headers for the request
Accept, X-RequestDigest, X-HTTP-Method, IF-MATCH, etc. success: delegate in case of success error: delegate in case of failure
SecurityLeaving in a safe world
Authentication Techniques Anonymous
Read-only Require Use Remote
Interfaces permission
Windows integrated (NTLM, Kerberos)
OAuth
OAuth Requires a context access token Provided in the Authorization header
Bearer + access token
jQuery.ajax({ url: "http://hostname/_api/contextinfo", type: "POST", headers: { "Authorization": "Bearer " + accessToken, "accept": "application/json;odata=verbose", "contentType": "text/xml" },})
...and visit our sponsors who made this day possible!
Thank you!
Please rate this session...