API Interface Development Brief

Source: Internet
Author: User

As the most popular service-side language PHP (Php:hypertext preprocessor), in the development of the API, it is very simple and very advantageous. API (Application programming Interface, Application Interface) architecture, has become a common software architecture model in Internet product development, and a number of specialized API service companies, such as: aggregated data (https:// www.juhe.cn/), Baidu Apistore (http://apistore.baidu.com/)

First understand the following API:
1, the API is more concise than the development of the WEB, but may be more complex logic, the API only returns the results, that is, only the data output, not rendering the page,
2, WEB Development, more is GET and POST request, API also has PUT, DELETE request
3, and WEB development, the first need some relevant parameters, these parameters, will be sent by the client, perhaps a GET or POST, this requires the development team to agree with each other, or to develop a unified specification
4, with the parameters, according to the application needs, complete data processing, such as: access to user information, send a friend circle, send messages, a game end data submission and so on
5, after the data logic processing, return the client needs to use the relevant data, such as: User information array, friend circle list, message status, game results data, and so on, how the data is returned to the client? It is common to have XML, JSON, set the appropriate header and print the data to be returned directly.
6. After the client obtains the data you return, it interacts with the user locally and on the client.

So we probably know that the API does not actually exist in the web domain MVC schema pattern, to layered, the API is only M and C two layer, of course, the backend may have more complex architecture!

Understand how PHP develops the API by using an API instance of the following HTTP protocol:

<?php/*** Compare standard interface output function * @param string $info message * @param integer $code interface error code, key parameter * @param array $data additional data * $param St Ring $location REDIRECT * @return array*/function Var_json ($info = ", $code = 10000, $data = Array (), $location =") {$ou    t[' Code ' = $code?: 0; $out [' info '] = $info?: ($out [' Code ']?    ' ERROR ': ' Success ');    $out [' data '] = $data?: Array ();    $out [' location '] = $location;    Header (' Content-type:application/json; Charset=utf-8 ');    Echo Json_encode ($out, Json_hex_tag); Exit (0);} $a = empty ($_get[' a '])? ": $_get[' a ']; $qq = empty ($_get[' QQ ')? 0:intval ($_get[' QQ '));//Assume this is a data source, such as Mysql$data = Array (); $data [979136] = array (' QQ ' =>979136, ' VIP ' =>5, ' level ' = >128, ' reg_time ' =>1376523234, ' QB ' =>300); $data [979137] = array (' QQ ' =>979137, ' VIP ' =>8, ' level ' = 101, ' Reg_time ' =>1377123144, ' QB ' =>300);p reg_match ('/^[a-za-z]+$/', $a) | | Var_json (' illegal invocation '); Isset ($data [$qq]) | | Var_json (' User not present ', 100001); switch ($a) {//Get user basic information case ' info ':        Your more business logic ... var_json (' success ', 0, $data [$qq]);    Break        Get the dynamic message case ' message ': Var_json (' You are invoking the dynamic message interface ', 0);    Break        Get buddy list case ' friends ': Var_json (' You are calling buddy list interface ', 0);    Break Default:var_json (' illegal invocation ');}

The interface output example returns a string of JSON:

{        "code": 0,        "info": "Success",        "data": {                "QQ": 979137,                "VIP": 8, "Level                ": 101,                "Reg_ Time ": 1377123144,                " QB ":" * "        ,        " location ":"}

JSON has a strong cross-platform, and almost every language has a function to parse the JSON, here is an example of PHP as a client call:

<?phpheader (' Content-type:text/html;charset=utf-8 '); $url = "Http://demo.979137.com/api/test/user.php?a=info &qq=979137 "; $arg = Array (    ' a ' = =  ' info ',    ' qq ' = ' 979137 '); $query _string = Http_build_query ($ ARG); $ch = Curl_init ($url. '? '). $query _string); curl_setopt ($ch, curlopt_http_version, curl_http_version_1_1); curl_setopt ($ch, Curlopt_useragent, ' qq_mobile_v5.5 '), curl_setopt ($ch, Curlopt_connecttimeout, curl_setopt ($ch, Curlopt_timeout,); curl_setopt ($ CH, curlopt_returntransfer, True); curl_setopt ($ch, curlopt_followlocation, true); $response = Curl_exec ($ch); $ Httpcode = Curl_getinfo ($ch, Curlinfo_http_code), Curl_close ($ch), if ($response = = = False) {    Var_dump (Curl_error ($ CH));} ElseIf ($httpcode! =) {    var_dump ($httpcode, ' interface request failed ');} else {    $ret = Json_decode ($response, true);    Var_dump ($ret);}

Page Output results:

Array (4) {    ["code"]=>int (0)    ["Info"]=>string (7) "Success"    ["Data"]=>    Array (5) {        ["QQ "]=>int (979137)        [" VIP "]=>int (8)        [" Level "]=>int (101)        [" Reg_time "]=>int (1377123144)        ["QB"]=>int (+)    }    ["Location"]=>string (0) "}

A few points that we should be aware of when developing the API in the actual project (for reference only)

1, single-file implementation of multiple interfaces in a variety of forms, such as: If. ElseIf. or switch or many of the unified portals used in the framework are implemented by invoking a class function
2, the data output is recommended to use Json,json has a strong cross-platform, most programming languages support JSON parsing, JSON is gradually replacing XML, become a common format for network data
3, in order to ensure the security of the interface, we must join the authentication system
4, for the API on the line, be sure to turn off all error display, you can write the error in the log, PHP, can be blocked by error_reporting (0) all errors
The purpose of this is to secure the interface to prevent output of error messages that should not be printed
On the other hand is to ensure that the output is the correct data format, such as JSON, if not the standard JSON format, the client will be parsing error, thus affecting the normal operation of the client
PS: We usually use the mobile app, the hand of the opportunity to flash back, most of the reason, that is, the interface call exception
5, the development of the API and the web has a certain difference, if it is the Web, if the program is written with a problem, such as a notice or warning level of error, the web may not have any problems, perhaps just cause a part of the web is misplaced or garbled. But if it is the API, it will seriously call the client, if it is the mobile app, that flash what is inevitable, if it is also a web call, may also appear Server Error
6, we must focus on stability and response speed, because we use the mobile app, do not want the app often flash, and want to apply very smooth
7, do not casually use some of the PHP open source framework, the reason is summed up with two points:
1) as described in 6, the client generally to the API response speed is very high, the current PHP field of open-source framework is very much, according to the author's understanding, the current more popular framework, generally do more heavy, and basic is for the web, so, the framework of a lot of API can not use something, The framework is actually consuming your performance when loading and executing redundant files
2) as described in 4 and 5, the framework is a very happy thing for web development, but for the API, you can't imagine what it's going to do to you, because many frameworks don't fully consider the API scenario

API Interface Development Brief

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.