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.

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.


Endpoint URI
  1. url: "<app web url>/_api/SP.AppContextSite(@target)/web
  2. /sitegroups(7)/users
  3. ?@target='<host web url>'",
  4. method: "POST",
  5. body: "{ '__metadata': { 'type': 'SP.User' }, 'LoginName':'i:0#.w|domain\\user' }",
Source Code
  1. 'use strict';
  2. var hostweburl;
  3. var appweburl;
  4. // Get the URLs for the app web the host web URL from the query string.
  5. $(document).ready(function () {
  6. //Get the URI decoded URLs.
  7. hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  8. appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
  9. // Resources are in URLs in the form:
  10. // web_url/_layouts/15/resource
  11. // Load the js file and continue to load the page with information about the folders.
  12. // SP.RequestExecutor.js to make cross-domain requests
  13. $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js",newuser);
  14. });
  15. function newuser () {
  16. var executor;
  17. var userEmail="[email protected]";
  18. // Initialize the RequestExecutor with the app web URL.
  19. executor = new SP.RequestExecutor(appweburl);
  20. executor.executeAsync({
  21. url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(6)/users?@target='"+ hostweburl + "'",
  22. method: "POST",
  23. body:"{ '__metadata': { 'type': 'SP.User' }, 'LoginName': 'i:0#.f|membership|"+userEmail+"' }",
  24. headers: {
  25. "Accept": "application/json; odata=verbose",
  26. "content-type": "application/json; odata=verbose"
  27. },
  28. success: function(data)
  29. {
  30. alert("New User added successfully in SharePoint Group");
  31. },
  32. error: function(err)
  33. {
  34. alert("error: " + JSON.stringify(err));
  35. } });
  36. }
  37. //Utilities
  38. // Retrieve a query string value.
  39. // For production purposes you may want to use a library to handle the query string.
  40. function getQueryStringParameter(paramToRetrieve) {
  41. var params = document.URL.split("?")[1].split("&");
  42. for (var i = 0; i < params.length; i = i + 1) {
  43. var singleParam = params[i].split("=");
  44. if (singleParam[0] == paramToRetrieve) return singleParam[1];
  45. }
  46. }
Publish: Publish the app and click the Trust it Button.



Output: New User added in to the Group Successfully.