Introduction
This is not an article, but a small tip. In certain cases, it is required to fetch UserId
of particular site users in SharePoint. This tip may be helpful in getting UserId
for site user by passing login name. SharePoint provides OOB REST APIs to get site users, however, with login name format, which is dependent upon SharePoint environment, it becomes little tricky.
The REST endpoint to get site users is : http://<site url>/_api/web/siteusers(@v)?@v='<pass login name>'
Using the Code
The below code can be included on your page to fetch the UserId
of a given Site User.
function GetUserId(userName) {
var prefix = "i:0#.w|";
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
var accountName = prefix + userName;
$.ajax({
url: siteUrl + "/_api/web/siteusers(@v)?@v='" +
encodeURIComponent(accountName) + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
alert("Received UserId" + data.d.Id);
alert(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
});
}
For examples of login names and further information, refer to 'table 1 Login name formats' in MSDN link: http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx.
Points of Interest
Without appending the login name format prefix, SharePoint returns error HTTP 500, hence it is important to identify suitable login format according to the environment and set as prefix on login name.
References: User, Groups and Roles, REST API reference and example:
http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx