SharePoint REST サービスを使用したアイテムの CRUD 方法

こんにちは SharePoint サポートの森 健吾 (kenmori) です。

 

今回の投稿では、SharePoint Online または SharePoint 2013 サイト上のページから REST API を使用し、リストアイテムを CRUD (Create, Read, Update, Delete) 操作する方法についてサンプルを記載します。

 

今回紹介する方法は、SharePoint の REST サービスを理解する上で非常に重要であり、SharePoint アプリなどを作っていく前に一度経験しておいた方が良い内容です。ただし、今回ご案内するサンプルは、実際に使用するシナリオが限定されます。

 

SharePoint のクライアント サイド API は、下記のような用途で使用されます。

 

CSOM

 .NET ベースのクライアント サイド アプリケーションおよびプロバイダー ホスト型アプリ

JSOM

 SharePoint サイト上のページから同じサイトのサイト コンテンツへのアクセス

REST (JavaScript)
 SharePoint ホスト アプリのアプリ サイトからホスト サイトへのアクセス (ただし RequestExecutor を使用)

REST (コード)

 .NET 以外のクライアント サイド アプリケーション およびプロバイダー ホスト型アプリ

  今回のような REST (JavaScript) の自サイトに対してアクセスするサンプルを使用する機会は非常に少ないと思います。このシナリオでは JSOM が多くの場合使用されますが、もちろん代わりに REST を使用することはできます。MSDN などの公開情報も実運用シナリオで使用するシナリオを公開しているためサンプルが少ないようですが、ここに備忘録として記載しておきます。
特に .NET 以外の開発環境で使用する際などにお役立ていただけますと幸いです。

 

2014/11/15 更新 JSOM を使用したサンプルも公開しました。下記と比較しながらご参考にしてください。

 

タイトル : SharePoint JSOM を使用したアイテムの CRUD 方法
アドレス : https://blogs.technet.com/b/sharepoint_support/archive/2014/11/15/sharepoint-jsom-crud.aspx

 

 

事前準備

1. SharePoint のサイトのページ ライブラリ内にページを作成します。

2. スクリプト エディタ Web パーツを貼り付けます。

 

 

3. [Web パーツの編集]をクリックし、[スニペットの編集] をクリックします。

4. 表示されるテキスト内に下記のスクリプトを貼り付けます。

 

 <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script langauge="JavaScript">
<!--
 
var weburl = "https://tenant.sharepoint.com";
var listTitle = "customlist01"

$(document).ready(function () {
    GetListItems();
});

function GetListItems() {
$.ajax({
     url: weburl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items",
     type: "GET",
     headers: {
          "accept": "application/json;odata=verbose",
          "Content-Type": "application/json;odata=verbose",
          "x-requestforceauthentication": true
     },
     success: this.renderData,
     error: function (xhr) { alert(xhr.status + ": " + xhr.statusText) }
});
}


function QueryListItems() {
 var title = $("#title").val();
 if (title == "")
 {
   GetListItems();
   return;
 }

 $.ajax({
     url: weburl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items?$filter=Title%20eq%20'" + encodeURIComponent(title) + "'",
     type: "GET",
     headers: {
          "accept": "application/json;odata=verbose",
          "Content-Type": "application/json;odata=verbose",
          "x-requestforceauthentication": true
     },
     success: this.renderData,
     error: function (xhr) { alert(xhr.status + ": " + xhr.statusText) }
 });
}

function renderData(data)
{
    var strres = "";
    for (i = 0; i < data.d.results.length ; i++)
    {
        strres += "<tr onclick=\"setItemDate(" + data.d.results[i].Id + ", '" + data.d.results[i].Title + "')\">";
        strres += "<td>";
        strres += data.d.results[i].Id;
        strres += "</td><td>";
        strres += data.d.results[i].Title;
        strres += "</td></tr>";
    }
    if (strres == "")
    {
        strres += "<tr><td>(Empty)</td></tr>";
    }
    strres = "<b>" + "Items on " + listTitle + "</b>"
     + "<br><br><table><tr><th>ID</th><th>Title</th></tr>"
     + strres + "</table>";
    $("#P1").html(strres);
}

var myDigest = null;
function runWithFormDigest(fn){
  if (myDigest == null)
  {
    $.ajax({
        url: weburl + "/_api/contextinfo",
        type: "POST",
        contentType: "application/x-www-url-encoded",
        dataType: "json",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        contentLength: 0,
        beforeSend: function (xhr) { xhr.withCredentials = true; },
        success: function (data) {
            if (data.d) {
                myDigest = data.d.GetContextWebInformation.FormDigestValue;
                fn();  
            }
        }
    });
  }
  else
  {
    fn();
  }
}

function AddListItem() {
var title = $("#title").val();
runWithFormDigest(function(){
   $.support.cors = true;
   $.ajax({
       url: weburl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items",
       type: "POST",
       data: JSON.stringify({ '__metadata': { 'type': 'SP.ListItem' }, 'Title': title }),
       headers: {
            "accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "x-requestforceauthentication": true,
            "X-RequestDigest": myDigest
       },
      success: function (xhr) { GetListItems() },
       error: function (xhr) { alert(xhr.status + ": " + xhr.statusText) }
   });
});
}

function UpdateListItem() {
var id = $("#itemid").val()
var title = $("#title").val();

runWithFormDigest(function(){
   $.support.cors = true;
   $.ajax({
       url: weburl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items(" + id + ")",
       type: "POST",
       data: JSON.stringify({ '__metadata': { 'type': 'SP.ListItem' }, 'Title': title }),
       headers: {
            "X-HTTP-Method":"MERGE",
            "accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "x-requestforceauthentication": true,
            "X-RequestDigest": myDigest,
            "IF-MATCH": "*"
       },
       success: function (xhr) { GetListItems() },
       error: function (xhr) { alert(xhr.status + ": " + xhr.statusText) }
   });
});
}

function DelListItem(){
var id = $("#itemid").val()

runWithFormDigest(function(){
   $.support.cors = true;
   $.ajax({
       url: weburl + "/_api/Web/Lists/GetByTitle('" + listTitle + "')/Items(" + id + ")",
       type: "POST",
       headers: {
            "X-HTTP-Method":"DELETE",
            "accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "x-requestforceauthentication": true,
            "X-RequestDigest": myDigest,
            "IF-MATCH": "*"
       },

       success: function (xhr) { GetListItems() },
       error: function (xhr) { alert(xhr.status + ": " + xhr.statusText) }
   });
});
}


function setItemDate(itemid, title)
{
  $("#title").val(title);
  $("#itemid").val(itemid);
}
-->

</script>
<div id="P1"></div>
<br>
<table><tr>
<td>itemid :</td><td><input type="text" id="itemid"></td>
</tr><tr>
<td>title : </td><td><input type="text" id="title"></td>
</tr>
</table>
<br>
<input type="button" onclick="QueryListItems()" value="Query">
<input type="button" onclick="AddListItem()" value="Add">
<input type="button" onclick="UpdateListItem()" value="Update">
<input type="button" onclick="DelListItem()" value="Delete">
 

 

5. サンプル内にて、緑字で記載した jQuery ライブラリの位置、サイトの URL、リストのタイトルなどを調整します。

 

6. ページの保存を実施します。

 

上記操作を実施することで、リストアイテムを表示、追加、更新、削除できる最小限のサンプル Web パーツが完成しました。

 

 

 

下記に本投稿に関連する参考情報を記載いたします。

 

タイトル : SharePoint 2013 REST サービスの概要

アドレス : https://msdn.microsoft.com/ja-jp/library/office/fp142380(v=office.15).aspx

 

2019.1.8 追記 : 以下に SharePoint Online のページ カスタマイズの注意点を紹介します。

タイトル : SharePoint Online ページ カスタマイズの注意点
アドレス : https://social.msdn.microsoft.com/Forums/ja-JP/dfcccf1a-f63f-418b-b817-fbe7f5399651/sharepoint-online-125061254012472?forum=sharepointsupportteamja

 

今回の投稿は以上になります。