Click here to Skip to main content
15,885,278 members
Articles / Web Development / ASP.NET

Using the SharePoint REST API in a SharePoint Add In

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
24 Aug 2015CPOL2 min read 31.5K   8   3
A simple example of a SharePoint Add-In using the REST API and the Cross Domain library

Introduction

Recently I started exploring using the SharePoint REST API framework within a SharePoint Add-In (formerly called SharePoint Apps.) Microsoft has a couple of good pages of documentation, but finding a simple practical example proved challenging. What I wanted was a complete project with step by step instructions on how to access data in a SharePoint website from your add-in by using the cross domain library in SharePoint 2013.

Background

As mentioned, this article and example uses the information found at MSDN:

Access SharePoint 2013 data from add-ins using the cross-domain library

Complete basic operations using SharePoint 2013 REST endpoints

Note: For my example, I used Visual Studio 2015 and a SharePoint 365 site with a List called Movies.

Image 1

Important: The site has sideloading enabled.

Project Setup

You can download my project, but when it comes time to build your own, you will need these steps for initial setup:

Step 1: From the Visual Studio New Project window, choose App for SharePoint

Image 2

For my example, I named the project spRestExample

Step 2: Enter the address of your SharePoint Site. Choose SharePoint-Hosted as how you wish to host the app.

Image 3

Step 3: Specify the target SharePoint Version

Image 4

You will end up with a set of solution files like this (in VS 2015)

Image 5

At this point, hitting run brings up our site with my user name (as a result of javascript in the App.js file)

Image 6

Step 4: Double click the AppManifest.xml file and give set the SharePoint Permissions like this:

Image 7

 

Adding the Code

Double Click the App.js file and remove everything there.

Replace it with this code:

<formatted>

'use strict';

$(document).ready(function () {

    var hostweburl;
    var appweburl;

    //The SharePoint site where the App is installed
    hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
    //The location within the site where the App will be deployed
    appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));

    // resources are in URLs in the form: web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);

    // Use cross-domain library to interact with more than one domain
    //in your remote add-in page through a proxy
    function execCrossDomainRequest() {
        var executor = new SP.RequestExecutor(appweburl);
    }

    $("#showButton").click(function () {

        var executor = new SP.RequestExecutor(appweburl);
        executor.executeAsync(
            {
                url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Movies')/Items?@target='"
                    + hostweburl + "'",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
                success: successHandler,
                error: errorHandler
            }
        );

    });

});

function successHandler(data) {

    var jsonObject = JSON.parse(data.body);
    var moviesHTML = "";
    var results = jsonObject.d.results;
    for (var i = 0; i < results.length; i++) {
        moviesHTML = moviesHTML + "<p><h3>" + results[i].Title + "</p><hr>";
    }

    document.getElementById("resultsDiv").innerHTML = moviesHTML;
}

function errorHandler(error) {
    $("#resultsDiv").append(error.statusText)
}

//function to get a parameter value by a specific key
function getQueryStringParameter(urlParameterKey) {
    var params = document.URL.split('?')[1].split('&');
    var strParams = '';
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split('=');
        if (singleParam[0] == urlParameterKey)
            return decodeURIComponent(singleParam[1]);
    }
}

</formatted>

 

In the Default.aspx file, add this code between the <asp:Content> tags

<div>
         <input id="showButton" type="button" value="Show Movies2" />
    </div>

    <div id="resultsDiv">
    </div>

 

Now you are ready to run the project. The first time you do this, you will be prompted to Trust the new application. Choose the name of your list (Movies in this case) and click Trust It

Image 8

 

You will see your page with your new Show Movies button.

 

Image 9

Clicking the button will now show all the Movie titles

Image 10

Using the project with your site

If you want to run my project against your own SharePoint site, you will need to change the Site Url. You find this property by selecting the project with the Properties window open:

 

Image 11

 

 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Unknown
I started as a graphic designer who got suckered into being the webmaster at an internet startup back in 1999. It was a fun, exciting place to work, so of course it went belly up. Since then, I've been at several large and small enterprise companies working with ASP (yeah, the old school stuff) ASP.NET (VB and C#), SharePoint (2007 to 2013) and have been recently working with AngularJS (not entirely sold on that btw...)

Outside of the development scene, I'm the FlashbackUniverse comics guy. Check out my site for some free downloadable comics and cool weekly posts about geeky stuff.

Comments and Discussions

 
QuestionGet List Items Pin
Intan Puspitasari24-Aug-16 17:46
Intan Puspitasari24-Aug-16 17:46 
AnswerRe: Get List Items Pin
JimShelley25-Aug-16 4:56
JimShelley25-Aug-16 4:56 
SuggestionSharePoint Hosted app with Cross domain library!!! Pin
Atish Dipongkor24-Aug-15 20:46
professionalAtish Dipongkor24-Aug-15 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.