M365関連 プログラム 技術

SharePointRestAPIを使ってみる

SharePointに対して、これまでCSOMやPowerShellのPnPコマンド等を使っていましたがRestAPIは使ったことがなかったので今回はそれを実際に触ってみます。対象はSharePointOnlineとします
また、今回はアクセストークンを使わないやり方で実装しています

おおもとになるコード

この実装方法だとアクセストークンの設定やGraphAPIの追加といった作業することなく実施できます

SharePointOnlineCredentials credential = new SharePointOnlineCredentials(user, passWord);
using (var handler = new HttpClientHandler() { Credentials = credential })
{
    Uri uri = new Uri(webUrl);
    handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

    using (var client = new HttpClient(handler))
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync(string.Format(restURL, webUrl, listName)).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();

        jsonData = await response.Content.ReadAsStringAsync();
    }
}

サイト情報の取得

・サイト内のリスト一覧

string restURL = "{0}_api/web/lists";

・サイト内のリストのアイテム数の一覧

string restURL = "{0}_api/web/lists?$select=Title,ItemCount";

リスト情報の取得

・上位20件を取得

string restURL = "{0}_api/web/lists/GetByTitle('{1}')/items?$top=20";

・上位20件を取得し、プロパティはタイトルのみ取得

string restURL = "{0}/_api/web/lists/GetByTitle('{1}')/items?$top=20&$select=Title";

最後に

以下のサイトではオンプレ・オンライン含めて使えるSharePointRestAPIがまとめられているので、参考になると思います

参考サイト
SharePoint REST サンプル集 - SharePoint Developer
SharePoint REST サンプル集 - SharePoint Developer

SharePoint Online や、オンプレ SharePoint で使える、SharePoint REST のサン ...

続きを読む

-M365関連, プログラム, 技術
-, ,