SharePoint REST API - 一個請求批量操作

Justin-Liu發表於2017-10-23

部落格地址:http://blog.csdn.net/FoxDave

本篇主要講解如何應用$batch查詢選項來批量執行REST/OData請求,它將多個操作捆綁到一個請求中,可以改進應用程式的效能。

$batch選項執行摘要

SharePoint Online(也包括SharePoint 2016)和Office 365的API實現了OData的$batch查詢選項,下面羅列了一些主要的點:

1. 請求URL由根服務URL和$batch選項構成,例如https://fabrikam.sharepoint.com/_api/$batch或https://fabrikam.office365.com/api/v1.0/me/$batch。

2. HTTP請求的MIME型別為multipart/mixed。

3. 請求的body被請求頭的邊界字串分割成了相對獨立的部分。

4. 請求body的每個部分有自己的HTTP動作符和REST URL,還有內部的body。

5. 一個部分可以是讀操作或寫操作的變更集合或函式呼叫。變更集合本身的MIME型別是multipart/mixed,它裡面的部分包含插入、更新或刪除操作。

6. 最後一點需要注意,不支援“全部或沒有”這種表達,變更集合中的操作是相對獨立的,任何失敗的部分都不會影響其他的,並且也不會回滾,這一點在開發的時候需要留意。

程式碼示例

C#:OfficeDev/Core.ODataBatch

JavaScript:andrewconnell/sp-o365-rest

請求和響應的示例

下面是一個帶有兩個GET操作的HTTP請求從兩個不同列表獲取列表項標題的請求和響應示例。

POST https://fabrikam.sharepoint.com/_api/$batch HTTP/1.1
Authorization: Bearer <access token omitted>
Content-Type: multipart/mixed; boundary=batch_e3b6819b-13c3-43bb-85b2-24b14122fed1
Host: fabrikam.sharepoint.com
Content-Length: 527
Expect: 100-continue

--batch_e3b6819b-13c3-43bb-85b2-24b14122fed1
Content-Type: application/http
Content-Transfer-Encoding: binary

GET https://fabrikam.sharepoint.com/_api/Web/lists/getbytitle('Composed%20Looks')/items?$select=Title HTTP/1.1

--batch_e3b6819b-13c3-43bb-85b2-24b14122fed1
Content-Type: application/http
Content-Transfer-Encoding: binary

GET https://fabrikam.sharepoint.com/_api/Web/lists/getbytitle('User%20Information%20List')/items?$select=Title HTTP/1.1

--batch_e3b6819b-13c3-43bb-85b2-24b14122fed1--
下面是帶有一個DELETE操作和一個GET操作的請求示例
POST https://fabrikam.sharepoint.com/_api/$batch HTTP/1.1
Authorization: Bearer <access token omitted>
Content-Type: multipart/mixed; boundary=batch_7ba8d60b-efce-4a2f-b719-60c27cc0e70e
Host: fabrikam.sharepoint.com
Content-Length: 647
Expect: 100-continue

--batch_7ba8d60b-efce-4a2f-b719-60c27cc0e70e
Content-Type: multipart/mixed; boundary=changeset_efb6b37c-a5cd-45cb-8f5f-4d648006e65d

--changeset_efb6b37c-a5cd-45cb-8f5f-4d648006e65d
Content-Type: application/http
Content-Transfer-Encoding: binary

DELETE https://fabrikam.sharepoint.com/_api/Web/lists/getbytitle('OldList') HTTP/1.1
If-Match: "1"

--changeset_efb6b37c-a5cd-45cb-8f5f-4d648006e65d--
--batch_7ba8d60b-efce-4a2f-b719-60c27cc0e70e
Content-Type: application/http
Content-Transfer-Encoding: binary

GET https://fabrikam.sharepoint.com/_api/Web/lists HTTP/1.1

--batch_7ba8d60b-efce-4a2f-b719-60c27cc0e70e--
感興趣想了解更多關於OData庫資訊的可以訪問官網

SharePoint REST介面部分的講述就到這裡。

相關文章