Blue Flower

What is OData?

OData is Open Data Protocol, it is a REST-based protocol for querying and updating data

What is the use of OData?

One can fulfill many requirements without creating different endpoints, that’s the Power of OData

How can we implement it in one REST API? ex: in .NET core REST API?

Step 1 : Install ‘Microsoft.AspNetCore.OData’ NuGet Package in your existing application
Step 2: Add services.AddOData() under ConfigureServices Method in startup.cs file. 

            public void ConfigureServices(IServiceCollection services)
            {
              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
              services.AddDbContext<ProductContext>(o => o.UseSqlServer(Configuration.GetConnectionString("ProductDB")));
              services.AddTransient<IProductRepository, ProductRepository>();
              services.AddOData(); //this line of code will make your application understand what OData is.
            }
Step 3 : Add Dependency Injection & query functionalities

              app.UseMvc(routeBuilder => {
                routeBuilder.EnableDependencyInjection(); //enable existing endpoint with power of OData.
                routeBuilder.Expand().Select().OrderBy().Filter(); //Add query functionalities in UseMvc method, add those functionalities which you want to                                                                                                enable for endpoints.
             });
Step 4: provide the ‘query power of OData’ to endpoint by adding annotation of [EnableQuery()] on top of your controller method.

            [HttpGet]
            [Microsoft.AspNet.OData.EnableQuery]
            public IActionResult GetAllProducts()
           {
              var product = _productRepository.GetProducts();
              return new OkObjectResult(product);
           }

Done it !! lets see how OData RESTful APIs can be consumed

How can we consume above implemented OData based REST API?

1) select only name field
    http://localhost:59582/api/Product?$select=name
2) filter id = 1 or 3 with all field
     http://localhost:59582/api/Product?$filter=(id eq 1) or (id eq 3)

3) filter records where id is 1 or 2 and order by 'name' property

     http://localhost:59582/api/Product?$filter=((id eq 1) or (id eq 2))&$orderby=name
     http://localhost:59582/api/Product?$orderby=name& $filter=((id eq 1) or (id eq 2))
4) can specify type of output (to be check)
     http://localhost:59582/api/Product?$orderby=name& $filter=((id eq 1) or (id eq 2))&$format=text

You have no rights to post comments