REST API示例「终于解决」

REST API示例「终于解决」如果你现在正使用iphone、Android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTfulAPI。Representationalstatetransfer(REST)是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。RESTAPI处理流程数据库数据库表user

大家好,欢迎来到IT知识分享网。

如果你现在正使用iphone、Android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTful API。Representational state transfer (REST) 是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。

REST API处理流程

REST API处理流程

数据库

数据库表users包含了user_id, user_fullname, user_email, user_password 和 user_status字段,十分简单。

CREATE TABLE IF NOT EXISTS `users`(
 	`user_id` int(11) NOT NULL AUTO_INCREMENT,
 	`user_fullname` varchar(25) NOT NULL,
 	`user_email` varchar(50) NOT NULL,
 	`user_password` varchar(50) NOT NULL,
 	`user_status` tinyint(1) NOT NULL DEFAULT '0',
 	PRIMARY KEY (`user_id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API类:api.php

代码十分简单,你需要修改数据库配置信息,如数据库名、数据库账户以及密码。

require_once("Rest.inc.php");	 
class API extends REST{
	public $data = "";
	const DB_SERVER = "localhost";
 	const DB_USER = "Database_Username";
 	const DB_PASSWORD = "Database_Password";
 	const DB = "Database_Name";
 	 
 	private $db = NULL;
 	 
 	public function __construct(){
	 	parent::__construct();// Init parent contructor
 		$this->dbConnect();// Initiate Database connection
 	}
 	 
 	//Database connection
 	private function dbConnect(){
	 	$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
 		if($this->db)
 		mysql_select_db(self::DB,$this->db);
 	}
 	 
 	//Public method for access api.
 	//This method dynmically call the method based on the query string
 	public function processApi(){
	 	$func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));
 		if((int)method_exists($this,$func) > 0)
	 		$this->$func();
	 	else
 			$this->response('',404);
	 	// If the method not exist with in this class, response would be "Page not found".
 	}
 	 
 	private function login(){
	 	..............
 	}
 	 
 	private function users(){
	 	..............
 	}
 	 
 	private function deleteUser(){
	 	.............
 	}
 	 
 	//Encode array into JSON
 	private function json($data){
	 	if(is_array($data)){
 			return json_encode($data);
	 	}
 	}
}
       // Initiiate Library
 	$api = new API;
 	$api->processApi();

提交登陆

通过访问REST API地址http://localhost/rest/login/ 显示从users表中查询出的用户数据。Restful API 的登录状态是根据状态码工作的。如果状态码为200,则登陆成功;否则状态码为204,会显示失败信息。更多的状态码信息请查看示例文件中的Rest.inc.php。

private function login(){
	// Cross validation if the request method is POST else it will return "Not Acceptable" status
	if($this->get_request_method() != "POST"){
	 	$this->response('',406);
 	}
	$email = $this->_request['email'];
 	$password = $this->_request['pwd'];
 	 
 	// Input validations
 	if(!empty($email) and !empty($password)){
	 	if(filter_var($email, FILTER_VALIDATE_EMAIL)){
 		    $sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_email = '$email' AND user_password = '".md5($password)."' LIMIT 1", $this->db);
 		    if(mysql_num_rows($sql) > 0){
		 	    $result = mysql_fetch_array($sql,MYSQL_ASSOC);
 			    // If success everythig is good send header as "OK" and user details
		 	    $this->response($this->json($result), 200);
		    }
	 	$this->response('', 204); // If no records "No Content" status
	    }
	}
 	 
 	// If invalid inputs "Bad Request" status message and reason
 	$error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
 	$this->response($this->json($error), 400);
 }

获取用户信息

通过访问REST API 地址http://localhost/rest/users/ 获取用户的信息。

 private function users(){
 	// Cross validation if the request method is GET else it will return "Not Acceptable" status
 	if($this->get_request_method() != "GET"){
 	    $this->response('',406);
 	}
 	$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
 	if(mysql_num_rows($sql) > 0){
        $result = array();
 	    while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC)){
     	    $result[] = $rlt;
        }
 	    // If success everythig is good send header as "OK" and return list of users in JSON format
     	$this->response($this->json($result), 200);
 	}
    $this->response('',204); // If no records "No Content" status
}

删除用户信息

根据user_id删除特定用户的信息,只需要访问REST API地址http://localhost/rest/deleteUser/

private function deleteUser(){
 	if($this->get_request_method() != "DELETE"){
     	$this->response('',406);
 	}
 	$id = (int)$this->_request['id'];
 	if($id > 0){
     	mysql_query("DELETE FROM users WHERE user_id = $id");
        $success = array('status' => "Success", "msg" => "Successfully one record deleted.");
     	$this->response($this->json($success),200);
 	}else{
     	$this->response('',204); // If no records "No Content" status
 	}
}

Chrome拓展

测试PHP restful API 响应的一个chrome的插件为Advanced REST client Application

.htaccess code
使用.htaccess使URL更加友好。在demo示例中修改htaccess.txt to .htaccess。

<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{REQUEST_FILENAME} !-d
	RewriteCond %{REQUEST_FILENAME} !-s
	RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]
 	 
	RewriteCond %{REQUEST_FILENAME} -d
	RewriteRule ^(.*)$ api.php [QSA,NC,L]
	 
 	RewriteCond %{REQUEST_FILENAME} -s
 	RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/20948.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信