跳转至

Complete basic operations using SharePoint 2013 REST endpoints.note

Source: /Volumes/X9 Pro/ObsNotes/YoudaoYunNotes/默认笔记本/Complete basic operations using SharePoint 2013 REST endpoints.note.pdf Converted: 2025-12-10 12:19:23


SharePoint Add-ins

Learn how to perform basic create, read, update, and delete (CRUD) operations with the SharePoint

2013 REST interface.

Last modified: March 10, 2016

Applies to: apps for SharePoint | Office 365 | SharePoint Add-ins | SharePoint Foundation 2013 |

SharePoint Server 2013

You can perform basic create, read, update, and delete (CRUD) operations by using the

Representational State Transfer (REST) interface provided by SharePoint 2013. The REST interface

exposes all of the SharePoint entities and operations that are available in the other SharePoint client

APIs. One advantage of using REST is that you don’t have to add references to any SharePoint 2013

libraries or client assemblies. Instead, you make HTTP requests to the appropriate endpoints to

retrieve or update SharePoint entities, such as webs, lists, and list items. See

for a thorough introduction to the SharePoint 2013 REST interface and its

architecture.

and explain in

greater detail how to work with core SharePoint entities. See

for a sample that shows you how to do many of these operations in the context of an

ASP.NET web application written in C#.

For more details about the sets of APIs available on the SharePoint 2013 platform, see

. For information about how to use the other client APIs, see

,

, and

.

Complete basic operations using SharePoint 2013 REST

endpoints

Note

The name "apps for SharePoint" is changing to "SharePoint Add-ins". During the transition, the

documentation and the UI of some SharePoint products and Visual Studio tools might still use the

term "apps for SharePoint". For details, see .New name for apps for Office and SharePoint

Developing with the SharePoint client APIs and REST

Get to know the Share

Point 2013 REST service

Working with lists and list items with RESTWorking with folders and files with REST

SharePoint-Add-in-REST-OData-BasicD

ataOperations

Choose the ri

ght API set in SharePoint 2013 Complete

basic operations using JavaScript library code in SharePoint 2013Complete basic operations using

JavaScript library code in SharePoint 2013Build Windows Phone apps that access SharePoint

2013

HTTP operations in SharePoint 2013 REST services

The endpoints in the SharePoint 2013 REST service correspond to the types and members in the

SharePoint client object models. By using HTTP requests, you can use these REST endpoints to

perform typical CRUD (Create, Read, Update, and Delete) operations against SharePoint entities,

such as lists and sites.

Typically, endpoints that represent Read operations map to HTTP GET commands. Endpoints that

represent update operations map to HTTP POST commands, and endpoints that represent update or

insert operations map to HTTP PUT commands.

In SharePoint 2013, use POST to create entities such as lists and sites. The SharePoint 2013 REST

service supports sending POSTcommands that include object definitions to endpoints that represent

collections. For example, you could send a POST command that included a new list object definition

in ATOM to the following URL, to create a SharePoint list:

http:///_api/web/lists

For POST operations, any properties that are not required are set to their default values. If you

attempt to set a read-only property as part of a POST operation, the service returns an exception.

Use PUT and MERGE operations to update existing SharePoint objects. Any service endpoint that

represents an object property setoperation supports both PUT requests and MERGE requests.

For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain

their current property. For PUT commands, however, any properties you do not explicitly set are set

to their default properties. In addition, if you do not specify all required properties in object updates

when using HTTP PUT commands, the REST service returns an exception.

Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object

represented by that endpoint. In the case of recyclable objects, such as lists, files, and list items, this

results in a Recycle operation.

To use the REST capabilities that are built into SharePoint 2013, you construct a RESTful HTTP

request, using the OData standard, which corresponds to the client object model API you want to

use. Each SharePoint entity is exposed at an endpoint on the SharePoint 2013 site that you are

targeting, and its metadata is represented in either XML or JSON format. You can make the HTTP

requests in any language, including but not limited to JavaScript and C#.

To read information from a REST endpoint, you must know both the URL of the endpoint and the

OData representation of the SharePoint entity that is exposed at that endpoint. For example, to

retrieve all of the lists in a specific SharePoint site, you would make a GET request

to http:///_api/web/lists. You can navigate to this URL in your browser and see

the XML that gets returned. When you make the request in code, you can specify whether to receive

the OData representation of the lists in XML or JSON.

Reading data with the SharePoint 2013 REST interface

The following C# code demonstrates how to make this GET request that returns a JSON

representation of all of a site’s lists by using JQuery. It also assumes that you have a valid OAuth

access token that is stored in the accessToken variable. You do not need the access token if you

make this call from inside an add-in web, as you would in a SharePoint-hosted add-in. Note that you

cannot obtain an access token from code that is running on a browser client. You must obtain the

access token from code that is running on a server.

and explain how you can obtain an access

token.

This request would look a little different if you are writing your add-in in JavaScript but using the

SharePoint 2013 cross-domain library. In this case, you don’t need to provide an access token. The

following code demonstrates how this request would look if you are using the cross-domain library

and want to receive the OData representation of the lists as XML instead of JSON. (Because Atom is

the default response format, you don’t have to include an Accept header.) See

for more information about using the cross-

domain library.

Context Token OAuth flow for SharePoint Add-

ins Authorization Code OAuth flow for SharePoint Add-ins

C#

HttpWebRequest endpointRequest =1

(HttpWebRequest)HttpWebRequest.Create(2

"http:///_api/web/lists");3

endpointRequest.Method = "GET";4

endpointRequest.Accept = "application/json;odata=verbose";5

endpointRequest.Headers.Add("Authorization", 6

"Bearer " + accessToken);7

HttpWebResponse endpointResponse =8

(HttpWebResponse)endpointRequest.GetResponse();9

10

11

Access SharePoint 2

013 data from add-ins using the cross-domain library

JavaScript

The code in the following example shows you how to request a JSON representation of all of the lists

in a site by using C#. It assumes that you have an OAuth access token that you are storing in

the accessToken variable.

Many property values are returned when you retrieve a resource, but for some properties, you have

to send a GET request directly to the property endpoint. This is typical of properties that represent

SharePoint entities.

The following example shows how to get a property by appending the property name to the resource

endpoint. The example gets the value of the Author property from a File resource.

http:///_api/web/getfilebyserverrelativeurl('//')/author

var executor = new SP.RequestExecutor(appweburl);1

executor.executeAsync(2

{3

url:4

appweburl +5

"/_api/SP.AppContextSite(@target)/web/lists?@target='" +6

hostweburl + "'",7

method: "GET",8

success: successHandler,9

error: errorHandler10

}11

);12

13

C#

HttpWebRequest endpointRequest =

(HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");

1

endpointRequest.Method = "GET";2

endpointRequest.Accept = "application/json;odata=verbose";3

endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);4

HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();5

6

7

Getting properties that aren't returned with the resource

To get the results in JSON format, include an Accept header set

to "application/json;odata=verbose".

You can create and update SharePoint entities by constructing RESTful HTTP requests to the

appropriate endpoints, just as you do when you’re reading data. One key difference, however, is that

you use a POST request. When you’re updating entities, you also pass a PUT or MERGE HTTP

request method by adding one of those terms to the headers of your request as the value of the X-

HTTP-Method key. The MERGE method updates only the properties of the entity that you specify,

while the PUT method replaces the existing entity with a new one that you supply in the body of

the POST. Use the DELETE method to delete the entity. When you create or update an entity, you

must provide an OData representation of the entity that you want to create or change in the body of

your HTTP request.

Another important consideration when creating, updating, and deleting SharePoint entities is that if

you aren’t using OAuth to authorize your requests, these operations require the server’s request form

digest value as the value of the X-RequestDigest header. You can retrieve this value by making

a POST request with an empty body to http:///_api/contextinfo and extracting

the value of the d:FormDigestValue node in the XML that the contextinfo endpoint returns. The

following example shows an HTTP request to the contextinfo endpoint in C#.

If you’re using the authentication and authorization flow described in

, you don’t need to include the request digest in your requests.

If you're using the JavaScript cross-domain library, SP.RequestExecutor handles getting and sending

the form digest value for you.

Writing data by using the REST interface

C#

HttpWebRequest endpointRequest =1

(HttpWebRequest)HttpWebRequest.Create(2

"http:///_api/contextinfo");3

endpointRequest.Method = "POST";4

endpointRequest.Accept = "application/json;odata=verbose";5

HttpWebResponse endpointResponse =6

(HttpWebResponse)endpointRequest.GetResponse();7

8

9

Authorization and authentication

of SharePoint Add-ins

If you’re creating a SharePoint-hosted SharePoint Add-in, you don’t have to make a separate HTTP

request to retrieve the form digest value. Instead, you can retrieve the value in JavaScript code from

the SharePoint a page (if the page uses the default master page), as shown in the following example,

which uses JQuery and creates a list.

The following example shows how to update the list that is created in the previous example. The

example changes the title of the list, uses JQuery, and assumes that you are doing this operation in a

SharePoint-hosted add-in.

JavaScript

jQuery.ajax({1

url: "http:///_api/web/lists",2

type: "POST",3

data: JSON.stringify({ '__metadata': { 'type': 'SP.List' },

'AllowContentTypes': true,

4

'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list

description', 'Title': 'Test' }

5

),6

headers: { 7

"accept": "application/json;odata=verbose",8

"content-type": "application/json;odata=verbose",9

"content-length": ,10

"X-RequestDigest": $("#__REQUESTDIGEST").val()11

},12

success: doSuccess,13

error: doError14

});15

16

17

18

JavaScript

The value of the IF-MATCH key in the request headers is where you specify the etag value of a list or

list item. This particular value applies only to lists and list items, and it is intended to help you avoid

concurrency problems when you update those entities. The previous example uses an asterisk (*) for

this value, and you can use that value whenever you don’t have any reason to worry about

concurrency issues. Otherwise, you should obtain the etag value or a list or list item by performing

a GET request that retrieves the entity. The response headers of the resulting HTTP response will

pass the etag as the value of the ETag key. This value is also included in the entity metadata. The

following example shows the opening tag for the XML node that contains the list

information. The m:etagproperty contains the etag value.

jQuery.ajax({1

url: "http:///_api/web/lists/GetByTitle('Test')",2

type: "POST",3

data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New

title' }),

4

headers: { 5

"X-HTTP-Method":"MERGE",6

"accept": "application/json;odata=verbose",7

"content-type": "application/json;odata=verbose",8

"content-length": ,9

"X-RequestDigest": $("#__REQUESTDIGEST").val(),10

"IF-MATCH": "*"11

},12

success: doSuccess,13

error: doError14

});15

16

17

XML

The following example shows how to create a site in JavaScript.

<entry xml:base="

<entry xml:base="

<entry xml:base="

1

http://site

http://www.w3.org/2005/Atom

xmlns:d="

xmlns:d="

2

http://schemas.microsoft.com/ado/2007/08/dataservices

xmlns:m="

xmlns:m="

3

http://schemas.microsoft.com/ado/2007/08/dataservices/metadata

xmlns:georss="

xmlns:georss="

xmlns:georss="

4

http://www.georss.org/georss

http://www.opengis.net/gml

5

Creating a site with REST

JavaScript

Building and sending an HTTP request may vary according to language, library, and add-in type, so

you often need to change one or more request components when you're translating a request from

one environment to another. For example, jQuery AJAX requests use dataand type parameters to

specify the request body and type, but cross-domain library requests

use body and method parameters to specify those values.

The following sections describe other common differences across environments.

When you send a POST request, the request must include the form digest value in the X-

RequestDigest header. However, the way you get and send the value differs by add-in:

jQuery.ajax({1

url: "http:///_api/web/webinfos/add",2

type: "POST",3

data: JSON.stringify(4

{'parameters': {5

'__metadata': {'type': 'SP.WebInfoCreationInformation' },6

'Url': 'RestSubWeb',7

'Title': 'RestSubWeb',8

'Description': 'REST created web',9

'Language':1033,10

'WebTemplate':'sts',11

'UseUniquePermissions':false}12

}13

),14

headers: { 15

"accept": "application/json; odata=verbose", 16

"content-type":"application/json;odata=verbose",17

"content-length": ,18

"X-RequestDigest": $("#__REQUESTDIGEST").val() 19

},20

success: doSuccess,21

error: doError22

});23

24

How REST requests differ by environment

The way you get and send the form digest value depends on the add-in

In SharePoint-hosted add-ins, you can just pass the following header:

"X-RequestDigest": $("#__REQUESTDIGEST").val()

contextinfo endpoint, and then add it to requests, as shown in

.

Cloud-hosted add-ins use either OAuth or the cross-domain library to authorize access to SharePoint

data. Add-in components with code that runs on a remote web server must use OAuth to authorize

access to SharePoint data. In this case, you need to include an Authorization header to send the

access token. See for an example that adds

an authorization header to an HTTPWebRequest object.

To learn more about OAuth access tokens and how to get them, see

and .

Requests are sent to the resource endpoint that's specified in the url property of the request.

Endpoint URIs use the following format:

/_api// (example,

Cross-domain library requests use this format when they access data on the add-in web, which is the

default context for cross-domain library requests. But to access data on the host web or on another

site collection, the requests need to initialize the host web or other site collection as the context. To

do this, they use the SP.AppContextSite endpoint in the URI, as shown in Table 1. The example

URIs in Table 1 use the @target alias to send the target URL in the query string because the URL

contains a special character (':').

In cloud-hosted add-ins that use OAuth, first retrieve the form digest value by sending a request

to the

Writing data by using the REST interf

ace

In cloud-hosted add-ins that use the JavaScript cross-domain library, you don't need to specify

the form digest value. By default, SP.RequestExecutor automatically handles this for you. (It also

handles the content-length value.)

Add-ins that use OAuth must pass access tokens in requests

Reading data with the SharePoint 2013 REST interface

Note

Cloud-hosted add-in components that are written in JavaScript must use

the SP.RequestExecutor object in the cross-domain library to access to SharePoint data. Cross-

domain library requests don't need to include an access token.

Context Token OAuth flow for S

harePoint Add-insAuthorization Code OAuth flow for SharePoint Add-ins

Endpoint URIs in cross-domain requests use SP.AppContextSite to change

the context

https://contoso.com/_api/web/lists)

Table 1. Using the SP.AppContextSite endpoint to change the context of the request

SharePoint Add-ins can get the add-in web URL and host web URL from the query string of the add-

in page, as shown in the following code example. The example also shows how to reference the

cross-domain library, which is defined in the SP.RequestExecutor.js file on the host web. The

example assumes that your add-in launches from SharePoint. See

for guidance on setting your SharePoint context correctly when your add-in does

not launch from SharePoint.

Note

An add-in web instance is required for a cloud-hosted add-in to access SharePoint data when using

the cross-domain library.

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

<app web

url>/_api/SP.AppContextSite(@t

arget)/web/lists?@target='<host

web url>'

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)

<app web

url>/_api/SP.AppContextSite(@t

arget)/web/title?

@target=''

SharePoint-hosted

Add-in web component

accessing data in another site

collection (tenant-scoped add-

ins only)

<app web

url>/_api/SP.AppContextSite(@t

arget)/web/title?

@target=''

Note

Cross-domain data access scenarios also require appropriate add-in permissions. For more

information, see and .Access data from the host webAccess data across site collections

Authorization Code OAuth flow for

SharePoint Add-ins

JavaScript

var hostweburl;1

var appweburl;2

3

// Get the URLs for the add-in web the host web URL from the query string.4

$(document).ready(function () {5

//Get the URI decoded URLs.6

hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));7

appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));8

9

// Load the SP.RequestExecutor.js file.10

$.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",

runCrossDomainRequest);

11

});12

13

// Build and send the HTTP request.14

function runCrossDomainRequest() {15

var executor = new SP.RequestExecutor(appweburl); 16

executor.executeAsync({17

url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" +

hostweburl + "'",

18

method: "GET", 19

headers: { "Accept": "application/json; odata=verbose" }, 20

success: successHandler, 21

error: errorHandler 22

});23

}24

25

// Get a query string value.26

// For production add-ins, you may want to use a library to handle the query string.27

function getQueryStringParameter(paramToRetrieve) {28

var params = document.URL.split("?")[1].split("&");29

var strParams = "";30

for (var i = 0; i < params.length; i = i + 1) {31

var singleParam = params[i].split("=");32

if (singleParam[0] == paramToRetrieve) return singleParam[1];33

}34

}35

… // success and error callback functions36

37

Table 2 shows properties that are commonly used in HTTP requests for the SharePoint REST

service.

Table 2. When to use REST request properties in HTTP requests

Properties used in REST requests

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 represent

s 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 en

dpoint. SharePoint-hosted add-

ins can get the value from

the #__REQUESTDIGEST pag

e control if it's available on the

SharePoint page. See

.

Writing d

ata 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":"applic

ation/json;odata=verbos

e"

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.len

gth

IF-MATCH header

POST requests

for DELETE, MERGE,

or PUToperations, 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 PUToperations

Used to specify that the request

performs an update or delete

operation. Example: "X-HTTP-

Method":"PUT"

binaryStringRequestBody

SP.RequestExecutor POSTrequ

ests that send binary data in the

body

Specifies whether the request

body is a binary

string. Boolean.

binaryStringResponseBodySP.RequestExecutor requests

that return binary data

Specifies whether the response

is a binary str