An initial understanding of OData

Source: Internet
Author: User

What is What–odata?

Odata-open Data Protocal is a standard for designing and using restful APIs. Rest itself is just a thought and idea for building Web services, and it does not provide a unified standard to limit how developers can design restful APIs. In fact, our actual development did not follow a unified standard to design WEBAPI. Because in most scenarios, it is not necessary to follow a unified standard. But in some scenarios, there is a standard that can bring great benefits.

The ideal for OData is that no matter which organization builds a restful API, as long as it complies with the OData standard. Other organizations can use this API to obtain/modify resources in the manner defined in the OData standard. This can be analogous to the SQL standard for RDBMS relationships. No matter what the relational database, if it claims to support the SQL standard, anyone can query the data using standard SQL query statements.

Another benefit of normalization: The OData protocol can be implemented into a common class library, and the use of this class library to create and access restful APIs can reduce the workload for developers. There are many such components on the official website.

Who – who released OData?

The standard was initiated by Microsoft and the first three versions 1.0, 2.0 and 3.0 were Microsoft open standards.

When – When did you become an industry standard?

Fourth version 4.0 voted in Oasis on March 17, 2014 to become an open industry standard

why– Why do I need OData?

OData is a protocol, a standard. So the question is the same as why we need an agreement. The analogy TCP protocol can be understood in general. Suppose you develop a component that must communicate with a third-party component, and if a third-party component does not support TCP and only supports a private protocol that is developed internally, you must be a big boss, and you have to implement this private protocol separately for it in your component. If we all support the TCP protocol, it is not easy. This is the role of standard protocols: protocols and standards are used to develop a uniform and common rule. We only need to produce components in accordance with this Protocol or standard, so this component can be easily integrated/collaborated with other components. You do not need to customize components based on the private standards of other components.

As mentioned earlier, rest is just a thought of designing web services, not a standardized protocol. The lack of standardization has led to a lack of uniformity in the common use of restful APIs published by various companies. OData is the standard protocol that has been proposed to compensate for this lack.

The following is all extended reading can be skipped.

There are two ways to implement Web services, one is the SOAP protocol, and the other is the rest mode. Soap is a complete set of solutions for implementing Web services. There is a need for a simple understanding of the SOAP-style Web service, and then a comparison of soap patterns, and we'll find out what the rest approach lacks.

The Web Service Description Language (WSDL) and Simple Object Access Protocol (SOAP) in a SOAP-style Web service together form the structure unit of a Web service in SOAP mode. The client uses WSDL to understand that the Web service exposes the methods that can be executed and the message formats that the Web service can send or receive (addressing the issue of publishing access to resource methods). The client serializes the information required by SOAP to invoke the service that is located on the remote system as a message (resolves the issue of how to invoke a remote method). Note that WSDL describes the service as well as the SOAP messages that are consistent with the unified standard and are machine-readable.

WSDL is based on the XML format used to describe Web services. The WSDL document can be seen as a compact between the client and the server. Using the WSDL tool, you can automate this process and make it possible for applications to integrate new services with little or no manual coding. Therefore, WSDL is the foundation of the Web services architecture because it provides a common language for describing services and the platforms that integrate them.

SOAP itself provides a way to exchange information with a Web service. SOAP is a standard way to serialize the information required to invoke a service on a remote system, which can be sent over the network to a remote system using a format that can be read by a remote system, without having to worry about which platform the remote system is running on or in what language. SOAP provides a simple, lightweight mechanism for exchanging structured and type information in a decentralized or distributed environment, in XML format. In fact, it defines a simple mechanism for representing application semantics by providing a package model with standard components and a mechanism for encoding data in the module.

Compared to a SOAP-style Web service, there is no WSDL-like stuff in rest that describes a list of resources (services) and resource metadata. So someone in 2009 proposed a standard WADL to describe a restful web service, but so far it has not been standardized. The personal view that using WSDL/WADL to describe restful Web services is awkward, a typical RPC idea, while rest is an architectural thought that abstracts services into resources. It is not appropriate to use the WSDL described in RPC to describe a restful web service. We need other strategies instead of WSDL to implement the issue of "publishing access to resource methods".

Since there is no authoritative protocol like SOAP as a specification, the rest implementations of each Web site have their own set, and it is precisely because of this individual implementation that the performance and availability of the SOAP-published Web service is much higher, but there are too many areas of detail that are not constrained. Its unified common aspect is far less than soap.

For example, suppose a organization, b organizations have implemented RESTful APIs to query staff information through work numbers, because there is no uniform specification.

The API for a may be:http://A/api/person/001

The API for B may be:http://A/api/person/id=001

Third-party clients must consider the differences in these APIs when implementing a remote invocation, viewing the API documentation of A/b, respectively.

If there is an authoritative protocol to guide the specification, the API should be implemented as follows, then the third-party client only need to follow this standard to invoke the remote API, instead of looking at the API documentation of A/b:

HTTP://A/API/PERSON/{001}

This is explained in order to elicit that OData is such an authoritative protocol for designing and using restful APIs. OData defines some standard rules (like an interface defines a bunch of methods), and when implementing a restful API, these Standard rules must be implemented (just like implementing an interface must implement all of its methods). Third parties can access the restful API according to the rules defined by the OData protocol.

where– What scenarios can you consider using OData?

Not that all restful APIs you create need to conform to the OData protocol. It is only necessary to design restful APIs in accordance with the OData protocol when Open data is needed (open to other organizations). The Open data here refers to the use of information to third parties, and you do not know who the third party is. For example, Blog Park RSS, who subscribed to the RSS, blog Park is unclear. If your data is only used by clients in your own company, OData is an option and you have every reason not to design restful APIs in accordance with the OData specification.

how– How do I use OData?

First look at how easy it is for a C # client to invoke WEBAPI that conforms to the OData standard (http://www.odata.org/also has a JS class library on the website).

The first step is to install OData Client for with NuGet. NET package.

Second step, install the VS plugin: OData v4 Client Code Generator.

Step three: Suppose there is an available webapi (how to create it later)-Http://localhost:33189/Odata. We modify the Metadatadocumenturi in the code template as follows and then save. T4 accesses http://localhost:33189/Odata to obtain the metadata for the resource, and then generates the C # class corresponding to the resource based on the metadata. What T4 can do is because WEBAPI is publishing metadata for resource lists and resources according to OData standards.

Fourth step: In our code we can manipulate the CLR object to consume the remote WEBAPI. Experience the power of the OData standard.

Next look at how the C # server implements the OData Webapi that the client needs to invoke above, in two ways, a little bit different.

The first step: Create an empty WEBAPI project.

Step two: Introduce EF6 and WEBAPI 2.2 for OData v4.0 through NuGet. Such as.

Step three: Create the entity and DbContext classes, and configure the database connection. And through the Enable migration to complete the creation of the database, you can add some initialization data in the configuration seed method.

Fourth step: Configure Webapiconfig as follows

Fifth Step: Create ProductsController

usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingSystem.Web.Http;usingSystem.Web.Http.ModelBinding;usingOdataapi.models;usingSystem.Web.OData;namespaceodataapi.controllers{/*to add a route for this controller, merge these statements into the Register method of the Webapiconfig class.    Note that OData URLs is case sensitive.    Using System.Web.Http.OData.Builder;    Using Odataapi.models;    Odataconventionmodelbuilder builder = new Odataconventionmodelbuilder (); Builder.    Entityset<product> ("Products"); Config. Routes.mapodataroute ("OData", "OData", builder.)    Getedmmodel ()); */     Public classProductscontroller:odatacontroller {PrivateOdataapicontext db =NewOdataapicontext (); //GET odata/products//[queryable][Enablequery] PublicIqueryable<product>getproducts () {returndb.        Products; }        //GET odata/products (5)//[queryable][Enablequery] PublicSingleresult<product> getproduct ([Fromodatauri]intkey) {            returnSingleresult.create (db. Products.where (Product = Product.id = =key)); }        //PUT odata/products (5)         Public AsyncTask<ihttpactionresult> Put ([Fromodatauri]intkey, product product) {            if(!modelstate.isvalid) {returnbadrequest (modelstate); }            if(Key! =product.id) {                returnbadrequest (); } db. Entry (product). State=entitystate.modified; Try            {                awaitdb.            Savechangesasync (); }            Catch(dbupdateconcurrencyexception) {if(!productexists (Key)) {                    returnNotFound (); }                Else                {                    Throw; }            }            returnUpdated (product); }        //POST odata/products         Public AsyncTask<ihttpactionresult>Post (product product) {if(!modelstate.isvalid) {returnbadrequest (modelstate); } db.            Products.add (product); awaitdb.            Savechangesasync (); returnCreated (product); }        //PATCH odata/products (5)[Acceptverbs ("PATCH","MERGE")]         Public AsyncTask<ihttpactionresult> Patch ([Fromodatauri]intKey, delta<product>patch) {            if(!modelstate.isvalid) {returnbadrequest (modelstate); } Product Product=awaitdb.            Products.findasync (key); if(Product = =NULL)            {                returnNotFound (); } patch.            Patch (product); Try            {                awaitdb.            Savechangesasync (); }            Catch(dbupdateconcurrencyexception) {if(!productexists (Key)) {                    returnNotFound (); }                Else                {                    Throw; }            }            returnUpdated (product); }        //DELETE odata/products (5)         Public AsyncTask<ihttpactionresult> Delete ([Fromodatauri]intkey) {Product Product=awaitdb.            Products.findasync (key); if(Product = =NULL)            {                returnNotFound (); } db.            Products.remove (product); awaitdb.            Savechangesasync (); returnStatusCode (httpstatuscode.nocontent); }        protected Override voidDispose (BOOLdisposing) {            if(disposing) {db.            Dispose (); }            Base.        Dispose (disposing); }        Private BOOLProductexists (intkey) {            returnDb. Products.count (E = e.id = = key) >0; }    }}
View Code

Sixth step: F5 run, then the client can call. You can see what resource list and metadata look like by visiting the http://localhost:#/OData/and http://localhost:#/OData/$metadata.

In addition, we can create Webapicontroller with the OData controller template for VS (below).

An initial understanding of OData

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.