Using SharePoint 2013 Get Current user Group Collection through Rest API

Introduction

In this blog, let’s explore the easy way to get current user group collection through REST API in JQuery.

Initially we have to obtain the current user of SharePoint group they belong to, which can be achieved using SharePoint 2013 REST API.

Let's proceed

When we use /_api/web/CurrentUser and /_api/web/GetUserById("+UserID+")/ Groups , we get the current user’s group collection . Right now I am using a work around that iterates through the (big) result set. To get the group for the current Login User follow below steps.

Step 1: Navigate to your SharePoint 2013 site.

Step 2: From this page select the Site Actions | Edit Page.

Edit the page, go to the "Insert" tab in the Ribbon and click the "Web Part" option. In the "Web Parts" dialogue, go to the "Media and Content" category, select the "Script Editor" Web Part and click the "Add button".

Step 3: Once the Web Part is inserted into the page, you will see an "EDIT SNIPPET" link; click it. You can insert the HTML and/or JavaScript as in the following.

  1. <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>  
  2. <script type="text/javascript">  
  3. $(document).ready(function ()  
  4. { getCurrentUser(); });  
  5. function getCurrentUser()   
  6. {  
  7. getUserWebPermissionREST();  
  8. $.ajax({  
  9. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/CurrentUser",  
  10. method: "GET",  
  11. headers: { "Accept""application/json; odata=verbose" },  
  12. success: function (data)  
  13. {  
  14. getCurrentUserGroupColl(data.d.Id);  
  15. },  
  16. error: function (data)   
  17. {  
  18. failure(data);  
  19. }  
  20. });  
  21. }  
  22. function getCurrentUserGroupColl(UserID)   
  23. {  
  24. $.ajax  
  25. ({  
  26. url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetUserById(" + UserID + ")/Groups",  
  27. method: "GET",  
  28. headers: { "Accept""application/json; odata=verbose" },  
  29. success: function (data) {  
  30. /* get all group's title of current user. */  
  31. var results = data.d.results; var InnrHtmlgrp = "  
  32.     <ul>";  
  33. for (var i = 0; i < results.length; i++)   
  34. {  
  35. InnrHtmlgrp += "  
  36.         <li>" + results[i].Title + "</li>";  
  37. }  
  38. $("#Group").append(InnrHtmlgrp + "  
  39.     </ul>");  
  40. }  
  41. });  
  42. }  
  43. </script>  
  44. <strong>security Group Name:</strong>  
  45. <div id="Group"></div>  
Final Output Result