This article shows how to add a new user to a group in SharePoint using REST. Develop the project using the following method in the NAPA Tool.
On your Developer Site, open the "Napa" Office 365 Development Tools and then choose Add New Project.
- Choose the App for SharePoint template, name the project Create Site and then choose the Create button
- Replace APP.js with the following source code.
- Publish Your App.
Prerequisites
The following is the important procedure to be done before creating the app. Specify the permissions that your app needs as in the following. Choose the Properties button at the bottom of the page.
- In the Properties window, choose Permissions.
- In the Content category, set the Write permissions for the Tenant scope.
- In the Social category, set the Read permissions for the User Profiles scope.
- Close the Properties window.
Endpoint URI
- url: "<app web url>/_api/SP.AppContextSite(@target)/web
- /sitegroups(7)/users
- ?@target='<host web url>'",
- method: "POST",
- body: "{ '__metadata': { 'type': 'SP.User' }, 'LoginName':'i:0#.w|domain\\user' }",
Source Code
- 'use strict';
-
- var hostweburl;
- var appweburl;
-
-
-
- $(document).ready(function () {
-
-
- hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
- appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
-
-
-
-
-
-
-
- $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",newuser);
- });
-
-
- function newuser () {
- var executor;
- var userEmail="[email protected]";
-
- executor = new SP.RequestExecutor(appweburl);
-
- executor.executeAsync({
-
- url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users?@target='"+ hostweburl + "'",
- method: "POST",
- body:"{ '__metadata': { 'type': 'SP.User' }, 'LoginName': 'i:0#.f|membership|"+userEmail+"' }",
- headers: {
- "Accept": "application/json; odata=verbose",
- "content-type": "application/json; odata=verbose"
- },
-
- success: function(data)
- {
- alert("New User added successfully in SharePoint Group");
- },
- error: function(err)
- {
- alert("error: " + JSON.stringify(err));
- } });
- }
-
-
-
- function getQueryStringParameter(paramToRetrieve) {
- var params = document.URL.split("?")[1].split("&");
- for (var i = 0; i < params.length; i = i + 1) {
- var singleParam = params[i].split("=");
- if (singleParam[0] == paramToRetrieve) return singleParam[1];
- }
- }
Publish: Publish the app and click the Trust it Button.
Output: New User added in to the Group Successfully.