Create a rest API yourself

Source: Internet
Author: User
2015.10 Junior Top-to-Web computing course

In the junior course, Mr. Haitao asked the project to use rest for data collection. My eyes are crazy, what is rest? Then went to the Internet to find study materials. Then start writing a rest API yourself. Why do you write it yourself? Because I do not use the framework, the first time using PHP to do the site, I want to lay a good foundation to consider high-level things, there is no framework. PHP frameworks such as Laravel, which are used by others, themselves carry a rest mechanism. For me a useless frame of the child, can only write silently.

Of course, there are reference examples Oh http://www.gen-x-design.com/archives/create-a-rest-api-with-php/, but this example is not comprehensive, I add a lot of myself.

 Setmethod ($request _method); Set the raw data, so we can access it if needed (there is//other pieces to your requests) $return _o            Bj->setrequestvars ($data); if (Isset ($data [' data ')]) {//Translate the JSON to a Object for use however you want $retur        N_obj->setdata (Json_decode ($data [' data ')]);    } return $return _obj; }public static function Sendresponse ($status = $, $body = ", $content _type = ' text/html ') {$status _heade r = ' http/1.1 '. $status. ' ' .          Restutils::getstatuscodemessage ($status);          Set the status header ($status _header);            Set the content Type header (' Content-type: '. $content _type);              Pages with body is easy if ($body! = ") {//Send the body echo $body;          Exit       }//We need to create the body if none is passed else {       Create some body messages $message = ';  This is purely optional, but makes the pages a little nicer to read//for your users. Since won ' t likely send a lot of the different status codes,//This also shouldn ' t is too ponderous to maint Ain Switch ($status) {case 401: $message = ' must is AU                      thorized to view this page.                  Break Case 404: $message = ' The requested URL '. $_server[' Request_uri '.                      ' is not found. ';                  Break                      Case A: $message = ' The server encountered an error processing your request. ';                  Break                      Case 501: $message = ' The requested method was not implemented. ';              Break }//Servers don ' t always has a signature turned on (This is a Apache directive "serversignature on") $signature = ($_server[' server_signature '] = = ")? $_server[' Server_software '. ' Server at '. $_server[' server_name '. ' Port '.                $_server[' server_port ': $_server[' server_signature ']; This should is templatized in a real-world solution $body = '                                                                                          
 
  
                                   <title>' . $status. ' ' . Restutils::getstatuscodemessage ($status). '</title>                                                                                              

' . Restutils::getstatuscodemessage ($status). '

' . $message. '

' . $signature. ' '; Echo $body; Exit }} public static function Getstatuscodemessage ($status) {//These could is stored in a. ini file and Loaded/via Parse_ini_file () However, this would suffice//for a example $codes = Array ( ' Continue ', 101 = ' Switching Protocols ', ' OK ', 201 = ' C Reated ', 202 = ' Accepted ', 203 = ' non-authoritative information ', 204 = ' No C Ontent ', 205 = ' Reset content ', 206 = ' Partial content ', ' multiple Choi ' Ces ', 301 = ' Moved permanently ', 302 = ' Found ', 303 = ' See other ', 304 = ' Not Modified ', 305 = ' Use Proxy ', 306 = ' (Unused) ', 307 = ' Tempor ary Redirect ', ' Bad Request ', 401 = ' Unauthorized ', 402 = ' Payment Required ', 403 = ' Forbidden ', 404 = ' not Found ', 40 5 = ' Method not allowed ', 406 = ' not acceptable ', 407 = ' Proxy authentication Required ', 408 = ' Request Timeout ', 409 = ' Conflict ', 410 = ' Gone ', 411 =&GT ; ' Length Required ', 412 = ' precondition Failed ', 413 = ' Request Entity Too Large ', 414 = ' Request-uri Too Long ', 415 = ' Unsupported Media Type ', 416 = ' Requested Range No T satisfiable ', 417 = ' expectation Failed ', ' Internal Server Error ', 501 =& Gt ' Not implemented ', 502 = ' bad Gateway ', 503 = ' Service unavailable ', 504 = ' G Ateway Timeout ', 505 = ' HTTP Version not supported '); Return (Isset ($codes [$status])? $codes [$status]: '; }}class restrequest{private $request _vars; Private $data; Private $http _accept; Private $method; Public Function __construct () {$this->request_vars = array (); $this->data = "; $this->http_accept = (Strpos ($_server[' http_accept '), ' json ')? ' JSON ': ' XML '; $this->method = ' get '; The Public Function SetData ($data) {$this->data = $data; The Public Function Setmethod ($method) {$this->method = $method; The Public Function setrequestvars ($request _vars) {$this->request_vars = $request _vars; } public Function GetData () {return $this->data; } public Function GetMethod () {return $this->method; } public Function gethttpaccept () {return $this->http_accept; } public Function Getrequestvars () {return $this->request_vars; }} $data = Restutils::p rocesSrequest (); switch ($data->getmethod ()) {case ' get '://Print_r ($data->getrequestvars ()); $infoType = $data->getrequestvars () [' InfoType ']; if (array_key_exists ("username", $data->getrequestvars ())) {$username = $data->getrequestvars () [' username '] ; if ($data->gethttpaccept () = = ' json ') {if ($infoType = = "Health") {$healthService =new He Althservice (); $result = $healthService->getuserhealth ($username); if ($result = = "") {Restutils::sendresponse (404, "not Found"); } else{Restutils::sendresponse ($, Json_encode ($result), ' Application/json ') ; }}}} else if ($data->gethttpaccept () = = ' xml ') {if ($inf otype== "Health") {$healthService =new healthservice (); $result= $healthService->getuserhealth ($username); if ($result = = "") {Restutils::sendresponse (404, "not FOUND"); } else{$health =new healthxml (); Restutils::sendresponse ($health->create_xml ($result), ' application/xml '); }}}} break; Case ' post ': $infoType = $data->getrequestvars () [' InfoType ']; if ($infoType = = "Health") {$username = $data->getrequestvars () [' username ']; $height = $data->getrequestvars () [' Height ']; $weight = $data->getrequestvars () [' Weight ']; $date = $data->getrequestvars () [' Date ']; $healthService =new HealthService (); $ID = $healthService->addhealthwithdate ($username, $height, $weight, $date); $health =new healthxml (); $data _array = Array (Array ( ' ID ' = $ID,)); Restutils::sendresponse (201, $health->create_idxml ($data _array)); } break; Case ' put '://Print_r ($data->getrequestvars ()); $infoType = $data->getrequestvars () [' InfoType ']; Echo $infoType; echo $infoType = = "Health"? " True ":" false "; if ($infoType = = "Health") {$ID = $data->getrequestvars () [' ID ']; $username = $data->getrequestvars () [' username ']; $height = $data->getrequestvars () [' Height ']; $weight = $data->getrequestvars () [' Weight ']; $date = $data->getrequestvars () [' Date ']; $healthService =new HealthService (); $result = $healthService->modifyhealthwithdate ($ID, $username, $height, $weight, $date); if ($result = = "false") {Restutils::sendresponse ("bad Request"); } else{$health =new healthxML (); Restutils::sendresponse ($health->create_xml ($result), ' application/xml '); }} break; Case ' Delete ': $infoType = $data->getrequestvars () [' InfoType ']; if ($infoType = = "Health") {$ID = $data->getrequestvars () [' ID ']; $healthService =new HealthService (); $result = $healthService->deletehealth ($ID); if ($result ==false) {restutils::sendresponse (404, "not Found"); } else{Restutils::sendresponse (204, "No Content"); }} break; }class healthxml{//Create XML single function Create_item ($ID _data, $username _data, $height _data, $weight _data, $dateTim E_data) {$item = " \ n "; $item. = " ". $ID _data. " \ n"; $item. = " ". $username _data. " \ n"; $item. = " ". $height _data. " \ n"; $item. = " ". $weight _data. " \ n"; $item. = " ". $dateTime _data. " \ n"; $item. = " \ n "; return $item; } function Create_xml ($data _array) {$title _size = 1; $xml = " \ n "; $xml. = "\ n"; foreach ($data _array as $data) {$xml. = $this->create_item ($data [' ID '], $data [' username '], $data [' Height '], $data [' weight '], $data [' dateTime ']; } $xml. = "\ n "; return $xml; }//Create XML single function Create_iditem ($ID _data) {$item = " \ n "; $item. = " ". $ID _data. " \ n"; $item. = " \ n "; return $item; } function Create_idxml ($data _array) {$title _size = 1; $xml = " \ n "; $xml. = "\ n"; foreach ($data _array as $data) {$xml. = $this->create_iditem ($data [' ID ']); } $xml. = "\ n "; return $xml; }}?>

The difficulty is the parsing of the HTTP request header really makes me vomit blood ah, at that time I did not know that Chrome can look at the request content, my practice is crude output to see. After the analysis of the wild fill a regular expression, and finally with the regular smooth analysis.

I can not use the API directly, there are my website analysis of health data examples, you can also see that the second half of the large number of "health", is my site of the example of access to healthy data ah.

Because time is urgent, so only use half a day to write out of the API, probably is also shabby and have a lot of shortcomings bar. But the thought of this project final check when so many students did not implement rest, and I did not use the framework to learn rest, to achieve a own API, but also very happy.

The above describes your own creation of a rest API, including aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • 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.