Create And Consume MVC CRUD Web API In SharePoint 2016 - Part Two

SharePoint can consume a Web Service, WCF Service, or Web API when we have to integrate a .NET Service with SharePoint. In the previous article, we saw how to create the MVC CRUD Web API using Entity Framework. In this article, we will see how to host the Web API in IIS and consume the Web API for performing CRUD operations from within SharePoint 2016.

Web API

Host the Web API in IIS

Before consuming the Web API from SharePoint, we will host it in IIS. Open IIS Manager and create a Website.

Web API

Specify the Site Name, Physical Path, and the port used for hosting the Web API.

Web API

Once the site is up and running, go to the Visual Studio Solution and "Publish" the solution.

Web API

Select "Custom" option and specify a name.

Web API

Select the publish method as Web Deploy. Specify the Server, Site name, and the destination URL.

Web API

Upon clicking "Publish", the Web API will be hosted in the IIS Site.

Test the Web API

Now, let’s go ahead to the browser and hit the URL http://sitename/api/films. However, we have received the error - Login Failed for User “Domain\machine$”.

Web API

In order to resolve this issue, we can either grant this user the required access in the SQL Server or we can change the application pool account that will be used by the Web API to access SQL Server.

Web API

Currently, it is set as Application Pool Identity.

Web API

Let’s change it to a different user with SQL Server permissions.

Web API

Now, checking the Web API URL in browser, we can see the data pulled from SQL Server table.

Web API

We have a fully functional Web API that connects to the SQL Server table using Entity Framework hosted in IIS. Now, let’s see how we can consume this from SharePoint. As the first step, we will create a UI for invoking the CRUD operations.

HTML Structure

The HTML structure for the UI that will call the various methods is defined in the Web API Controller, as shown below.

Web API

Here, ‘Search Film’ button will call the GET method issuing the Web API AJAX request. ‘Add Film’ button will call the POST method, ‘Update Film’ will call the Put method, and ‘Delete Film’ will call the DELETE method using the Web API URL. We will discuss in detail about these method calls in the upcoming section.

  1. <table>  
  2.     <tr>  
  3.         <td>  
  4.             <div>  
  5.                 <h2>Films Database</h2>  
  6.                 <table id="Film" cellpadding="2" cellspacing="2" border="1" width="400px">  
  7.                     <tr>  
  8.                         <td style="background-color: white; color: grey">Film ID</td>  
  9.                         <td style="background-color: white; color: grey">Film Name</td>  
  10.                         <td style="background-color: white; color: grey">Director</td>  
  11.                         <td style="background-color: white; color:grey">Year</td>  
  12.                     </tr>  
  13.                 </table>  
  14.             </div>  
  15.             </br>  
  16.             <div>  
  17.                 <h2>Search by Film ID</h2>  
  18.                 <input type="text" size="5" id="FilmId" />  
  19.                 <input type="button" value="Search Film" onclick="find();" />  
  20.                 <p id="FilmSearch"></p>  
  21.             </div>  
  22.         </td>  
  23.         <td>  
  24.             <div>  
  25.                 <h2>Add/Update by Film ID</h2>  
  26.                 <table id="FilmUpdate" cellpadding="2" cellspacing="2" border="1" width="400px">  
  27.                     <tr>  
  28.                         <td style="background-color: white; color: grey">Film ID</td>  
  29.                         <td style="background-color: white; color: grey">Film Name</td>  
  30.                         <td style="background-color: white; color: grey">Director</td>  
  31.                         <td style="background-color: white; color:grey">Year</td>  
  32.                     </tr>  
  33.                     <tr>  
  34.                         <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmIdToUpdate" /></td>  
  35.                         <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmNameUpdated" /></td>  
  36.                         <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmDirectorUpdated" /></td>  
  37.                         <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmYearUpdated" /></td>  
  38.                     </tr>  
  39.                     <tr>  
  40.                         <td><input type="button" value="Add Film" onclick="Add();" /></td>  
  41.                         <td><input type="button" value="Update Film" onclick="Update();" /></td>  
  42.                     </tr>  
  43.                 </table>  
  44.             </div>  
  45.             <div>  
  46.                 <h2>Delete by Film ID</h2>  
  47.                 <input type="text" size="5" id="FilmIdToDelete" />  
  48.                 <input type="button" value="Delete Film" onclick="Delete();" />  
  49.             </div>  
  50.         </td>  
  51.     </tr>  
  52. </table>  
Get All Items

We can use the “api/films” Web API URL to get all the list items from the SQL Server table. We will then issue an AJAX call and append the returned data dynamically to the HTML table named ‘Film’. The function to retrieve the film information is as shown below:
  1. functionGetFilmData() {  
  2.     varuri = 'http://localhost:8082/api/films';  
  3.     $.getJSON(uri)  
  4.         .done(function(data) {  
  5.             $.each(data, function(key, item) {  
  6.                 $('#Film').append("<tr><td>" + item.id + "</td>" + "<td>" + item.FilmName + "</td>" + "<td>" + item.Director + "<td>" + item.Year + "</td></tr>");  
  7.             });  
  8.         });  
  9. }  
Web API

Search for an Item

In order to search for a specific item, we will be making use of the Web API URL “api/films/5” where ‘5’ is the id of the item to be searched for. The function to search the film information is as shown below.
  1. varuri = 'http://localhost:8082/api/films';  
  2.   
  3. function find() {  
  4.     var id = $('#FilmId').val();  
  5.     $.getJSON(uri + '/' + id)  
  6.         .done(function(data) {  
  7.             $('#FilmSearch').text(formatItem(data));  
  8.         })  
  9.         .fail(function(jqXHR, textStatus, err) {  
  10.             $('#Film').text('error' + err);  
  11.         })  
  12. }  
  13. functionformatItem(item) {  
  14.     returnitem.FilmName + '-' + item.Director + '-' + item.Year;  
  15. }  
Web API

Add an Item

In order to add the item, we will issue a POST request using the Web API URL “api/films/id”. We accept the input using input fields defined in the HTML structure and create an object based on the input. We will be passing the object as the data attribute while issuing the AJAX request. The function to add the film information is shown below.
  1. function Add() {  
  2.     var id = $('#FilmIdToUpdate').val();  
  3.     varapiURL = 'http://localhost:8082/api/films/' + id;  
  4.     var film = new Object();  
  5.     film.id = $('#FilmIdToUpdate').val();  
  6.     film.FilmName = $('#FilmNameUpdated').val();  
  7.     film.Director = $('#FilmDirectorUpdated').val();  
  8.     film.Year = $('#FilmYearUpdated').val();  
  9.     $.ajax({  
  10.         url: apiURL,  
  11.         type: 'POST',  
  12.         dataType: 'json',  
  13.         data: film,  
  14.         success: function(data, textStatus, xhr) {  
  15.             alert("Film Record with ID : " + id + " Added !");  
  16.             $("#Film").find("tr:gt(0)").remove();  
  17.             GetFilmData();  
  18.         },  
  19.         error: function(xhr, textStatus, errorThrown) {  
  20.             alert("An error occurred!!");  
  21.         }  
  22.     });  
  23. }  
Web API

Upon inputting the values and clicking in Add Film, it will add the details to the table.

Web API

Web API

Update an Item

In order to update the item, we will issue a PUT request using the Web API URL “api/films/id”. We accept the input using input fields defined in the HTML structure and create an object based on the input. We will be passing the object as the data attribute while issuing the AJAX request. The function to update the film information is shown below.
  1. function Update() {  
  2.     var id = $('#FilmIdToUpdate').val();  
  3.     varapiURL = 'http://localhost:8082/api/films/' + id;  
  4.     var film = new Object();  
  5.     film.id = $('#FilmIdToUpdate').val();  
  6.     film.FilmName = $('#FilmNameUpdated').val();  
  7.     film.Director = $('#FilmDirectorUpdated').val();  
  8.     film.Year = $('#FilmYearUpdated').val();  
  9.     $.ajax({  
  10.         url: apiURL,  
  11.         type: 'PUT',  
  12.         dataType: 'json',  
  13.         data: film,  
  14.         success: function(data, textStatus, xhr) {  
  15.             alert("Film Record with ID : " + id + " Updated!");  
  16.             $("#Film").find("tr:gt(0)").remove();  
  17.             GetFilmData();  
  18.             ClearText();  
  19.         },  
  20.         error: function(xhr, textStatus, errorThrown) {  
  21.             alert("An error occurred!!");  
  22.         }  
  23.     });  
  24. }  
Web API

Delete an item

In order to delete the item, we will issue a DELETE AJAX request using the Web API URL “api/films/id”. The id is accepted using input text from the UI. The function to delete the film information is shown below.
  1. function Delete() {  
  2.     var id = $('#FilmIdToDelete').val();  
  3.     varapiURL = 'http://localhost:8082/api/films/' + id;  
  4.     $.ajax({  
  5.         url: apiURL,  
  6.         type: 'DELETE',  
  7.         dataType: 'json',  
  8.         success: function(data, textStatus, xhr) {  
  9.             alert("Film Name: " + data.FilmName + ", Director: " + data.Director + " . Record Deleted !");  
  10.             $("#Film").find("tr:gt(0)").remove();  
  11.             GetFilmData();  
  12.         },  
  13.         error: function(xhr, textStatus, errorThrown) {  
  14.             alert("An error occurred!!");  
  15.         }  
  16.     });  
  17. }  
Web API

On clicking Delete Item, the item will be removed from the SQL Server table as well as the UI.

Web API



Full Code for invoking Web API CRUD from SharePoint
  1. <head>  
  2.     <title>Film Database</title>  
  3.     <style type="text/css">  
  4.         body {  
  5.             background-color: silver;  
  6.         }  
  7.           
  8.         table {  
  9.             font-family: TimesNewRoman;  
  10.         }  
  11.           
  12.         input[type="text"] {  
  13.             background: white;  
  14.             border-color: lightgrey;  
  15.             size: 38;  
  16.         }  
  17.           
  18.         input[type="button"] {  
  19.             padding: 0.25em;  
  20.             margin: 0.25em;  
  21.             background: white;  
  22.             color: Black;  
  23.             border-color: black;  
  24.         }  
  25.     </style>  
  26. </head>  
  27.   
  28. <body>  
  29.     <table>  
  30.         <tr>  
  31.             <td>  
  32.                 <div>  
  33.                     <h2>Films Database</h2>  
  34.                     <table id="Film" cellpadding="2" cellspacing="2" border="1" width="400px">  
  35.                         <tr>  
  36.                             <td style="background-color: white; color: grey">Film ID</td>  
  37.                             <td style="background-color: white; color: grey">Film Name</td>  
  38.                             <td style="background-color: white; color: grey">Director</td>  
  39.                             <td style="background-color: white; color:grey">Year</td>  
  40.                         </tr>  
  41.                     </table>  
  42.                 </div>  
  43.                 </br>  
  44.                 <div>  
  45.                     <h2>Search by Film ID</h2>  
  46.                     <input type="text" size="5" id="FilmId" />  
  47.                     <input type="button" value="Search Film" onclick="find();" />  
  48.                     <p id="FilmSearch"></p>  
  49.                 </div>  
  50.             </td>  
  51.             <td>  
  52.                 </br>  
  53.                 </br>  
  54.                 </br>  
  55.                 </br>  
  56.                 </br>  
  57.             </td>  
  58.             <td>  
  59.                 <div>  
  60.                     <h2>Add/Update by Film ID</h2>  
  61.                     <table id="FilmUpdate" cellpadding="2" cellspacing="2" border="1" width="400px">  
  62.                         <tr>  
  63.                             <td style="background-color: white; color: grey">Film ID</td>  
  64.                             <td style="background-color: white; color: grey">Film Name</td>  
  65.                             <td style="background-color: white; color: grey">Director</td>  
  66.                             <td style="background-color: white; color:grey">Year</td>  
  67.                         </tr>  
  68.                         <tr>  
  69.                             <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmIdToUpdate" /></td>  
  70.                             <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmNameUpdated" /></td>  
  71.                             <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmDirectorUpdated" /></td>  
  72.                             <td style="background-color: white; color: grey"><input type="text" size="5" id="FilmYearUpdated" /></td>  
  73.                         </tr>  
  74.                         <tr>  
  75.                             <td><input type="button" value="Add Film" onclick="Add();" /></td>  
  76.                             <td><input type="button" value="Update Film" onclick="Update();" /></td>  
  77.                         </tr>  
  78.                     </table>  
  79.                 </div>  
  80.                 </br>  
  81.                 </br>  
  82.                 </br>  
  83.                 <div>  
  84.                     <h2>Delete by Film ID</h2>  
  85.                     <input type="text" size="5" id="FilmIdToDelete" />  
  86.                     <input type="button" value="Delete Film" onclick="Delete();" />  
  87.                 </div>  
  88.                 </br>  
  89.                 </br>  
  90.                 </br>  
  91.                 </br>  
  92.                 </br>  
  93.                 </br>  
  94.                 </br>  
  95.             </td>  
  96.         </tr>  
  97.     </table>  
  98.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>  
  99.     <script type="text/javascript">  
  100.         varuri = 'http://localhost:8082/api/films';  
  101.         $(document).ready(function() {  
  102.             GetFilmData();  
  103.         });  
  104.         functionGetFilmData() {  
  105.             $.getJSON(uri)  
  106.                 .done(function(data) {  
  107.                     $.each(data, function(key, item) {  
  108.                         $('#Film').append("<tr><td>" + item.id + "</td>" + "<td>" + item.FilmName + "</td>" + "<td>" + item.Director + "<td>" + item.Year + "</td></tr>");  
  109.                     });  
  110.                 });  
  111.             ClearText();  
  112.         }  
  113.         functionformatItem(item) {  
  114.             returnitem.FilmName + '-' + item.Director + '-' + item.Year;  
  115.         }  
  116.   
  117.         function find() {  
  118.             var id = $('#FilmId').val();  
  119.             $.getJSON(uri + '/' + id)  
  120.                 .done(function(data) {  
  121.                     $('#FilmSearch').text(formatItem(data));  
  122.                     ClearText();  
  123.                 })  
  124.                 .fail(function(jqXHR, textStatus, err) {  
  125.                     $('#Film').text('error' + err);  
  126.                 })  
  127.         }  
  128.   
  129.         function Delete() {  
  130.             var id = $('#FilmIdToDelete').val();  
  131.             varapiURL = 'http://localhost:8082/api/films/' + id;  
  132.             $.ajax({  
  133.                 url: apiURL,  
  134.                 type: 'DELETE',  
  135.                 dataType: 'json',  
  136.                 success: function(data, textStatus, xhr) {  
  137.                     alert("Film Name: " + data.FilmName + ", Director: " + data.Director + " . Record Deleted !");  
  138.                     $("#Film").find("tr:gt(0)").remove();  
  139.                     GetFilmData();  
  140.                 },  
  141.                 error: function(xhr, textStatus, errorThrown) {  
  142.                     alert("An error occurred!!");  
  143.                 }  
  144.             });  
  145.         }  
  146.   
  147.         function Add() {  
  148.             var id = $('#FilmIdToUpdate').val();  
  149.             varapiURL = 'http://localhost:8082/api/films/' + id;  
  150.             var film = new Object();  
  151.             film.id = $('#FilmIdToUpdate').val();  
  152.             film.FilmName = $('#FilmNameUpdated').val();  
  153.             film.Director = $('#FilmDirectorUpdated').val();  
  154.             film.Year = $('#FilmYearUpdated').val();  
  155.             $.ajax({  
  156.                 url: apiURL,  
  157.                 type: 'POST',  
  158.                 dataType: 'json',  
  159.                 data: film,  
  160.                 success: function(data, textStatus, xhr) {  
  161.                     alert("Film Record with ID : " + id + " Added !");  
  162.                     $("#Film").find("tr:gt(0)").remove();  
  163.                     GetFilmData();  
  164.                 },  
  165.                 error: function(xhr, textStatus, errorThrown) {  
  166.                     alert("An error occurred!!");  
  167.                 }  
  168.             });  
  169.         }  
  170.   
  171.         function Update() {  
  172.             var id = $('#FilmIdToUpdate').val();  
  173.             varapiURL = 'http://localhost:8082/api/films/' + id;  
  174.             var film = new Object();  
  175.             film.id = $('#FilmIdToUpdate').val();  
  176.             film.FilmName = $('#FilmNameUpdated').val();  
  177.             film.Director = $('#FilmDirectorUpdated').val();  
  178.             film.Year = $('#FilmYearUpdated').val();  
  179.             $.ajax({  
  180.                 url: apiURL,  
  181.                 type: 'PUT',  
  182.                 dataType: 'json',  
  183.                 data: film,  
  184.                 success: function(data, textStatus, xhr) {  
  185.                     alert("Film Record with ID : " + id + " Updated!");  
  186.                     $("#Film").find("tr:gt(0)").remove();  
  187.                     GetFilmData();  
  188.                 },  
  189.                 error: function(xhr, textStatus, errorThrown) {  
  190.                     alert("An error occurred!!");  
  191.                 }  
  192.             });  
  193.         }  
  194.         functionClearText() {  
  195.             $('#FilmIdToUpdate').val('');  
  196.             $('#FilmNameUpdated').val('');  
  197.             $('#FilmDirectorUpdated').val('');  
  198.             $('#FilmYearUpdated').val('');  
  199.             $('#FilmIdToDelete').val('');  
  200.             $('#FilmId').val('');  
  201.         }  
  202.     </script>  
  203. </body>  
  204.   
  205. </html>  
Add the Script to SharePoint

The entire script along with the applied style is available for download in this article with the name ‘SP2016WebAPI.txt’. Upload it to the SharePoint repository ‘Site Assets’. Copy the file path and assign it to the Content Link section of a Content Editor Web Part. Once done, click on Apply. We can see the CRUD web part available in the page.



Summary

Thus, we saw how to create and consume an MVC CRUD Web API from SharePoint Server 2016.