Web API Interface Design Experience Summary

Source: Internet
Author: User
Tags tojson

In the development of the Web API interface, we may encounter a variety of problems, I in the previous two essays "Web API application Architecture in the WinForm Hybrid Framework application (1)", "web Application of API application architecture in WinForm Hybrid Framework (2)--The processing of custom exception results is also introduced in general, after my large number of modules practice and successfully run, summed up this essay, I hope to help you.

1. Determine the Get or post mode of MVC in the interface definition

Since our entire Web API platform is based on the development of the API on the basis of MVC, the interface of the entire Web API, when defined, generally needs to be displayed to declare that the interface is [HttpGet] or [HttpPost], although some interfaces may not be declared, However, it is also advantageous to avoid the following error messages, which are explicitly declared.

The requested resource does not support the HTTP method "POST

For example, the Lookup object interface defined in the base class is shown below.

 /// <SUMMARY>  ///  Query the database for the existence of an object with the specified ID  /// Span style= "color: #808080;" ></summary>  /// <param name= " ID "  </PARAM>  Span style= "color: #808080;" >/// <RETURNS>   presence returns the specified object.        Otherwise returns null  </RETURNS>   [HttpGet]  public  virtual  T FindByID (string  ID, string  token) 

If the interface is added and deleted, it is generally necessary to declare the data for post, and for security reasons, more parameters need to be carried.

        /// <summary>        ///inserts the specified object into the database/// </summary>        /// <param name= "info" >the specified object</param>        /// <returns>whether the operation was successful. </returns>[HttpPost] Public VirtualCommonresult Insert (T info,stringTokenstringSignaturestringTimestampstringNoncestringAppID

2. Interface definition of dynamic object

In the General Web API interface, we may encounter many simple types of parameters, but also want them to post the data, then we can have two methods to deal with, one is to define a class to place these parameters, one is to use dynamic jobject parameters, The former has many inconvenient places because it is not possible to define more than one entity class for each interface parameter, so there may be many class definitions that are difficult to manage. As the following is the API invocation interface case, we also need to set such a processing rule.

Interface Call Request Description HTTP request mode: POST (use HTTPS protocol) https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_ Tokenpost data format: JSONPost Data example: {"group": {"id": 108, "name": "Test2_modify2"}}

So we're using jobject, so let's look at the definition of the interface and the processing code. Jobject is an object under the Newtonsoft.Json.Linq namespace.

        /// <summary>        ///Modify User Password/// </summary>        /// <param name= "param" >composite objects containing username and UserPassword</param>        /// <param name= "token" >User access token</param>        /// <returns></returns>[httppost] PublicCommonresult Modifypassword (jobject param,stringtoken) {            //token Check, throw exception if not passedCheckresult Checkresult =Checktoken (token);  dynamic obj = param; if(obj! =NULL)            {                stringUserName =Obj.username; stringUserPassword =Obj.userpassword; BOOLSuccess = Bllfactory<user>.                Instance.modifypassword (UserName, UserPassword); return NewCommonresult (Success); }            Else            {                Throw NewMyapiexception ("Pass parameter error occurred"); }        }

When we convert the Jobject object to the object we need, because we do not define a specific entity class, we use the dynamic syntax, which declares that this is a dynamically-based object that gets the corresponding property from the runtime.

dynamic obj = param;

This allows us to invoke the JSON object of the dynamic post to the Web API interface, without having to pre-define the classes of the various interface parameters.

        /// <summary>        ///call the Web API interface to modify the user password/// </summary>        /// <param name= "UserName" >User name</param>        /// <param name= "UserPassword" >Modified Password</param>        /// <returns>returns False if the modification successfully returns True</returns>         Public BOOLModifypassword (stringUserName,stringUserPassword) {            varAction ="Modifypassword"; varPostData =New{userName=UserName, UserPassword=UserPassword}.            ToJson (); stringURL =Gettokenurl (action); Commonresult result= jsonhelper<commonresult>.            Convertjson (URL, postdata); return(Result! =NULL) ? Result. Success:false; }

The Gettokenurl is to build a complete submission address based on parameters such as token and API address. We pass the code above

            var New             {                = userName,                = userpassword            }. ToJson ();

It is possible to create an object dynamically, generate its JSON string, submit the data post to the corresponding API interface, and then convert the object to the result, even if it is done.

3. Processing of collections and pagination

In many interfaces, we all need to use paging processing, WEB API is no exception, so that can submit data retrieval efficiency, reduce the pressure of server data processing, but also submit the client's data display speed.

The general set interface definition is as follows (universal base class interface).

        /// <summary>        ///returns a collection of all objects in the database/// </summary>        /// <returns>specifies the collection of objects</returns>[HttpGet] Public VirtualList<t> GetAll (stringtoken) {            //Check whether the user has permission or throw mydenyaccessexception exception            Base.            Checkauthorized (Authorizekey.listkey, token); List<T> list =Basebll.getall (); returnlist; }

However, such a return record will be more, in general, paging is required, then the processing interface of the paging is defined as follows.

        /// <summary>        /// Query the database based on criteria and return a collection of objects (for paging data        display) /// </summary>        /// <returns> specifies the collection of objects </returns>         [HttpPost]        publicvirtual pagedlist<t> Findwithpager (  Stringstring token)

Paging interface, in the results returned here, using a pagelist generic class, which facilitates us to get the current record and total, it is defined as follows.

    /// <summary>    ///Paging Collection/// </summary>    /// <typeparam name= "T" >Object</typeparam>     Public classPagedlist<t>    {        /// <summary>        ///returns the total number of records/// </summary>         Public intTotal_count {Get;Set; } /// <summary>        ///List Collection/// </summary>         PublicList<t> List {Get;Set; } }

Finally, the entire paging Processing Web API interface implementation is as follows.

        /// <summary>        ///Query the database based on criteria and return a collection of objects (for paging data display)/// </summary>        /// <returns>specifies the collection of objects</returns>[HttpPost] Public VirtualPagedlist<t> Findwithpager (stringCondition, Pagerinfo Pagerinfo,stringtoken) {            //Check whether the user has permission or throw mydenyaccessexception exception            Base.            Checkauthorized (Authorizekey.listkey, token); List<T> list =Basebll.findwithpager (condition, pagerinfo); //structure to JSON format delivery            varresult =NewPagedlist<t> () {total_count = Pagerinfo.recordcount, List =list}; returnresult; }

The Web API code for the last client call paging is shown below.

        /// <summary>        ///Query the database based on criteria and return a collection of objects (for paging data display)/// </summary>        /// <param name= "condition" >criteria for the query</param>        /// <param name= "Pagerinfo" >Paging Entities</param>        /// <returns>specifies the collection of objects</returns>         Public VirtualList<t> Findwithpager (stringConditionrefpagerinfo Pagerinfo) {            varAction ="Findwithpager"; stringurl = Gettokenurl (action) +string. Format ("&condition={0}", condition); varPostData =Pagerinfo.tojson (); List<T> result =NewList<t>(); Pagedlist<T> list = jsonhelper<pagedlist<t>>.            Convertjson (URL, postdata); if(List! =NULL) { pagerinfo.recordcount = list.total_count;//Total number of records modified result = list.list; }            returnresult; }

4. Integrated Web API interface for mixed frame interface

Throughout the platform building of the Web API and the integration of the hybrid framework, I have developed and integrated the modules in a relatively independent way, implementing a unified approach from direct access to the database, data acquisition in WCF services, and access to data through WEBAPI invocation. This enables a high degree of integration of the entire hybrid framework.

The core of the whole hybrid framework is to integrate the reusable modules in a relatively independent way, and we can quickly build a unified application platform on a certain basis.

The complete WEBAPI platform, which includes the server content, publishes the corresponding Web API interface in the way of API controller.

Within the standalone module of each hybrid framework, we encapsulate the corresponding Web API client invocation processing, which implements the invocation of the Web API.

Under WIN10, use the Web API mode to run the hybrid framework, and get the main interface effect as shown below.

The standalone module Rights Management System interface is shown below.

Web API Interface Design Experience Summary

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.