HTTP interface design and log Printing

Source: Internet
Author: User

In any relatively large project, the use of web interfaces is indispensable. Both C2S and s2s depend on HTTP interfaces. Next, let's make a summary of the various HTTP interfaces that have been written over the past one or two years.

It can be roughly divided into the following five points:

1. Use requestid to record tracing requests

2. Only receive JSON string requests in the body to avoid Encoding Problems.

3. Return the appropriate data structure

4. Print useful logs

5. Provide readable documents

First, use requestid to record tracing requests. If you do this, you will find out how useful the rule is when you locate the problem. The UUID can be forcibly used as the requestid in the request. The same UUID is carried when the server returns the request. Otherwise, you can generate a unique ID for each request. This method is described in the log at the fourth point.

Second, except the request data is very simple or the get method must be used in special cases, all requests should use the POST method whenever possible, and the request parameter should be a JSON string, in the requstbody, try not to place extra parameter information in Form-encoded. This not only effectively avoids encoding problems, but also corresponds to the JSON body returned by the interface.

Third, define the return status code, error information, and valid information when designing each API. In most cases, the http api should use JSON as the responsebody, which can correspond to the request and facilitate interface expansion. Below is my frequently used returned Data Structure: public class responseentry {

Private int code; // status code private string result; // description information private object data; // valid information public responseentry (INT code) {This. code = Code;} public responseentry (INT code, string result) {This. code = Code; this. result = result ;}

// Omit getter and setter
@ Override Public String tostring () {return "responseentry {" + "code =" + code + ", result = '" + Result +' \ ''+ ", data = "+ Data + '}';} Public String tojsonstring () {return JSON. tojsonstring (this );}}

The existence of Code allows the request client to determine the returned information more accurately and determine the result of the request. The responsecode design should also follow certain rules. For example, 200 usually indicates success, and 404 generally indicates not found. If you use springmvc for framework development, we can directly return the responseentry object in the interface, and automatically convert it into a JSON string and return it by configuring servlet-context. As follows:

@ResponseBody    @RequestMapping(value = "/communicate", method = RequestMethod.POST)    private ResponseEntry communicate(@RequestBody String jsonBody) {    /* code */      }
<mvc:annotation-driven>        <mvc:message-converters register-defaults="true">            <!-- fastjosn spring support -->            <bean id="jsonConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">                <property name="supportedMediaTypes">                    <list>                        <!--<value>application/json;charset=UTF-8</value>-->                        <value>text/html;charset=UTF-8</value>                    </list>                </property>            </bean>        </mvc:message-converters>    </mvc:annotation-driven>

Fastjson is used for conversion, or the default Jackson or other JSON processing method can be used.

Fourth, print useful logs. Print the necessary information in the interface to help you locate the problem. Usually the request and response content must be printed. Use requestid to indicate each response and the corresponding request. In the HTTP interface design, we can add a filter to print logs, so that every API does not have to print the input and output operations again. Code can be more concise. If there are too many codes here, you will not post them. Refer to the source code GitHub.

Fifth, after the interface is completed and tested, a readable interface document should be provided. This document not only helps others use your API, but also helps others write the document, you can review your code to ensure that there are no logical errors.

HTTP interface design and log Printing

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.