expression, from the simple beginning. Robin Williams: A design book for everyone to see 1.14.1 uniform return format
Obviously, by default, we chose JSON to return the interface results as a unified format. Here's a quick explanation for the reason to select the JSON uniform return: JSON is currently popular, and the normal interface returns JSON in this format, which is supported in most development languages, across languages
JSON is supported by visual plug-ins when browsing in the browser, such as under FF:
1.14.2 Unified return Structure
Normally, we normally request that the interface return a similar:
{
"ret": "
Data": {
"title": "Default Api",
"content": "Phper Hello, Welcome to use PHALAPI." ",
" version ":" 1.1.0 ",
" Time ": 1423142802
},
" MSG ":" "
}
Where the RET is represented as a return status code, 200 indicates success, data is the domain business data, is customized by the interface, and the last MSG is the wrong hint. explained separately below. (1) Return status code RET
Reference to the status code of HTTP, special convention: 200: interface normal request and return 4XX: Client illegal request 5XX: Server Run error 200 normal return
When you return 200, you need to return data at the same time so that the client can implement the required business functions. 4XX Client Illegal request
Such requests are caused by improper calls from the client, such as the requested interface service does not exist, or the interface parameters are incorrect, validation fails, and so on. When this happens, the client student only needs to adjust the correction call.
For the status code of this system, the project can customize the contract when developing the interface. Typically, we need to tell the client that the signature fails:
throw new Phalapi_exception_badrequest (' Wrong sign ', 1);
That is, throw the phalapi_exception_badrequest exception, the error message will return to the client, corresponding to the MSG field, the state is 1, the system for this class of exceptions will be added on the basis of 400, namely:401 = + 1 . 5XX Server Run error
Such errors should be avoided, but when the client discovers this, it should be known to the backend interface developer for corrections.
This type of exception is triggered when the configured parameter rule does not conform to the requirement, or if a nonexistent parameter is obtained, which is usually thrown by the frame. (2) Business data
Data for the interface and the client main communication docking of the section, can be any type, by the interface of the customization. However, for better expansion and backward compatibility, it is recommended that you use array. returns the definition and online view of the format
When we are developing an interface, we can define the return format of the interface by adding annotations to the interface, and then we can provide an external real-time view of the online documentation.
Such as:
<?php
class Api_user extends Phalapi_api {
/**
* Get user profile
* @desc used to get a single user basic information
* @return int code Operation code, 0 indicates success, 1 means user does not exist
* @return Object Info User information Objects
* @return int info.id User ID
* @return string info.name user name
* @return String info.note user Source
* @return string MSG message
/public
function Getbaseinfo () {
//..... ..
}
Then in the browser access:
Http://demo.phalapi.net/checkApiParams.php?service=User.getBaseInfo
You can see:
annotation Format
The format is indicated by a docs return comment, in the form of:
@return returned type field name path (concatenated by dots) field name and parsing
Where the returned type can be:
Key Words |
Description |
String |
String |
Int |
Integral type |
Float |
Floating-point type |
Boolean |
Boolean type |
Date |
Date |
Array |
Array |
Fixed |
Fixed value |
Enum |
Enum type |
Object |
Object |
Warm hint: The difference between array and object
An array is a set of arrays with no subscript, or a subscript but a continuous number of natural numbers, and each element has the same structure; object refers to a struct, similar to a dictionary.
In addition, in order to clarify the return format between the array and the object, we also recommend that if the element is from an array, the brackets are added after the returned field to remind the client that it needs to be recycled when receiving such a return. Such as:
* @return Array list user
@return int list[].id User ID
* @return string list[].name user name
* @return String list [].note User Source
When you need more information about an interface, you can use the @desc annotation, which is:
* @desc used to get basic information about a single user
(3) error message msg
When the return status code is not 200, this field is not empty. That is, when an exception is triggered, such as the client's illegal request and the server-side Run-time error, the exception's error message is automatically returned as the error message MSG.
However, for server-side exceptions, the framework is not overly specific when it comes to error messages because of the protection of interface privacy; Instead, for client exceptions, the necessary instructions are made to remind the client how to make the call adjustment.
In addition, we can consider the need for international translations as needed. It is helpful to prepare for translation in advance if the project needs to be deployed abroad within a predictable range. For example, you can return an exception error message at development time:
throw new Phalapi_exception_badrequest (T (' wrong sign '), 1);
1.14.3 about the reason exception class exception was not captured
We did not capture the exception of the exception class, the package returned in the form of non 200, because we consider the following: To facilitate the development process to quickly find and locate the specific error location; Secondly, in order to facilitate the online environment in the Nginx server to the wrong capture and record; 1.14.4 JSONP format and other returns
In the case of partial H5 of the page asynchronous request, the client needs us to return the results of the JSONP format, so you can re-register the response in the entry file:
if (!empty ($_get[' callback ')) {
DI ()->response = new Phalapi_response_jsonp ($_get[' callback ']);
However, in the test environment, we do not want to have content output, so we can test this registration response:
DI ()->response = ' phalapi_response_explorer ';
1.14.5 Extend your return format
When your project needs to return to other formats, such as returning XML, you can first implement your format class:
Class Myresponse_xml extends Phalapi_response {
protected function FormatResult ($result) {
//todo: put an array of $ Result format into XML ...
}
}
After that, it is also simple to re-register:
DI ()->response = ' myresponse_xml ';
1.14.6 The timing of each state code generation
1.14.7 better to suggest
Many times, many business scenarios, when the client completes an interface request and acquires the required data, requires different processing. In the case of a login, you may need to know whether the username does not exist when the login fails. Whether the password is incorrect. Whether it has been blocked by the system. Whether the number of password errors exceeds the maximum number of retries. ...
Obviously, there is also a return status code, more prepared to say, is the business Operation status Code. And, the state of this class is different depending on the interface, it is difficult to unify.
So.
We recommend that the project interface unify and redefine a status code in the business data, usually the Code field, and the full path is: data.code , while 0 means the operation succeeds, not 0 o'clock for different failure scenarios. As above login: Code = 0 Login Success Code = 1 Username does not exist code = 2 Password Error code = 3 System has blocked this account code = 4 Password errors More than the maximum number of retries ...
Finally, after obtaining the data returned by the interface, the client first unified to determine whether RET normal request and normal return, that is, ret = 200, if so, then each judge the operation status code is 0, if not 0, then prompts the corresponding copy and the corresponding guidance, if 0, then go normal flow. 1.14.8 Domain Specific design and Fiat standards
As mentioned in the RESTful Web APIs, standards can be grouped into 4 categories: Fiat standards, personal standards, corporate standards, and open standards.
Obviously, what we recommend here is the JSON + ret-data-msg return format is neither a personal standard nor a company standard (no company defined this format for the areas I observed). Moreover, it is not an open standard, because it has not yet reached this level. More, it is the Fiat standard.
It is easy to see that the applications, systems, and surrounding projects are all using the return structure format, such as some AJAX interfaces.
Of course, we can hope to eliminate the semantic divide in order to have a good consensus on background interface development.
At the same time, theJSON + ret-data-msg return format is a domain-specific format, and it is more of a specification for the app-multiport acquisition of business data. It's not perfect, it doesn't have self-describing messages, and it doesn't have the ability to link resources, but we think it's just the right format.
Based on the common format of JSON, it is ret-data-msg , it has a good uniformity, may be low threshold, easy to understand.
Interface Request Format
http://dev.phalapi.com/demo/?service=User.GetBaseInfo&user_id= account ID
//Return result format
{
" RET ":" "
data": {
"code": 0, //status code, 0 for normal access, 1 means that the user does not exist
"MSG": "",
"info": { //user information
ID ": 1",// User ID
"name": "Dogstar", //account
"Note": "Oschina" //Source
}
,
"MSG": ""
}