SharePoint 2013 Rest Api - How to get List Items

 
Can anyone let me know why the below method fails? I am not getting where i am making mistake. Please help
function getListItems(term) {
            var caml = "<View><Query><Where><BeginsWith><FieldRef Name=Title/><Value Type='Text'>" + term + "</Value></BeginsWith></Where></Query></View>";
            var requestData = { "query": { "__metadata": { "type": "SP.CamlQuery" }, "ViewXml": caml } };
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getbytitle('SampleList')/Getitems",
                method: "POST",
                data:requestData,
                headers: {
                    "accept": "application/json; odata=verbose",
                    "content-type": "application/json; odata=verbose"
                success: function (data) {
                    $("#countItem").html("Pass");
                error: function (data) {
                    $("#countItem").html("Fail");
Below is the responseText (log)
"{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.ClientServiceException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The HTTP method \'GET\' cannot be used to access
the resource \'GetItems\'. The operation type of the resource is specified as \'Default\'. Please use correct HTTP method to invoke the resource.\"}}}"
Navaneeth

Finally executed successfully using below code. The learning is we need to use  type:"POST" instead of method:"POST"
 function getListItems(term) {
            var urltest = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/lists/getByTitle('SampleList')/getitems(<Query><Where><BeginsWith><FieldRef">query=@v1)?@v1={\"ViewXml\":\"<View><Query><Where><BeginsWith><FieldRef
Name='Title'/><Value Type='Text'>" + term + "</Value></BeginsWith></Where></Query><RowLimit>1</RowLimit></View>\"}";
            $.ajax({
                url: urltest,
                type: "POST",
                headers: {
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "Accept": "application/json; odata=verbose",
                    "Content-Type": "application/json; odata=verbose"
                contentType: 'application/json',
                success: function (data) {
                    if (data.d.results.length != 1) {
                        $("#countItem").html("Pass");
                        $("#" + term).parent().parent().prop('disabled', true);
                        $("#" + term).removeAttr("onclick");
                        $("#" + term).css('cursor', 'default');
                        $("#" + term).parent().unbind("mouseenter mouseleave");
                error: function (data) {
                    $("#countItem").html(urltest);
Navaneeth

Similar Messages

  • SharePoint 2013 Rest API - How to get the item count with startsWith

    Hi All,
    I am using the below url to get the item count for specfied startsWith. For example I want to know how many items are there in the list which starts with "A". When i hit the below url in the address bar i am getting HTTP not found.
    siteURL/sites/Apps/SharePointApp3/_vti_bin/listdata.svc/SampleList/items?$filter=startsWith(Title,’A’)
    Navaneeth

    what
    is SharePointApp3.
    here. 
    it is a webpart.
    this will not work on webpart\apps
    Also I am not sure if it will work with specific SampleList 
    Try 
    siteURL/sites/Apps/SharePointApp3/SampleList/_vti_bin/listdata.svc/Keywords?$filter=substringof('r',Title)
    If this helped you resolve your issue, please mark it Answered

  • SharePoint 2010 Rest API: How to add attachment to a list item via ListData.svc

    Hi
    I have set up a project using the REST API in c# Visual Studio 2010.
    I have added a service reference to the URL //site/_vti_bin/listdata.svc/
    I can query the list and get back data, but I can't retrieve the attachments.
    I can write data to the list, but I can't add attachments.
    Are there any examples of how to add or retrieve attachments using the REST API services.
    Thanks
    Mike

    Hi,                                                             
    If you want to work with list attachments using REST API, here are some links will show how to do this using Javascript:
    http://msdn.microsoft.com/en-us/library/office/dn292553.aspx#FileAttachments
    http://chuvash.eu/2013/02/20/rest-api-add-a-plain-text-file-as-an-attachment-to-a-list-item/
    http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2013/06/27/how-to-get-list-item-attachments-using-rest-and-javascript-in-sharepoint-2013.aspx
    Best regards
    Patrick Liang
    TechNet Community Support

  • How to get List Item attachments name without write any custom code or any database query?

    Hi,
    How to get List Items attachments name without write any custom code or any database query?

    You can get it from Rest,
    There are 2 options,
    1) create a 'Result Source' which has a search query for that List which has attachments 
     - Use rest query to get the 'Filename' , it will have the attachment file name 
    For example, if the result source id is : 73e6b573-abf8-4407-9e5f-8a85a4a95159 , then the query will be 
    http://[site URL]/_api/search/query?querytext='*'&selectproperties='Title,Path,FileExtension,SecondaryFileExtension,Filename'&sourceid='73e6b573-abf8-4407-9e5f-8a85a4a95159'&startrow=0&rowLimit=100
    You can refine the query, be giving proper 'querytext'
    2) Use the List rest api
    For example if your list guid is :38d524a1-e95c-439f-befd-9ede6ecd242e
    You can get he attachments for 1st item using this 
    http://[Site URL]/_api/lists(guid'38d524a1-e95c-439f-befd-9ede6ecd242e')/items(1)/AttachmentFiles
    get2pallav
    Please click "Propose As Answer" if this post solves your problem or "Vote As Helpful" if this post has been useful to you.

  • SharePoint 2013 REST API with C# - Mapping HTTP verbs to data operations - Requesting FormDigest

    SharePoint REST interface maps HTTP verbs to data operations. Endpoints that represent
    Read operations map to HTTP
    GET commands. Endpoints that represent update operations map to HTTP
    POST commands, and endpoints that represent update or insert operations map to HTTP
    PUT commands (Ref:
    How to: Complete basic operations using SharePoint 2013 REST endpoints).
    Is this mapping of HTTP verbs to CRUD operations a design paradigm or whether there are other technical reasons to this mapping
    Is is possible to use a GET command for say an update operation or a POST for say a read operation.If so, what consideration make the choice of either usage
    In the code snippet below FormDigest is requested as POST, why not use GET here?
    private static string GetFormDigest(string webUrl)
    //Validate input
    if (String.IsNullOrEmpty(webUrl) || String.IsNullOrWhiteSpace(webUrl))
    return String.Empty;
    //Create REST Request
    Uri uri = new Uri(webUrl + "/_api/contextinfo");
    HttpWebRequest restRequest = (HttpWebRequest)WebRequest.Create(uri);
    restRequest.Credentials = CredentialCache.DefaultCredentials;
    restRequest.Method = "POST";
    restRequest.ContentLength = 0;
    //Retrieve Response
    HttpWebResponse restResponse = (HttpWebResponse)restRequest.GetResponse();
    XDocument atomDoc = XDocument.Load(restResponse.GetResponseStream());
    XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
    //Extract Form Digest
    return atomDoc.Descendants(d + "FormDigestValue").First().Value;
    Thanks - Abhishek

    Many SharePoint REST api methods use parameters. It is much more efficient to post parameters than use query string variables.  Many times complex types are sent and these require json notation objects posted in the body. In the case of "_api/contextinfo,
    it is recommended to use POST rather than a GET when using sensitive data. GET responses can be cached. Since you are getting a security token back in that call it is recommended to use a POST.
    http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post
    Blog | SharePoint Field Notes Dev Tools |
    SPFastDeploy | SPRemoteAPIExplorer

  • Sharepoint 2013 REST API calls with JASONP support

    We are working on sharepoint online integration with PHP Based application. We need to provide REST API call which supports JSONP.
    So is it possible to create new REST API Endpoints in Sharepoint online APP? Please sugggest right direction.

    Hi,
    In Office 365 (aka SharePoint Online), you can simply consume the SharePoint data through REST API or WS call,but cannot create your own endpoint.
    By default you can get the JSON response from the Office 365 REST API,its upto you to use the JSONP on your client compatibility not on SharePoint online REST API.
    Sometime before I tried, It didn't work for me.
    If you develop the AppModel, SPRequestor.js does the same job(overcome the Cross domain restriction) the what JSONP does.
    Murugesa Pandian| MCPD | MCTS |SharePoint 2010

  • Trying to Access SharePoint 2013 Rest Api in HTML page but getting Mime Type Exception with Status Success

    I am trying to invoke the SharePoint Rest Api using HTML page. I have included the Access Control Allow Origin to the web.config file. I am getting Readty State 4 and
    Status Success but still I am getting the below error.
    Refused to execute script from 'http://<server>/_api//web/lists?callback=jQuery172045857910416089_1430217181282&_=1430217363882' because its MIME
    type ('application/atom+xml') is not executable, and strict MIME type checking is enabled.
        <script>
            $(document).ready(function () {
                $("#KMPDiscussions").click(function () {
                    //$.support.cors = true;
                    $.ajax({
                        url: "http://<server>/_api//web/lists",
                        dataType: "jsonp",
                        type: "GET",
                        method: "GET",
                        contentType: "application/javascript",
                        headers: {
                            "content-type":
    "application/json;odata=verbose",
                            "accept": "application/json;odata=verbose",
                        success: function onSuccess(data) {
                            alert("Inside Alert");
                        error: function onError(data){
                            alert("Error: "
    + data);
        </script>
    It always hits the error on callback.
    Is there any other way that I can invoke SharePoint Rest Api from a Cross Domain. Please Help.

    Hi Chris,
    Thanks for the reply,Here iam using different files to be uploaded in library.
    please find the below snapshot of json response and ULS logs.
    12/22/2013 18:31:15.02 w3wp.exe (0x3338) 0x401C SharePoint Foundation Files 
    abq2i High Could not get DocumentContent row: 0x80004005. 79f7629c-4694-c026-
    3349-2049178ee919
    12/22/2013 18:31:15.02 w3wp.exe (0x3338) 0x401C SharePoint Foundation Files 
    aiv4w Medium Spent 0 ms to bind -1 byte file stream 79f7629c-4694-c026-3349-
    2049178ee919 
    12/22/2013 18:31:15.02 w3wp.exe (0x3338) 0x401C SharePoint Foundation Files 
    aise3 Medium Failure when fetching document. 0x80070012 79f7629c-4694-c026-
    3349-2049178ee919
    12/22/2013 18:31:15.39 w3wp.exe (0x3338) 0x0D4C SharePoint Foundation 
    Database ab1a9 High Failed to get document content data.
    System.ComponentModel.Win32Exception (0x80004005): Cannot complete this function     at
    Microsoft.SharePoint.SPSqlClient.GetDocumentContentRow(Int32 rowOrd, Object
    ospFileStmMgr, SPDocumentBindRequest& dbreq, SPDocumentBindResults& dbres) 
    79f7629c-76ab-c026-3349-2c9132b13e9a
    12/22/2013 18:31:15.39 w3wp.exe (0x3338) 0x4184 SharePoint Foundation 
    Database ab1a9 High Failed to get document content data.
    System.ComponentModel.Win32Exception (0x80004005): Cannot complete this function     at
    Microsoft.SharePoint.SPSqlClient.GetDocumentContentRow(Int32 rowOrd, Object
    ospFileStmMgr, SPDocumentBindRequest& dbreq, SPDocumentBindResults& dbres) 
    79f7629c-76ab-c026-3349-281167b6cd09
    Thanks again,
    Naresh.

  • How to get list item from LongListSelector

    I have a list item in LongListSelector like this:
    Now when i tap on the app button so I will have the list of item in the LongList where check box value is true
    Any help or advice ?

    Add a property to the class the long list selector is bound to for the checkbox.  Loop through the items in the data source and use the new property to tell what is checked

  • How to Get List Item in Custom Context Menu?

    Hi,
    I got this code from the net.
    <CustomAction Id="SPTest.CustomMenuItem.ButtonClicked"
    RegistrationType="ContentType"
    RegistrationId="0x0101"
    Location="EditControlBlock"
    ImageUrl="/_layouts/IMAGES/DOCLINK.GIF"
    Sequence="600"
    Title="Click Me!"
    Description="Shows an alert message for this content type."
    >
    <UrlAction Url="javascript:alert('Hello World!');" />
    </CustomAction>
    It creates a custom context menu. How can i get the selected item using that code..
    Sorry for the tons of question. SharePoint newbie here (5 weeks in SP), Hehhehe!

    If you can redirect your request on context.....you can try this line of code
    <UrlActionUrl=”~site/_layouts/ItemAudit.aspx?ID={ItemId}&amp;List={ListId}”/>
    The Idea is to send in query string parameter and get the ItemID in the Pageload Event of the page you want to redirect to.
    Other tokens that are available
    Token
    Replaced By
    ~site/
    SPContext.Current.Web.ServerRelativeUrl
    ~sitecollection/
    SPContext.Current.Site.ServerRelativeUrl
    {ItemId}
    item.ID.ToString()
    {ItemUrl}
    item.Url
    {SiteUrl}
    web.Url
    {ListId}
    list.ID.ToString(“B”)
    {RecurrenceId}
    item.RecurrenceID
    Srikant N , MCPD SharePoint Developer 2010

  • How to create list items with multiple attachment files using rest api javascript

    In one of user form I am using javascript rest api to create a list item with multiple attachment files. So far I am able to create list item and once created uploading an attachment file. But this is two step process first create an item and then upload
    a file.
    It create an additional version of the item which is not desired. Also I am not able find a way to attach multiple files in a go. Following is the code I am using.
    createitem.executeAsync({
                    url: "/_api/web/lists/GetByTitle('UserForm')/items(1)/AttachmentFiles/add(FileName='" + aFile.name + "')",
                    method: "POST",
                    contentType: "application/json;odata=verbose",
                    headers: {
                        "Accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val()
                    binaryStringRequestBody: true,
                    body: fileContent,
                    success: fnsuccess,
                    error: fnerror
    So somehow I need to combine item attributes along with attachment files in body: param. I visited https://msdn.microsoft.com/en-us/library/office/dn531433.aspx#bk_ListItem but no success.
    Appreciate any help.

    Thanks Mahesh for the reply and post you share it was useful.
    But this does not solve the core of the issue. You are uploading attachments after creation of item and multiple files are being attached in loop. This is kind of iterative update to an existing item with attachments. This will end up creating multiple versions. 
    What I am trying to achieve is to create an item along with multiple attachments in a go. No item updates further to attach a file.
    Please suggest how this can be done in one go. SharePoint does it when one creates an item with multiple attachment.
    Thanks for your reply.

  • Get list items using spservices for sharepoint 2013

    Hi,
    I have a requirement like below.
    I have 2 sharepoint custom list with some columns.
    List1:listA
    List2:listB
    Now when i open the listB new item form i want some of the field values from listA should auto populate in Textboxes of listB new form.
    Is there any ways to implement this?
    Regards,
    Poovi

    Hi Poovi,
    You can achieve this using jQuery to get the SharePoint list items. Refer the below articles. It has explained how to get list items using jQuery and auto populate a text-box from a list item as a source.
    You can put this code in list forms through SharePoint Designer. The articles explain about auto populating text box of web part but similarly you can implement it for list form, because nevertheless the text boxes are same.
    http://www.c-sharpcorner.com/UploadFile/sagarp/sharepoint-2010-jquery-autocomplete-textbox-containing-list/
    http://tomvangaever.be/blogv2/2011/07/sharepoint-2010-autocomplete-with-list-items/
    Please remember to click 'Mark as Answer' if the reply answers your query or 'Upvote' if it helps you.

  • How to get List of SharePoint Groups to which Current Users belongs using Javascript ?

    How to get List of SharePoint Groups to which Current Users belongs using JavaScript? Not JSOM

    Here is the code that worked for me:
    var userid= _spPageContextInfo.userId;
      var requestUri = _spPageContextInfo.webAbsoluteUrl + '/_api/web/CurrentUser/Groups?$select=Id,Title';
    alert(requestUri);
      var requestHeaders = { "accept" : "application/json;odata=verbose" };
      $.ajax({
        url : requestUri,
        contentType : "application/json;odata=verbose",
        headers : requestHeaders,
        success : onSuccess,
        error : onError
      function onSuccess(data, request){
    var s='';
     for (var i = 0; i < data.d.results.length; i++)
    s +=data.d.results[i].Title+'\n';
        alert(s);
      function onError(error) {
        alert("error");

  • Im using CloverETL to connec to SharePoint using REST API.

    my team is trying to get the List items in SharePoint using REST api. we are using the CloverETL tool using the REST api URL of the list and the credentials in SharePoint which has full control. Below is the rest command that we used.
    /_api/web/lists/getbytitle('title of list')/items 
    when viewing this URL on the same Internet explorer with a user log on to sharepoint the XML of the list is successfully showing. but when we try to load it on the CloverETL tool using the same SharePoint credentials it says access is denied. Also when viewing
    the URL to a browser with no other SharePoint sites open it also says access is denied. 

    how is the webapp configured, as far as authentication?
    Scott Brickey
    MCTS, MCPD, MCITP
    www.sbrickey.com
    Strategic Data Systems - for all your SharePoint needs

  • HTTP 403 while using SharePoint Online REST API anonymously

    Hey Team,
    While using REST API to get list items (SharePoint Online) anonymously, I am getting HTTP 403 error:
    Request: http://server/site/_api/web/lists('guid')/items?$select=Title,Products/Name&$expand=Products/Name
    Response: HTTP 403 : System.UnauthorizedAccessException : Access denied. You do not have permission to perform this action or access this resource.
    Authenticated users do not face this issue. The list has anonymous access (View) enabled. Anonymous users can access the lists without facing any issue.
    I am not sure and could not able to find any link that says anonymous users can't use REST API to get SPListItems. Any input in this regard will be highly appreciated.
    Regards,
    Sanjay
    Either you love IT or leave IT

    Hi,
    From this documentation from MSDN about
    Reading data with REST, “Note that you cannot obtain an access token from code that is running on a browser client. You must obtain the access token from code that is running
    on a server”, it will only allow the authenticated users who has an access token to access the REST API.
    The two links below will provide more information about authentication in SharePoint 2013:
    http://msdn.microsoft.com/en-us/library/fp142382.aspx
    http://msdn.microsoft.com/en-us/library/jj687470.aspx
    Thanks
    Patrick Liang
    Forum Support
    Please remember to mark the replies as answers if they
    help and unmark them if they provide no help. If you have feedback for TechNet
    Subscriber Support, contact [email protected]
    Patrick Liang
    TechNet Community Support

  • REST API POST and GET Error--Retriving following sites news feed

    i have used below code to retrive the newsfeeds but im getting 403 error.i think url formation for POST and GET is wrong.Kindly anyone worked help mee. 
    var feedManagerEndpoint;
    // Get the SPAppWebUrl parameter from the query string and build
    // the feed manager endpoint.
    $(document).ready(function () {
    var appweburl;
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
    var param = params[i].split("=");
    if (param[0] === "SPAppWebUrl") appweburl = param[1];
    alert(appweburl);
    feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";
    alert(feedManagerEndpoint);
    postToMyFeed();
    // Publish a post to the current user's feed by using the
    // "<app web URL>/_api/social.feed/my/Feed/Post" endpoint.
    function postToMyFeed() {
    alert('pOST');
    $.ajax( {
    url: feedManagerEndpoint+"/my/Feed/Post",
    type: "POST",
    data: JSON.stringify( {
    'restCreationData':{
    '__metadata':{
    'type':'SP.Social.SocialRestPostCreationData'
    'ID':null,
    'creationData':{
    '__metadata':{
    'type':'SP.Social.SocialPostCreationData'
    'ContentText':'This post was published using REST.',
    'UpdateStatusText':false
    headers: {
    "accept": "application/json;odata=verbose",
    "content-type":"application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
    success: getMyFeed,
    error: function (xhr, ajaxOptions, thrownError) {
    alert("POST error:\n" + xhr.status + "\n" + thrownError);
    // Get the current user's feed by using the
    // "<app web URL>/_api/social.feed/my/Feed" endpoint.
    function getMyFeed() {
    alert('get');
    $.ajax( {
    url: feedManagerEndpoint +"/my/Feed",
    headers: {
    "accept": "application/json;odata=verbose"
    success: feedRetrieved,
    error: function (xhr, ajaxOptions, thrownError) {
    alert("GET error:\n" + xhr.status + "\n" + thrownError);
    // Parse the JSON data and iterate through the feed.
    function feedRetrieved(data) {
    var stringData = JSON.stringify(data);
    var jsonObject = JSON.parse(stringData);
    alert(jsonObject);
    var feed = jsonObject.d.SocialFeed.Threads;
    alert(feed.results);
    var threads = feed.results;
    var feedContent = "";
    for (var i = 0; i < threads.length; i++) {
    var thread = threads[i];
    var participants = thread.Actors;
    var owner = participants.results[thread.OwnerIndex].Name;
    feedContent += '<p>' + owner +
    ' said "' + thread.RootPost.Text + '"</p>';
    $("#message").html(feedContent);

    Hi Scott,
    With EnableQueryRules and ProcessBestBets set to true in the search rest api, we can get the promoted results(best bets) in SharePoint 2013.
    I recommend to type the search rest api URL in the browser directly and then check if the best bets are displayed at the top of the search results.
    It will not displayed inside the table for normal results.
    Please also make sure that the query text matches the query rule condition.
    Thanks,
    Victoria
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected]

Maybe you are looking for

  • Can I set a reminder for when I arrive in a city?

    Here's the problem...We were driving several hours back home and I figured it would be helpful to set a reminder to perform an errand when we got back to the city. So I asked Siri and she wasn't having any of it. I figured she just was being glitchy.

  • Arbitrary signal generation acquire 5411 5911

    An arbitrary signal generated on a PCI-based NIFGEN(5411) is not acquired correctly on a PCI-based NISCOPE (5911). I use RTSI to synchronize the two boards (5911 is the master). When the 5411 board has generated the waveform the 5911 board should sta

  • Editing existing PDF documents

    I often receive PDF forms that require information to be added and then returned to the sender. How can you open a PDF file in Acrobat such that you can type in the necessary information and then resave it as a PDF file? Note that I have no design in

  • Placing photo into a resume template

    Hi, been at this for a couple of hours, learning plenty about everything other than what I really want to do: How do I place a photo into a Pages template? I am using one of the resume templates, have my completed resume and it looks great. Only the

  • Library size management

    i saw a short text explaining that folder vs album arrangement in library could increase size considerably. anyone knows how this works so i can put that into my workflow/organizing considerations? I still have some 60 GB pics I'm getting in to A2 so