'REST Call to Sharepoint Online to add user to a site group not working. Either user not unique or Value not in range
I got a REST API call to our SP Online Instance that is not working in any way:
Method: POST
Endpoint: https://xyz.sharepoint.com/sites/ATestSite/_api/web/sitegroups(5)/users
Header:
Accept application/json;odata.metadata=none
Content-type application/json
Content:
{'LoginName':'i:0#.f|membership|[email protected]'}
This results in a 400 error: Value does not fall within the expected range. I got the login name from the system when I looked up the siteuser through REST
if I change the content to {'LoginName':'[email protected]'}
I get a 404 error: The user does not exist or is not unique.
Anybody got any idea? Thanks in advance!
Solution 1:[1]
You can try following format
Post https://xyz.sharepoint.com/sites/ATestSite/_api/web/sitegroups(5)/users
{
'__metadata':
{ 'type': 'SP.User' },
'LoginName':'i:0#.f|membership|[email protected]'
}
Solution 2:[2]
Try using below code. I just tried this at my end and it is working for me:
<script type="text/javascript" src="/sites/siteName/SiteAssets/jquery.min.js"></script>
<button type="button" onclick="addUserToGroup()"> Add User To Group </button>
<script type="text/javascript">
function addUserToGroup() {
var addUserToGroupEndpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(38)/users";
var payload = JSON.stringify({
'__metadata': { 'type': 'SP.User' },
'LoginName': 'i:0#.f|membership|[email protected]'
});
$.ajax({
url: addUserToGroupEndpoint,
type: "POST",
data: payload,
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log("User Added to Group successfully!");
},
error: function (error) {
console.log(error);
}
});
}
</script>
Verify and use correct user LoginName in payload and group ID from your SharePoint site in REST endpoint.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RaytheonXie-MSFT |
| Solution 2 | Ganesh Sanap |
