14

The structure of my REST-API Url is /_api/Web/Lists/GetByTitle('FAQ')/Items.

Each item can be liked by users (like in discussion boards).

How can I send a "Like" or "Unlike" command via REST?

1

2 Answers 2

8

Do you use Javascript to send "Like"? At this case you could use JSOM to set likes:

<script type="text/javascript">

SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js');
    SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', UpdateLike);
});

function UpdateLike() {
    var itemId = 1;
    var listId = "361d6bc5-0034-4f53-8f7b-f7198a3a844c";//set list id
    var setLike = true;//set false to unlike

    var ctx = new SP.ClientContext("siteUrl");//your site url
    Microsoft.Office.Server.ReputationModel.Reputation.setLike(ctx, listId, itemId, setLike);

    ctx.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
};

function RatingSuccess(sender, args) {
    alert('Rating Done Successfully');
}

function RatingFailure(sender, args) {
    alert('SetRating failed:' + args.get_message());//note that you will get error if try like twice
}
</script>

That is not well documented. I could not find is it available by REST or not.

4
  • Ooh this looks nice. I'll try it out and come back to you, thanks ! Jan 28, 2016 at 17:32
  • @MonsieurPoivron, how is it going? Do you need any help with solution? Feb 3, 2016 at 9:26
  • this works .. thannks. Oct 10, 2017 at 5:39
  • 1
    this works ... thanks. One question - by OOTB functionality when you clink on Like/Unlike, it does not update the item but by the above code item gets updated. Is other anything we can do to do not update the item Oct 10, 2017 at 5:47
5

The below example demonstrates how to like/unlike a resource via SharePoint REST API, it simulates Microsoft.Office.Server.ReputationModel.Reputation.setLike method to some extent

Prerequisites: Rating settings needs to be enabled per List

var Reputation = Reputation || {};

Reputation = (function () {

    function executeJson(options) {
        var headers = options.headers || {};
        headers["Accept"] = "application/json;odata=verbose";
        if (options.method == "POST") {
            headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
        }

        var ajaxOptions =
            {
                url: options.url,
                type: options.method,
                contentType: "application/json;odata=verbose",
                headers: headers
            };
        if (options.method == "POST") {
            ajaxOptions.data = JSON.stringify(options.payload);
        }

        return $.ajax(ajaxOptions);
    }

    function getListItem(webUrl, listTitle, itemId) {
        var options = {
            url: webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")",
            method: "GET"
        };
        return executeJson(options);
    }

    function updateListItem(webUrl, listTitle, itemId, itemPayload) {
        var options = {
            url: webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items(" + itemId + ")",
            method: "POST",
            headers: {
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"
            },
            payload: itemPayload
        };
        return executeJson(options);
    }



    return {
        setLike: function (webUrl, listTitle, itemId, setLike) {
            //1.retieve existing ratings
            return getListItem(webUrl, listTitle, itemId)
                .then(function (data) {
                    //2.set like for current user
                    var userKey = _spPageContextInfo.userId.toString();
                    var likes = data.d.LikesCount;
                    var updated = false;
                    var userKeys = data.d.LikedByStringId == null ?  [] : data.d.LikedByStringId.results;
                    var posKey = userKeys.indexOf(userKey);
                    if (posKey == -1) {
                        if (setLike) {
                            userKeys.push(userKey);
                            likes++;
                            updated = true;
                        }
                    }
                    else {
                        if (!setLike) {
                            userKeys.splice(posKey, 1);
                            likes--;
                            updated = true;
                        }
                    }

                    if (updated) {
                        var itemProperties = {
                            "__metadata": data.d.__metadata,
                            "LikedByStringId": {"results": userKeys},
                            LikesCount: likes
                        };
                        return updateListItem(webUrl, listTitle, itemId, itemProperties);
                    }
                    return data;

                });
        }
    };
})();

Gist: setLike.js

Usages

  • like a resource: Reputation.setLike(webUrl, listTitle, itemId, true)
  • unlike a resource: Reputation.setLike(webUrl, listTitle, itemId, false)

Example

var listTitle = "Feedback";
var itemId = 1;
var webUrl = _spPageContextInfo.webServerRelativeUrl;

Reputation.setLike(webUrl, listTitle, itemId, true)
    .done(function (item) {
        console.log('Liked');
    })
    .fail(function (error) {
        console.log(JSON.stringify(error));
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.