10

I have a SharePoint list and i need to get the list items by using JSOM.how to add CAML query with in the API method? i have used the below code

    var url = "/_api/Web/Lists/GetByTitle('list')/Items(query=@v1)?@v1={'ViewXml':'<View><Query><RowLimit>1</RowLimit></Query></View>'}"
    var result;
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + url,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
       result = data.d.results;
alert(result)

        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });

Suggest any idea to form the URL.

3
  • you will get list items when you give a rest call, why do you need a caml query for that. Commented Feb 14, 2017 at 13:05
  • Is possible to get list items with custom querying?
    – PGP
    Commented Feb 14, 2017 at 13:07
  • Thanks @Rob Windsor for the approach, after trying multiple times using JSOM nested calls, I decided to re-write the code and use REST services and it is all working thanks for the big help! Commented Jul 7, 2018 at 15:39

3 Answers 3

15

There are a lot of things to cover in your question.

First, JSOM and REST are different things. JSOM is the JavaScript version of the Client Object Model. This is an API designed to be similar to the Server Object Model. The REST API is a data-centric web service designed to be used with modern web development.

Second, as the comments mention, you don't need to do a CAML query to do get list items with the REST API. This is something that is native to the API itself.

Here is a sample showing how to get list items using the REST API.

var call = jQuery.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Products')/Items",
    type: "GET",
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose"
    }
});
call.done(function (data, textStatus, jqXHR) {
    var message = jQuery("#message");
    message.text("Products");
    message.append("<br/>");
    jQuery.each(data.d.results, function (index, value) {
        message.append(value.Title);
        message.append("<br/>");
    });
});
call.fail(function (jqXHR, textStatus, errorThrown) {
    var response = "";
    try {
        var parsed = JSON.parse(jqXHR.responseText);
        response = parsed.error.message.value;
    } catch (e) {
        response = jqXHR.responseText;
    }
    alert("Call failed. Error: " + response);
});

If you do need to do a CAML query you can use this syntax:

var viewXml = {
    ViewXml: "<View>" +
        "<Query>" +
        "<Where><Eq>" +
        "<FieldRef Name='Category' LookupId='True' />" +
        "<Value Type='Lookup'>1</Value>" +
        "</Eq></Where>" +
        "</Query>" +
        "</View>"
}

var call = jQuery.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('Products')/GetItems(query=@v1)?" +
        "@v1=" + JSON.stringify(viewXml),
    type: "POST",
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose",
        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
    }
});
call.done(function (data, textStatus, jqXHR) {
    var message = jQuery("#message");
    message.text("Beverages");
    message.append("<br/>");
    jQuery.each(data.d.results, function (index, value) {
        message.append(value.Title);
        message.append("<br/>");
    });
});
call.fail(function (jqXHR, textStatus, errorThrown) {
    var response = "";
    try {
        var parsed = JSON.parse(jqXHR.responseText);
        response = parsed.error.message.value;
    } catch (e) {
        response = jqXHR.responseText;
    }
    alert("Call failed. Error: " + response);
});

For more information you can check out the slides and demos from my Introduction to the Client Object Model and REST API conference talk.

I also have a course on Client Object Model and REST API development in the Pluralsight library that you may find valuable.

1

JSOM, You can use the SharePoint client object model to retrieve, update, and manage data in SharePoint

For more information, use below link

Complete basic operations using JavaScript library code in SharePoint

REST : SharePoint introduces a Representational State Transfer (REST) service that is comparable to the existing SharePoint client object models. Now, developers can interact remotely with SharePoint data by using any technology that supports REST web requests. This means that developers can perform Create, Read, Update, and Delete (CRUD) operations from their SharePoint Add-ins, solutions, and client applications, using REST web technologies and standard Open Data Protocol (OData) syntax.

For more information, use below link

Get to know the SharePoint REST service

Retrieve the SharePoint list items using rest and caml query (Including caml query in the body) using below code

    function restCallwithCaml(listName, caml) {  
    /// get the site url
    var siteUrl = _spPageContextInfo.webAbsoluteUrl;  
    /// set request data
    var data = { 'query' :{'__metadata': { 'type': 'SP.CamlQuery' }, 'ViewXml': caml}};  
    /// make an ajax call
    $.ajax({  
            url: siteUrl+"/_api/Web/Lists/getByTitle(listName)/GetItems?$select=ID,Title",  
            method: "POST",  
            data: JSON.stringify(data),  
            headers: {  
               "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
               'content-type': 'application/json;odata=verbose',  
               'accept': 'application/json;odata=verbose',         
            },  
            success: function (response) {  
            alert('success');
            console.log(response);
            ///do your code
            },  
            error: function (data) {  
            alert('error');
            ///do your code
           }  
    });  
} 

var caml = <camlquery>;
var list = <listname>;
restCallwithCaml(list, caml); 

Retrieve the SharePoint list items using rest and caml query (Including caml query in the query string) using below code

var viewXml = {
    ViewXml: "<camlquery-here>"
}

var call = jQuery.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('<listname-here>')/GetItems(query=@v1)?$select=Title,FileRef,EncodedAbsUrl&" +
        "@v1=" + JSON.stringify(viewXml),
    type: "POST",
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose",
        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
    }
});
call.done(function (data) {
    console.log(data);
    jQuery.each(data.d.results, function (index, value) {
        //console.log(value.Title);

    });
});
call.fail(function (jqXHR) {
    var response = "";
    var response = "";
    try {
        var parsed = JSON.parse(jqXHR.responseText);
        response = parsed.error.message.value;
    } catch (e) {
        response = jqXHR.responseText;
    }
    alert("Call failed. Error: " + response);
});

If you want improve the REST API performance, hope below link will be helpful

Improving REST API performance with JSON Light

If you have idea to improve my answer. Please do comment.

Thank you.

0

First of all CAML is used in REST URL to bifurcate the limitation of REST URL (endpoint) of 260 characters in GET call. Please refer below URL to understand the limitations of REST and workarounds for those, https://www.c-sharpcorner.com/blogs/sharepoint-rest-api-limitation

Also, when used CAML in REST GET/POST call, we dont directly include query in URL which may again lead the URL to cross the 260 character limit so instead we use POST call and pass the CAML query in data part like below, https://www.c-sharpcorner.com/blogs/sharepoint-rest-api-caml-query

I hope this helps.

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.