1 out of 4 rated this helpful - Rate this topic

How to: Complete basic operations using SharePoint 2013 REST endpoints

apps for Office

Published: July 16, 2012

Conceptual overview topic

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

Applies to:  apps for SharePoint | Office 365 | 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 Programming using the SharePoint 2013 REST service for a thorough introduction to the SharePoint 2013 REST interface and its architecture.

See SharePoint 2013: Perform basic data access operations by using REST in apps 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 Choose the right API set in SharePoint 2013. For information about how to use the other client APIs see, How to: Complete basic operations using JavaScript library code in SharePoint 2013, How to: Complete basic operations using JavaScript library code in SharePoint 2013, and Build mobile apps for SharePoint 2013.

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://site url/_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.

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 app web, as you would in a SharePoint-hosted app. 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. OAuth authentication and authorization flow for cloud-hosted apps in SharePoint 2013 and OAuth authentication and authorization flow for apps that ask for access permissions on the fly in SharePoint 2013 (advanced topic) explain how you can obtain an access token.


HttpWebRequest endpointRequest =
  (HttpWebRequest)HttpWebRequest.Create(
  "http:// <site url>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", 
  "Bearer " + accessToken);
HttpWebResponse endpointResponse =
  (HttpWebResponse)endpointRequest.GetResponse();

This request would look a little different if you are writing your app 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. See How to: Access SharePoint 2013 data from remote apps using the cross-domain library for more information about using the cross-domain library.

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
                    }
                );

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.

HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();

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 these operations also require you to pass 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://site url/_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#. It assumes that you have an OAuth access token that you are storing in the accessToken variable.


HttpWebRequest endpointRequest =
  (HttpWebRequest)HttpWebRequest.Create(
  "http:// <site url>/_api/contextinfo");
endpointRequest.Method = "POST";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", 
  "Bearer " + accessToken);
HttpWebResponse endpointResponse =
  (HttpWebResponse)endpointRequest.GetResponse();

If you’re creating a SharePoint-hosted app for SharePoint, 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, as shown in the following example, which uses JQuery and creates a list.

jQuery.ajax({
        url: “http://site url/_api/web/lists”,
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,
 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "content-length":length of post body
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: doSuccess,
        error: doError
});


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

jQuery.ajax({
        url: http:// site url/_api/web/lists/GetByTitle(‘Test'),
        type: "POST",
        data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }
),
        headers: { 
            “X-HTTP-Method”:”MERGE”,
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "content-length":length of post body
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            “IF-MATCH”: “*”
        },
        success: doSuccess,
        error: doError
});

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 <entry> tag for the XML node that contains the list information. The m:etag property contains the etag value.

<entry xml:base="http:// site url/_api/" xmlns=http://www.w3.org/2005/Atom 
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
 xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:etag=""1"">

The following sections provide examples of HTTP requests that you’ll have to make to read, write, update, and delete SharePoint entities.

The following example shows how to create a site.

url: http://site url/_api/web/webinfos/add
method: POST
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-type: "application/json;odata=verbose"
    content-length:length of post body
body: { 'd' :{
  'parameters': { 
    '__metadata':  {'type': 'SP.WebInfoCreationInformation' }, 
    'Url': 'RestSubWeb', 
    'Title': 'RestSubWeb', 
    'Description': 'rest-created web',
    'Language':1033,
    'WebTemplate':'sts',
    'UseUniquePermissions':false}
  }}

The following example shows how to retrieve a specific list if you know its GUID.

url: http://site url/_api/web/lists/(guid'list GUID'),
method: GET
Headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

Note Note

Use application/json:odata=verbose in the accept header if you want the response in JSON. Use application/atom+xml in the accept header if you want the response in Atom format.

The following example shows how to retrieve a specific list if you know its title.

url: http://site url/_api/web/lists/GetByTitle(‘Test')
method: GET
Headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following XML shows an example of the list properties that are returned when you request the XML content type.

  <content type="application/xml">
  <m:properties>
  <d:AllowContentTypes m:type="Edm.Boolean">true</d:AllowContentTypes> 
  <d:BaseTemplate m:type="Edm.Int32">100</d:BaseTemplate> 
  <d:BaseType m:type="Edm.Int32">0</d:BaseType> 
  <d:ContentTypesEnabled m:type="Edm.Boolean">false</d:ContentTypesEnabled> 
  <d:Created m:type="Edm.DateTime">2012-06-26T23:15:58Z</d:Created> 
  <d:DefaultContentApprovalWorkflowId m:type="Edm.Guid">00000000-0000-0000-0000-000000000000</d:DefaultContentApprovalWorkflowId> 
  <d:Description>A list created by Project Based Retention used to store Project Policy Items.</d:Description> 
  <d:Direction>none</d:Direction> 
  <d:DocumentTemplateUrl m:null="true" /> 
  <d:DraftVersionVisibility m:type="Edm.Int32">0</d:DraftVersionVisibility> 
  <d:EnableAttachments m:type="Edm.Boolean">true</d:EnableAttachments> 
  <d:EnableFolderCreation m:type="Edm.Boolean">false</d:EnableFolderCreation> 
  <d:EnableMinorVersions m:type="Edm.Boolean">false</d:EnableMinorVersions> 
  <d:EnableModeration m:type="Edm.Boolean">false</d:EnableModeration> 
  <d:EnableVersioning m:type="Edm.Boolean">false</d:EnableVersioning> 
  <d:EntityTypeName>ProjectPolicyItemList</d:EntityTypeName> 
  <d:ForceCheckout m:type="Edm.Boolean">false</d:ForceCheckout> 
  <d:HasExternalDataSource m:type="Edm.Boolean">false</d:HasExternalDataSource> 
  <d:Hidden m:type="Edm.Boolean">true</d:Hidden> 
  <d:Id m:type="Edm.Guid">74de3ff3-029c-42f9-bd2a-1e9463def69d</d:Id> 
  <d:ImageUrl>/_layouts/15/images/itgen.gif</d:ImageUrl> 
  <d:IrmEnabled m:type="Edm.Boolean">false</d:IrmEnabled> 
  <d:IrmExpire m:type="Edm.Boolean">false</d:IrmExpire> 
  <d:IrmReject m:type="Edm.Boolean">false</d:IrmReject> 
  <d:IsApplicationList m:type="Edm.Boolean">false</d:IsApplicationList> 
  <d:IsCatalog m:type="Edm.Boolean">false</d:IsCatalog> 
  <d:IsPrivate m:type="Edm.Boolean">false</d:IsPrivate> 
  <d:ItemCount m:type="Edm.Int32">0</d:ItemCount> 
  <d:LastItemDeletedDate m:type="Edm.DateTime">2012-06-26T23:15:58Z</d:LastItemDeletedDate> 
  <d:LastItemModifiedDate m:type="Edm.DateTime">2012-06-26T23:15:59Z</d:LastItemModifiedDate> 
  <d:ListItemEntityTypeFullName>SP.Data.ProjectPolicyItemListItem</d:ListItemEntityTypeFullName> 
  <d:MultipleDataList m:type="Edm.Boolean">false</d:MultipleDataList> 
  <d:NoCrawl m:type="Edm.Boolean">true</d:NoCrawl> 
  <d:ParentWebUrl>/</d:ParentWebUrl> 
  <d:ServerTemplateCanCreateFolders m:type="Edm.Boolean">true</d:ServerTemplateCanCreateFolders> 
  <d:TemplateFeatureId m:type="Edm.Guid">00bfea71-de22-43b2-a848-c05709900100</d:TemplateFeatureId> 
  <d:Title>Project Policy Item List</d:Title> 
  </m:properties>
  </content>
Note Note

The ListItemEntityTypeFullName property (SP.Data.ProjectPolicyItemListItem in the previous example) is especially important if you want to create and update list items. This value must be passed as the type property in the metadata that you pass in the body of the HTTP request whenever you create and update list items.

The following example shows how to create a list.

url: http://site url/_api/web/lists
method: POST
body: { '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100,
 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to update a list by using the MERGE method.

url: http://site url/_api/web/lists/(guid'list GUID')
method: POST
body: { '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    IF-MATCH”: etag or “*”
    X-HTTP-Method: MERGE,
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to create a custom field for a list.

Url: url: http://site url/_api/web/lists/(guid'list GUID')/Fields
Method:POST
Body: { '__metadata': { 'type': 'SP.Field' }, 'Title': 'field title', 'FieldTypeKind': FieldType value,'Required': 'true/false', 'EnforceUniqueValues': 'true/false','StaticName': 'field name'}
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to delete a list.

url: http://site url/_api/web/lists/(guid'list GUID')
method: POST
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    IF-MATCH: etag or “*”
    X-HTTP-Method: DELETE

The following example shows how to retrieve all of a list’s items.

url: http://site url/_api/web/lists/GetByTitle(‘Test')/items
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following example shows how to retrieve a specific list item.

url: http://site url/_api/web/lists/GetByTitle(‘Test')/items(item id)
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following XML shows an example of the list item properties that are returned when you request the XML content type.

<content type="application/xml">
<m:properties>
<d:FileSystemObjectType m:type="Edm.Int32">0</d:FileSystemObjectType>
<d:Id m:type="Edm.Int32">1</d:Id>
<d:ID m:type="Edm.Int32">1</d:ID>
<d:ContentTypeId>0x010049564F321A0F0543BA8C6303316C8C0F</d:ContentTypeId>
<d:Title>an item</d:Title>
<d:Modified m:type="Edm.DateTime">2012-07-24T22:47:26Z</d:Modified>
<d:Created m:type="Edm.DateTime">2012-07-24T22:47:26Z</d:Created>
<d:AuthorId m:type="Edm.Int32">11</d:AuthorId>
<d:EditorId m:type="Edm.Int32">11</d:EditorId>
<d:OData__UIVersionString>1.0</d:OData__UIVersionString>
<d:Attachments m:type="Edm.Boolean">false</d:Attachments>
<d:GUID m:type="Edm.Guid">eb6850c5-9a30-4636-b282-234eda8b1057</d:GUID>
</m:properties>
</content>

The following example shows how to create a list item.

Note Note

To do this operation, you must know the ListItemEntityTypeFullName property of the list and pass that as the value of type in the HTTP request body.

url: http://site url/_api/web/lists/GetByTitle(‘Test')/items
method: POST
body: { '__metadata': { 'type': 'SP.Data.TestListItem' }, 'Title': 'Test'}
headers:
    Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to update a list item.

Note Note

To do this operation, you must know the ListItemEntityTypeFullName property of the list and pass that as the value of type in the HTTP request body.

url: http://site url/_api/web/lists/GetByTitle(‘Test')/items(item id)
method: POST
body: { '__metadata': { 'type': 'SP.Data.TestListItem' }, 'Title': 'TestUpdated'}
headers:
    Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    “IF-MATCH”: etag or “*”
    “X-HTTP-Method”:”MERGE”,
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to delete a list item.

url: http://site url/_api/web/lists/GetByTitle(‘Test')/items(item id)
method: POST
headers:
    Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    “IF-MATCH”: etag or “*”
    “X-HTTP-Method”:”DELETE”

Since a document library is a type of list (with a BaseType property of 1), you can retrieve a folder inside a document library by constructing an endpoint that points to a folder inside a list. The following example shows how to retrieve a folder inside a list that you know is a document library.

url: http://site url/_api/web/lists(guid’list GUID’)/RootFolder
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

You can also retrieve a folder inside a document library when you know its URL. For example, you can retrieve the root folder of your Shared Documents library by using the endpoint in the following example.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Shared Documents')
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following XML shows an example of folder properties that are returned when you request the XML content type.

<content type="application/xml">
<m:properties>
<d:ItemCount m:type="Edm.Int32">0</d:ItemCount>
<d:Name>Shared Documents</d:Name>
<d:ServerRelativeUrl>/Shared Documents</d:ServerRelativeUrl>
<d:WelcomePage/>
</m:properties>
</content>

The following example shows how to create a folder.

url: http://site url/_api/web/folders
method: POST
body: { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/document library relative url/folder name’}
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to update a folder by using the MERGE method.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')
method: POST
body: { '__metadata': { 'type': 'SP.Folder' }, 'Name': 'New name' }
Headers: 
     Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    “IF-MATCH”: etag or “*”
    “X-HTTP-Method”:”MERGE”,
    accept: "application/json;odata=verbose"
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following example shows how to delete a folder.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')
method: POST
Headers: 
     Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    “IF-MATCH”: etag or “*”
    “X-HTTP-Method”:”DELETE”

The following example shows how to retrieve all of the files in a folder.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following example shows how to retrieve a specific file.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files(‘file name’)/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken

You can also retrieve a file when you know its URL, as in the following example.

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name’)/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken

The following example shows how to create a file and add it to a folder.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url=’a.txt’,overwrite=true)
method: POST
body: “Contents of file”
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-length:length of post body

The following example shows how to update a file by using the PUT method.

Note Note

PUT is the only method that you can use to update a file. The MERGE method is not allowed.

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name’)/$value
method: POST
body: “Contents of file.”
Headers: 
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    X-HTTP-Method:”PUT”
    content-length:length of post body

You may want to check out a file in order to make sure that no one changes it before you update it. After your update, you should also may want to check the file back in so that others can work with it. The following example shows you how to check a file out.

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name’)/CheckOut()’
method: POST
headers:
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value

The following example shows you how to check a file in.

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name/CheckIn(comment='Comment', checkintype=0)
method: POST
headers:
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value

The following example shows how to delete a file.

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name’)
method: POST
headers:
    Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
    IF-MATCH: etag or “*”
    X-HTTP-Method:”DELETE”

When you need to upload a binary file that is larger than 1.5 megabytes (MB), the REST interface is your only option. See How to: Complete basic operations using JavaScript library code in SharePoint 2013 for a code example that shows you how to upload a binary file that is smaller than 1.5 MB by using the SharePoint 2013 Javascript object model. The maximum size of a binary file that you can create with REST is 2 gigabytes (GB). The following example shows how to create a large binary file.

Caution note Caution

This approach will work only with Internet Explorer 10 and the latest versions of other browsers.

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/Add(url='file name', overwrite=true)
method: POST
body: contents of binary file
headers:
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value
    content-type: "application/json;odata=verbose"
    content-length:length of post body

The following code sample shows how to create a file by using this REST endpoint and the cross-domain library.

function uploadFileBinary() {
XDomainTestHelper.clearLog();
var ro;
if (document.getElementById("TxtViaUrl").value.length > 0) {
ro = new SP.RequestExecutor(document.getElementById("TxtWebUrl").value, document.getElementById("TxtViaUrl").value);
}
else {
ro = new SP.RequestExecutor(document.getElementById("TxtWebUrl").value);
}
var body = "";
for (var i = 0; i < 1000; i++) {
var ch = i % 256;
body = body + String.fromCharCode(ch);
}
var info = {
url: "_api/web/lists/getByTitle('Shared Documents')/RootFolder/Files/Add(url='a.dat', overwrite=true)",
method: "POST",
binaryStringRequestBody: true,
body: body,
success: success,
error: fail,
state: "Update"
};
ro.executeAsync(info);
}

The following example shows how to retrieve all of the files that are attached to a list item.

url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles/
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following example shows how to retrieve a file that is attached to a list item.

url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles('file name')/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or “application/atom+xml”

The following example shows how to create a file attachment to a list item.

url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles/ add(FileName='file name')
method: POST
headers:
    Authorization: "Bearer " + accessToken
    body: “Contents of file.”
    X-RequestDigest: form digest value
    content-length:length of post body

The following example shows how to update a file attachment to a list item by using the PUT method.

Note Note

PUT is the only method that you can use to update a file. The MERGE method is not allowed.

url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles('file name')/$value
method: POST
body: “Contents of file.”
headers:
    Authorization: "Bearer " + accessToken
    “X-HTTP-Method”:”PUT”
    X-RequestDigest: form digest value
    content-length:length of post body
Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.