0. SharePoint 2013使用_api來標識出 REST SERVICE,REST Service實際上是 client.svc web service的一部分,但爲了簡化 REST URI的構造以及縮短REST URI的長度,使用 _api 來替代 _vti_bin/client.svc,例如, 你可使用 http://server/site/_vti_bin/client.svc/web/lists 來替代 http://server/site/_api/web/lists;然而URL有256字符長度的限制,因此建議使用 _api 慣例;可參考此文章中的 Reference the SharePoint 2013 REST service in your endpoint URI 章節;javascript
SharePoint 2013 REST Syntax Posters.pdfjava
工具:Chrome瀏覽器中的 Advanced Rest Client Application插件web
1. Search REST API的query(GET)能夠設置返回json格式的結果,存儲在data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results中,results是個數據集合,序號從0開始;ajax
2. 使用REST API獲取(GET)數據時,若返回多條記錄,則返回值存儲在data.d.results中,results是個數據集合,序號從0開始,每個result包含一個對象單元信息,例如:一個List Item的全部屬性,如代碼所示;若返回單條記錄,則返回值存儲在data.d中;json
{ "__metadata":{"id":"b719e719-e4cc-445c-9c7c-0250aba4338a", "uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)", "etag":"\"4\"","type":"SP.Data.TasksListItem"}, "FirstUniqueAncestorSecurableObject":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/FirstUniqueAncestorSecurableObject"}}, "RoleAssignments":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/RoleAssignments"}}, "AttachmentFiles":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/AttachmentFiles"}}, "ContentType":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/ContentType"}}, "FieldValuesAsHtml":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/FieldValuesAsHtml"}}, "FieldValuesAsText":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/FieldValuesAsText"}}, "FieldValuesForEdit":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/FieldValuesForEdit"}}, "File":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/File"}}, "Folder":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/Folder"}}, "ParentList":{"__deferred":{"uri":"https://gjq-11683d04060f3b.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'b44e6daf-ee1e-4249-987f-2f9305cdc884')/Items(1)/ParentList"}}, "FileSystemObjectType":0, "Id":1, "ContentTypeId":"0x0108005943A401D04CAD47AE81ABAA54AA39A3", "Title":"Test", "PredecessorsId":{"__metadata":{"type":"Collection(Edm.Int32)"},"results":[]}, "Priority":"(2) Normal", "Status":"Not Started", "PercentComplete":0.79, "AssignedToId":11, "TaskGroupId":null, "Body":"<div></div>", "StartDate":"2014-08-10T16:00:00Z", "DueDate":"2014-08-27T16:00:00Z", "RelatedItems":null, "WorkflowLink":null, "OffsiteParticipant":null, "OffsiteParticipantReason":null, "WorkflowOutcome":null, "WorkflowName":null, "GUID":"2c618f60-7fae-4689-a652-52458ae60dd6", "ID":1, "Modified":"2014-08-12T03:41:59Z", "Created":"2014-08-11T01:57:18Z", "AuthorId":11, "EditorId":11, "OData__UIVersionString":"4.0", "Attachments":false }
3. 使用REST API的一些建議:api
If you’re not using the cross-domain library, include an X-RequestDigest header to send the form digest value in all POST requests and a content-lengthheader for POST requests that send data in the request body.瀏覽器
If you're not making cross-domain requests, remove SP.AppContextSite(@target) and ?@target='<host web url>' from the endpoint URI.服務器
If you’re using OAuth, include an Authorization header ("Authorization": "Bearer " + <access token>) to send the OAuth access token.app
If you want the server to return responses in Atom format, remove the "accept": "application/json; odata=verbose" header.dom
4. 使用REST API獲取對象信息時,只能獲取到當前級別信息,相似於Client Object Model,好比 /_api/web/lists能夠得到全部list信息,但沒有list item的信息;例如:一個List的全部屬性,
{ "__metadata": { "id":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')", "uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')", "etag":"\"3\"", "type":"SP.List" }, "FirstUniqueAncestorSecurableObject":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/FirstUniqueAncestorSecurableObject"}}, "RoleAssignments":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/RoleAssignments"}}, "ContentTypes":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/ContentTypes"}}, "CreatablesInfo":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/CreatablesInfo"}}, "DefaultView":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/DefaultView"}}, "DescriptionResource":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/DescriptionResource"}}, "EventReceivers":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/EventReceivers"}}, "Fields":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/Fields"}}, "Forms":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/Forms"}}, "InformationRightsManagementSettings":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/InformationRightsManagementSettings"}}, "Items":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/Items"}}, "ParentWeb":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/ParentWeb"}}, "RootFolder":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/RootFolder"}}, "TitleResource":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/TitleResource"}}, "UserCustomActions":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/UserCustomActions"}}, "Views":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/Views"}}, "WorkflowAssociations":{"__deferred":{"uri":"https://gjq-11683d04060f3f.sharepoint.com/BasicOperationApp/_api/Web/Lists(guid'9b64f833-6b28-4bf4-b02d-31e6f1d649e6')/WorkflowAssociations"}}, "AllowContentTypes":true,"BaseTemplate":100,"BaseType":0,"ContentTypesEnabled":false,"CrawlNonDefaultViews":false,"Created":"2014-08-12T05:22:25Z", "DefaultContentApprovalWorkflowId":"00000000-0000-0000-0000-000000000000", "Description":"", "Direction":"none", "DocumentTemplateUrl":null, "DraftVersionVisibility":0, "EnableAttachments":true, "EnableFolderCreation":false, "EnableMinorVersions":false, "EnableModeration":false, "EnableVersioning":false, "EntityTypeName":"AccordionList", "ForceCheckout":false, "HasExternalDataSource":false, "Hidden":false, "Id":"9b64f833-6b28-4bf4-b02d-31e6f1d649e6", "ImageUrl":"/_layouts/15/images/itgen.png?rev=37", "IrmEnabled":false, "IrmExpire":false, "IrmReject":false, "IsApplicationList":false, "IsCatalog":false, "IsPrivate":false, "ItemCount":3, "LastItemDeletedDate":"2014-08-12T05:22:25Z", "LastItemModifiedDate":"2014-08-13T06:16:41Z", "ListItemEntityTypeFullName":"SP.Data.AccordionListItem", "MultipleDataList":false, "NoCrawl":false, "ParentWebUrl":"/", "ParserDisabled":false, "ServerTemplateCanCreateFolders":true, "TemplateFeatureId":"00bfea71-de22-43b2-a848-c05709900100", "Title":"Accordion" }
5. REST Search API時,默認的rowlimit是10,即默認返回10條記錄;
6. 使用REST API的POST方法建立新內容時,返回的信息存儲在data.d中,好比data.d.Id;
7. REST API 不能修改文件夾的Name,詳情請參考此處或者此處;
8. REST API在更新file內容時,只能使用PUT,更新文件的metadata時,須要將文件看做一個item;
If you want to update a file's metadata, you'll have to construct an endpoint that reaches the file as a list item. You can do this because each folder is also a list, and each file is also a list item. Construct an endpoint that looks like this: https://<site url>/_api/web/lists/getbytitle('Documents')/items(<item id>). Working with lists and list items with REST explains how to update a list item's metadata.
9. 使用REST API獲取item信息時,Look Up字段會發生一些變化,好比:有一個內部名稱爲Zone的列,查詢出來的數據中找不到Zone列,而會有個ZoneId字段,值爲被查詢item的ID值;若是想獲得Zone的顯示名稱,可以使用$expand來獲取:
1. 在$select=中能夠寫上Zone/Id,Zone/ColumnX;
2. 在$expand=中必須寫上Zone;
注:Zone爲當前列表的Look up字段;ColumnX爲被查詢列表的任何字段的內部名稱;
10. 若是不使用cross-domain類庫,在進行POST操做時,都要在headers中添加X-RequestDigest參數,默認賦值是$("#__REQUESTDIGEST").val();
11. 過濾操做須要使用$filter,例如,只須要Title字段以「B」開頭的數據:$filter=startswith(Title, 'B');只須要Title字段包含「B」的數據:$filter=substringof('B',Title);
12. REST API - GET
$.ajax({ url: "https://XXX.sharepoint.com/_api/web/lists/GetByTitle('XXX')/items", type: "GET", headers: {"Accept": "application/json;odata=verbose"}, success: function(data){ if(data.d.results){ var $selectObj = $("<select id='deptSelect'></select>"); $.each(data.d.results, function(index, item){ $selectObj.append($("<option></option>").attr("value", item.ID + item.Title).text(item.Title)); }); $("#getDiv").append($selectObj); $("#getDiv").append("<br/>"+JSON.stringify(data.d.results)); } }, error: function(xhr){ alert(xhr.status+': '+xhr.statusText); } });
注意:因爲服務器端分頁的限制,默認狀況下,每次只能獲取100條數據,但可使用$top參數來指定一次要獲取多少條數據,但最大不能超過5000;還可使用__next來獲取下一頁的100條數據,請參考此處;
13. REST API - POST (create)
var newItem={ "__metadata":{"type": "SP.Data.Region_x0020_ApproversListItem"}, "Title": "Test Dept", "Region": "GCN" }; $.ajax({ url: "https://XXX.sharepoint.com/_api/web/lists/GetByTitle('XXX')/items", type: "POST", contentType: "application/json;odata=verbose", data: JSON.stringify(newItem), headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }, success: function(data){ alert(JSON.stringify(data.d.Id)); }, error: function(xhr){ alert(xhr.status+': '+xhr.statusText); } });
14. REST API - POST (update)
var updatedItem={ "__metadata":{"type":"SP.Data.Region_x0020_ApproversListItem"}, "Title": "Test Dept Again" }; $.ajax({ url: "https://XXX.sharepoint.com/_api/web/lists/GetByTitle('XXX')/items(40)", type: "POST", contentType: "application/json;odata=verbose", data: JSON.stringify(updatedItem), headers:{ "ACCEPT": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "X-HTTP-METHOD": "MERGE", "IF-MATCH": "*" }, success: function(){ //此處沒有data參數 getListItem(); }, error: function(xhr){ alert(xhr.status+': '+xhr.statusText); } });
15. REST API - DELETE
$.ajax({ url: "https://XXX.sharepoint.com/_api/web/lists/GetByTitle('XXX')/items(43)", type: "POST", headers:{ "Accept": "application/json;odata=verbose", "X-Http-Method": "DELETE", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "If-Match": "*" }, success: function(data){ alert(JSON.stringify(data)); }, error: function(xhr){ alert(xhr.status+': '+xhr.statusText); } });
16. 在進行POST操做時,須要先獲得metadata中的type屬性值,方法是:http://XXXX/sites/XXX/_api/web/lists/getbytitle('listName')?$select=ListItemEntityTypeFullName
17. SharePoint 2016及 Office 365支持 REST API批量操做(Batch),可參考此處;
18. REST API 使用的uri中,SharePoint名稱(好比,列表名,列名)是大小寫敏感的,oData的名稱是大小寫不敏感;在使用$filter等條件語句進行篩選對比時,非數字類型值須要添加單引號,好比 userName eq 'ABC';
19. 使用REST API獲取當前用戶的登陸名:
<script type="text/javascript"> var userid= _spPageContextInfo.userId; var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")"; var requestHeaders = { "accept" : "application/json;odata=verbose" }; $.ajax({ url : requestUri, contentType : "application/json;odata=verbose", headers : requestHeaders, success : onSuccess, error : onError }); function onSuccess(data, request){ var loginName = data.d.LoginName; alert(loginName); } function onError(error) { alert("error"); } </script>
20. 建立一個 Custom REST Service,可參考此文章;重要一點是:無需修改Web Config文件,只須要在.svc文件聲明中加入如下代碼便可:
<%@ ServiceHost Language="C#" Debug="true" Service="SPRESTService.CustomRESTService, $SharePoint.Project.AssemblyFullName$" CodeBehind="CustomRESTService.svc.cs" Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
如需在聲明中使用 token 符 "$SharePoint.Project.AssemblyFullName$",須要在project文件(.csproj文件) 中加入如下代碼:
<PropertyGroup> ... <SandboxedSolution>False</SandboxedSolution> <TokenReplacementFileExtensions>svc</TokenReplacementFileExtensions> </PropertyGroup>
21. 在Custom REST Service時, 每一個 OperationContract的 Name屬性用於標識這個操做,是惟一的,在返回值中能夠體現出來,返回值爲 Name + 'Result',例如,在ajax回調函數中使用時即爲 response.GetAllPresidentsResult ;UriTemplate屬性是訪問此操做的路徑,也是惟一的;
22. 若要獲取一個web根目錄下的全部folder,可使用一下REST API:
http://site url/_api/web/folders
獲得的結果便是在SPD中看到的樣子:
REST返回的結果可能還會包含一下以"_vti_"開頭的文檔庫或列表地址,這些是FrontPage的遺產物,無需在乎,詳情可參考此文章;
23. SharePoint REST API中的 /folders 和 /files 接口都只能獲得當前文件夾下的 子文件夾 或者 文件,而不能遞歸讀取全部 子文件夾 或 文件;
http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents')/Files http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents')/Folders
而 /items 接口卻能夠獲得一個 list 或者 library 全部item,包括文件和文件夾;
http://host url/sites/jacky/_api/Web/Lists(guid'9957f1e6-a35a-4888-a770-d5325c5cfe74')/Items
24. $expand 至關於擴展查詢,將子查詢對象的結果集成到當前此次調用中來,好比:
使用 http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents') 接口咱們能夠獲得Documents 這個文件夾的一些信息,返回結果以下:
若是加上$expand 對象,將 REST URI 改成:http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents')?$expand=Folders,Files 即 加上了 查詢Folders 和 Files的子語句,返回的結果爲:
至關於,在查詢當前文件夾信息的同時,也進行了下面兩個查詢,並將結果一次性返回:
http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents')/Files http://host url/sites/jacky/_api/Web/GetFolderByServerRelativeUrl('/sites/jacky/Documents')/Folders
25. 在使用$select時,若是須要選擇的屬性位於一個集合(例如 results)中,那麼在路徑中能夠忽略掉 results (此爲虛擬節點),直接寫須要的屬性,好比下圖,若是須要選擇 Title屬性,不須要寫成:$select=ListItemAllFields/RoleAssignments/results/Member/Users/results/Title,直接寫成 $select=ListItemAllFields/RoleAssignments/Member/Users/Title 便可;
26.