SharePoint REST API - 基本操作(二)
部落格地址:http://blog.csdn.net/FoxDave
上一節講了SharePoint REST API的一些基本操作,本節將繼續介紹一些關於SharePoint REST API的內容。
構建和傳送HTTP請求常常會根據不同的語言、庫和Add-in而產生變化,所以你需要在切換環境的時候對請求做相應的修改。例如,JQuery AJAX請求使用data和type引數來指定請求的主體和型別,但是跨域庫請求使用body和method引數來指定這些值。
下面在講一些公共的跨環境差異。
SharePoint Add-in獲取和傳送表單摘要認證的方式
當你傳送一個POST請求時,請求必須在X-RequestDigest頭中包含表單摘要認證。但是在SharePoint Add-in中則不是。
對於SharePoint承載的add-in,可以直接傳遞下面的頭:
X-RequestDigest": $("__REQUESTDIGEST").val()
對於雲承載的Add-in分兩種情況:使用OAuth的,首先通過傳送請求到contextinfo終結點來獲取表單摘要認證的值,然後將它新增到請求中;使用JavaScript跨域庫的,你不需要指定表單摘要認證的值。預設情況下,SP.RequestExecutor方法會為你自動處理它,也會處理content-length的值。
使用OAuth的SharePoint Add-ins必須在請求中傳遞訪問令牌
雲承載的Add-in使用OAuth或跨域庫來授權訪問SharePoint的資料。遠端Web伺服器執行的程式碼必須使用OAuth來授權訪問SharePoint的資料。在這種情況下,你需要包含Authorization頭來傳送訪問令牌。
注意用JavaScript寫的雲承載的Add-in元件必須使用跨域庫中的SP.RequestExecutor物件來訪問SharePoint資料。跨域庫請求不需要包含訪問令牌。
在跨域請求中使用SP.AppContextSite終結點來更改context
傳送到資源終結點的請求在請求的url中被指定,使用如下格式:
_<site url>_/_api/ _<context>_/ _<resource>_ (example, https://contoso.com/_api/web/lists)
跨域庫請求在訪問Add-in的網站的資料時使用此種格式,是預設的上下文。但是如果要訪問承載該Add-in的網站或者是其他的網站,請求需要初始化一個上下文物件。使用URI中的SP.AppContextSite端點,如下表:
Add-in type | Cross-domain data access scenario | Example endpoint URI |
---|---|---|
Cloud-hosted | JavaScript add-in component accessing host web data by using the cross-domain library | /_api/SP.AppContextSite(@target)/web/lists?@target=' ' |
Cloud-hosted | JavaScript add-in component accessing data in a site collection other than the host web by using the cross-domain library (tenant-scoped add-ins only) | /_api/SP.AppContextSite(@target)/web/title?@target=' ' |
SharePoint-hosted | Add-in web component accessing data in another site collection (tenant-scoped add-ins only) | /_api/SP.AppContextSite(@target)/web/title?@target=' ' |
SharePoint Add-ins可以從查詢字串中獲取Add-in網站的URL和承載網站的URL,下面的程式碼展示瞭如何獲取。同時下面的程式碼也展示瞭如何引用在SP.RequestExecutor.js檔案中定義的跨域庫。
var hostweburl;
var appweburl;
// Get the URLs for the add-in web the host web URL from the query string.
$(document).ready(function () {
//Get the URI decoded URLs.
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
// Load the SP.RequestExecutor.js file.
$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", runCrossDomainRequest);
});
// Build and send the HTTP request.
function runCrossDomainRequest() {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" + hostweburl + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
}
// Get a query string value.
// For production add-ins, you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) return singleParam[1];
}
}
… // success and error callback functions
REST請求中使用的屬性下表展示了通常在HTTP請求中使用的SharePoint REST服務的屬性。
Properties | When required | Description |
---|---|---|
url | All requests | The URL of the REST resource endpoint. Example: http://<site url>/_api/web/lists |
method (or type) | All requests | The HTTP request method: GET for read operations and POST for write operations. POST requests can perform update or delete operations by specifying a DELETE, MERGE, or PUT verb in the X-HTTP-Method header. |
body (or data) | POST requests that send data in the request body | The body of the POST request. Sends data (such as complex types) that can't be sent in the endpoint URI. Used with the content-length header. |
Authentication header | Remote add-ins that are using OAuth to authenticate users. Does not apply when using JavaScript or the cross domain library. | Sends the OAuth access token (obtained from a Microsoft Access Control Service (ACS) secure token server) that's used to authenticate the user for the request. Example: "Authorization": "Bearer " + accessToken , where accessToken represents the variable that stores the token. Tokens must be retrieved by using server-side code. |
X-RequestDigest header | POST requests (except SP.RequestExecutor requests) | Remote add-ins that use OAuth can get the form digest value from the http://<site url>/_api/contextinfo endpoint. SharePoint-hosted add-ins can get the value from the #__REQUESTDIGEST page control if it's available on the SharePoint page. See Writing data by using the REST interface. |
accept header | Requests that return SharePoint metadata | Specifies the format for response data from the server. The default format is application/atom+xml . Example: "accept":"application/json;odata=verbose" |
content-type header | POST requests that send data in the request body | Specifies the format of the data that the client is sending to the server. The default format is application/atom+xml . Example: "content-type":"application/json;odata=verbose" |
content-length header | POST requests that send data in the request body (except SP.RequestExecutor requests) | Specifies the length of the content. Example: "content-length":requestBody.length |
IF-MATCH header | POST requests for DELETE, MERGE, or PUT operations, primarily for changing lists and libraries. | Provides a way to verify that the object being changed has not been changed since it was last retrieved. Or, lets you specify to overwrite any changes, as shown in the following example: "IF-MATCH":"*" |
X-HTTP-Method header | POST requests for DELETE, MERGE, or PUT operations | Used to specify that the request performs an update or delete operation. Example: "X-HTTP-Method":"PUT" |
binaryStringRequestBody | SP.RequestExecutor POST requests that send binary data in the body | Specifies whether the request body is a binary string. Boolean. |
binaryStringResponseBody | SP.RequestExecutor requests that return binary data | Specifies whether the response is a binary string. Boolean. |
相關文章
- Elasticsearch(二)——Rest APIElasticsearchRESTAPI
- 二. SpringCloud基本Rest微服務工程搭建SpringGCCloudREST微服務
- 筆記三:基本概念-文件、索引和 REST API筆記索引RESTAPI
- rest apiRESTAPI
- Elasticsearch 入門實戰(8)--REST API 使用二(Search API)ElasticsearchRESTAPI
- GraphQL API vs REST APIAPIREST
- elasticsearch(二)---基本資料操作Elasticsearch
- Spark REST API & metricsSparkRESTAPI
- Azure Cosmos DB (二) SQL API 操作SQLAPI
- 在REST API中支援批次操作的幾個不同方法 - mscharhagRESTAPI
- 【Azure API 管理】解決呼叫REST API操作APIM(API Management)需要認證問題(Authentication failed, The 'Authorization' header is missing)APIRESTAIHeader
- Django REST framework API 指南(21):SchemasDjangoRESTFrameworkAPI
- Harbor配置Swagger遠端REST APISwaggerRESTAPI
- rest-api設計風格RESTAPI
- Django REST framework API 指南(6):路由DjangoRESTFrameworkAPI路由
- Django REST framework API 指南(7):解析DjangoRESTFrameworkAPI
- Django REST framework API 指南(8):渲染DjangoRESTFrameworkAPI
- Django REST framework API 指南(27):SettingsDjangoRESTFrameworkAPI
- Django REST framework API 指南(15):限流DjangoRESTFrameworkAPI
- 夜刷:平衡二叉樹的基本操作二叉樹
- 深度解析Django REST Framework 批量操作DjangoRESTFramework
- Django REST framework API 指南(17):分頁DjangoRESTFrameworkAPI
- Django REST framework API 指南(18):版本控制DjangoRESTFrameworkAPI
- Elasticsearch Java High Level REST Client(Exists API)ElasticsearchJavaRESTclientAPI
- Elasticsearch Java High Level REST Client(Delete API)ElasticsearchJavaRESTclientdeleteAPI
- REST API簽名認證機制RESTAPI
- Django REST framework API 指南(13):認證DjangoRESTFrameworkAPI
- elasticsearch常用請求介面Rest API示例ElasticsearchRESTAPI
- Flask框架搭建REST-API服務Flask框架RESTAPI
- Pulsar 入門實戰(6)--Rest APIRESTAPI
- Django REST framework API 指南(23):返回 URLDjangoRESTFrameworkAPI
- Django REST framework API 指南(24):異常DjangoRESTFrameworkAPI
- Django REST framework API 指南(26):測試DjangoRESTFrameworkAPI
- Django REST framework API 指南(16):過濾DjangoRESTFrameworkAPI
- 在 .NET Core 中構建 REST APIRESTAPI
- MongoDB基本APIMongoDBAPI
- .net持續整合sonarqube篇之sonarqube基本操作(二)
- (16) SpringCloud-Eureka的REST API及API擴充套件SpringGCCloudRESTAPI套件
- Django REST framework API 指南(5):檢視集DjangoRESTFrameworkAPI