Creating, Updating, and Deleting
The REST endpoints also accept requests to create, update, and delete data using POST, PUT, and PATCH commands.
- POST is used for creating data
- PUT is used for updating (all property values specified)
- PATCH is used for updating (specified properties only)
When using any of the preceding commands from JS
running on a SharePoint page, you also must include the form digest
from the page in the appropriate HTTP header:
X-RequestDigest: formDigest
You can get the formDigest from the object returned from a POST call to /_api/contextinfo, or if you are building a SharePoint-hosted app then you can simply get the value of the formDigest with this JQuery function:
$('#__REQUESTDIGEST').val()
You are then ready to send your create, update,
or delete command to SharePoint. To practice doing so, take a look at
the following activity.
TRY IT OUT: Creating a New List in the Host Web
In this example you use a
SharePoint-hosted app using the Napa Office 365 Development Tools and
use the REST/OData API to create a new list in the host Web. You must
have the Napa application installed from the Office 365 marketplace
prior to starting this exercise. The full JavaScript source for this
exercise is available in the code download in the MyODataJavaScriptApp.js file.
1. Ensure you have Napa Office 365 Development Tools installed in your development site in Office 365.
2. Click Site Contents in your site navigation to see a list of all apps installed in your site.
3. Locate “Napa” Office 365 Development Tools in the list and click it, as shown in Figure 2.
4. Click Add New Project in the screen that appears.
5. Select App for SharePoint and enter MyODataJavaScriptApp
in the Project name box. Click Create to continue. Napa creates a set
of template files and folders for you. Explore the structure and get
familiar with the layout of the application.
6. In the lower left of the window click the wrench icon to open the Property panel for your application as shown in Figure 3.
7. Click the Permissions tab and set the permissions for Web under Content to Full Control.
8. Open the Scripts folder and then open the App.js file. This default file contains the JavaScript for your application.
9. Add the
following code to the bottom of the file. This helps you get the
various parameters that were passed to the page from the
querystring:
function getParams() {
var params = {};
location.search.split('?')[1].split('&').forEach(function (param) {
var key = param.split('=')[0],
val = decodeURIComponent(param.split('=')[1]);
params[key] = val;
});
return params;
}
10. Replace the
sharePointReady() function with the following. This code loads the
SP.RequestExecutor.js
JavaScript file that helps with cross-domain calls. The app needs this
to call into the host Web because it’s on a different domain name:
var params;
var scriptbase;
function sharePointReady() {
context = new SP.ClientContext.get_current();
params = getParams();
scriptbase = params.SPHostUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
}
11. Add the following new function. This uses a
POST command to post a JSON payload with the new list information to the host web’s REST API:
function execCrossDomainRequest()
{
var executor;
executor = new SP.RequestExecutor(params.SPAppWebUrl);
var data = JSON.stringify({ '__metadata': { 'type': 'SP.List' },
'AllowContentTypes': true, 'BaseTemplate': 100,
'ContentTypesEnabled': true, 'Description': 'My list description',
'Title': 'My New List' });
var requestUri = params.SPAppWebUrl +
"/_api/SP.AppContextSite(@target)/web/lists?@target='" + params.SPHostUrl + "'";
executor.executeAsync(
{
url: requestUri,
method: "POST",
body: data,
headers: {
"accept": "application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"content-length": data.length,
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
success: successHandler,
error: errorHandler
}
);
}
function successHandler(data) {
alert('success');
}
function errorHandler(data, errorCode, errorMessage) {
alert("Failed :( Error:" + errorMessage);
}
12. Click the
Run Project button in the bottom left of the window to test out the
application. When it completes a message appears like the one shown in Figure 4.
13.
Right-click the launch link and open your app in a new window to start
your application. When you are prompted to trust your app, click Trust
It to continue.
14. A JavaScript alert message appears, stating “Success.” The app has created the list in the host Web.
15. Navigate to the host website by clicking the title of your site in the navigation.
16. Click Site
Content to see a list of the apps/lists in your site. You can see the
new list called My New List that your app created, as shown in Figure 5.
How It Works
In this exercise you created a
SharePoint-hosted app that created a new list in the host or parent
Web. To do this it used the REST/OData API and a POST
command to post the creation information as a JSON payload in the
request. Because the request was from one domain to another, you used
the SP.RequestExecutor framework
to proxy the call via the app Web to the host Web. This step was
necessary due to the cross-domain security boundary browsers put on
JavaScript.
The JSON payload consisted of a JSON representation of an SP.List object, along with the properties needed for creation such as the BaseTemplate ID and the Title.
By making a POST request along with this JSON to the /_api/SP.AppContextSite(@target)/web/lists URI, SharePoint proxies the request to the host Web for you along with the JSON. Because the request is a POST SharePoint knows you want to create something. SharePoint knows you want to create a list because the URI specifies the /web/list REST endpoint. SharePoint looks in the body of the request for the details on the list you want to create and creates it.
WATCH THE JAVASCRIPT CSOM AT WORK WITH FIDDLER
If you are interested in seeing
the underlying API calls to SharePoint from the JavaScript CSOM you can
do so with a tool called Fiddler. You can download Fiddler from: http://www.fiddler2.com. Using Fiddler you can see all the HTTP traffic between your computer and another such as Sharepoint.com, where Office 365 is hosted. When watching Fiddler look for requests to URLs with paths that end in: /_vti_bin/client.svc/ProcessQuery. You will see XML payloads being sent to SharePoint along with JSON responses.