Consume Odata Endpoint From JavaScript Client

Introduction

 
In our previous article, we have discussed Odata, It's advantages, and how to expose Odata endpoints in the Web API. You can read them here. 
 
Expose Odata Endpoints Without Entity Framework and Performing CRUD
 
In this article, we will learn how to consume OData from a JavaScript client. I am planning to implement Odata in a Web API from scratch and we will consume Odata endpoints from the JavaScript client, it will help you to understand the fundamental concepts of Odata if you are very new in this field.
 
I will assume that you have a fundamental understanding of Odata and its uses and advantages. If not then the following quick introduction is for you.
 
OData stands for Open Data protocol that is proposed and introduced by Microsoft. Then it was adopted by the industry as an open and uniform platform to expose data to the outer world. So, it provides the idea of sharing and consuming data irrespective of platform and protocol.
 
You can get more information about Odata here.
 
As said, in this example we will implement Odata endpoints from scratch and for that we will use SqlServer and the Entity Framework.
 
First things first, create one Web API 2.0 application in the solution, in this example, I am using Visual Studio 2012. If you are using Visual Studio 2010 or lower then you need to have the MVC 4 template to get the Web API and need to update Web API application to Web API 2.0. Then install the Odata package from the NuGet Package Manager. Here is the package for reference.
 
/install Odata package from NuGet package manager
 
Web API 2.2 Odata is the core package and in this of package installation it will ask you to allow installation of its a dependent package. So please accept the prompt option and allow it to install its dependent packages.
 
Now, the application is Odata compatible and we are allowed to expose Odata endpoints from applications.
 
Here is our sample table that we will use to expose Odata endpoints.
 
 
Now, add an Entity Framework to generate a model from the database. Here is the model in my sample application. To add Entity Framework, please refer to any good tutorial if you are very new to Entity Framework.
 
Entity Framework
 
Fine, we will now add a controller and a few lines of code within the controller. Here is a sample controller to expose OData.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Data;    
  4. using System.Data.Entity;    
  5. using System.Data.Entity.Infrastructure;    
  6. using System.Linq;    
  7. using System.Net;    
  8. using System.Net.Http;    
  9. using System.Web.Http;    
  10. using System.Web.Http.ModelBinding;    
  11. using System.Web.Http.OData;    
  12. using System.Web.Http.OData.Routing;    
  13. using OdataAPI;    
  14. using OdataAPI.Models;    
  15.     
  16. namespace OdataAPI.Controllers    
  17. {    
  18.     public class userController : ODataController    
  19.     {    
  20.         private ApiSecurityEntities db = new ApiSecurityEntities();    
  21.             
  22.         [Queryable]    
  23.         public IQueryable<UserMaser> GetUser()    
  24.         {    
  25.               return db.UserMaser;    
  26.         }    
  27.     
  28.         [Queryable]    
  29.         public IQueryable<UserMaser> GetUserById([FromODataUri] int key)    
  30.         {    
  31.             return db.UserMaser.Where(um => um.id == key);    
  32.         }    
  33.     
  34.     }    
  35. }   
Now, let's discuss the controller a little bit. First of all the controller is inherited from the ODataControler class, not like from a Controler of an ApiController class. So, OdataController is the base class of a “user” controller. Then we implemented two methods/actions and both actions are decorated by the Queryable attribute; it will ensure that both actions will available as Odata endpoints.
 
The first action will return data as a query of the Odata standard and the second function is ready to return a single Entity of the UserMaster class by taking Id as an argument.
Ok, we have finished our controller implementation, now the next task is to register the Odata controller in the route so that when someone will try to point the Odata controller, the request will hot in the appropriate controller.
 
To register the Odata route just open the WebApiConfig.cs file of the application and modify it accordingly.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web.Http;    
  5. using System.Web.Http.OData.Builder;    
  6. using Microsoft.Data.Edm;    
  7. using OdataAPI.Models;    
  8.     
  9. namespace OdataAPI    
  10. {    
  11.     public static class WebApiConfig    
  12.     {    
  13.         private static IEdmModel GenerateEdmModel()    
  14.         {    
  15.             var builder = new ODataConventionModelBuilder();    
  16.             builder.EntitySet<UserMaser>("user");    
  17.             return builder.GetEdmModel();    
  18.         }    
  19.         public static void Register(HttpConfiguration config)    
  20.         {    
  21.             // Web API routes    
  22.             config.MapHttpAttributeRoutes();    
  23.     
  24.             config.EnableQuerySupport();    
  25.             config.Routes.MapODataRoute("odata""odata", GenerateEdmModel());    
  26.     
  27.             config.Routes.MapHttpRoute(    
  28.                 name: "DefaultApi",    
  29.                 routeTemplate: "api/{controller}/{id}",    
  30.                 defaults: new { id = RouteParameter.Optional }    
  31.             );    
  32.         }    
  33.     }    
  34. }   
Now, the Odata endpoint is registered to the routing engine and all the configurations have been done in the server and now we can host out application and test the application using Fiddler as the client to ensure that everything is working correctly and from the JavaScript client we can access it.
 
If we hit the following URL then we should get all the data from the UserMaster table that we are getting in Fiddler.
 
fiddler
 
http://localhost:10020/odata/user
 
Ok, everything is fine, now let's create one ajax() function of jQuery to call the Odata endpoint. Have a look at the following example.
  1. <script>    
  2.     $(document).ready(function () {    
  3.         $.ajax({    
  4.             type: "GET",    
  5.             url: "http://localhost:10020/odata/user?$top=1",    
  6.             contentType: "application/json; charset=utf-8",    
  7.             dataType: "json",    
  8.             success: function (response) {    
  9.                 alert(JSON.stringify(response));    
  10.             },    
  11.             failure: function (response) {    
  12.                 alert(response.d);    
  13.             }    
  14.         });    
  15.     });    
  16.     
  17.  </script>   
This piece of code will work as an Odata client and consume data from Odata endpoints. In the success callback function, we are printing a value.
 
callback function
 
We are firing an Odata query to the Odata endpoint as in the following.
 
http://localhost:10020/odata/user?$top=1
 
We are getting only one record, it's the top 1 record from the table. If you are interested then you are allowed to fire any odata parameter in this endpoint.
 

Conclusion

 
We have now learned how to implement an Odata endpoint and consume it from a JavaScript client. I hope this article will help you to understand the concept of Odata in the Web API.