如果你现在正使用iphone、android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTful API。Representational state transfer (REST) 是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。
REST API处理流程
数据库
数据库表users包含了user_id, user_fullname, user_email, user_password 和 user_status字段,十分简单。
1 |
CREATE TABLE
IF NOT
EXISTS `users`
|
3 |
`user_id` int (11)
NOT NULL
AUTO_INCREMENT,
|
4 |
`user_fullname` varchar (25)
NOT NULL ,
|
5 |
`user_email` varchar (50)
NOT NULL ,
|
6 |
`user_password` varchar (50)
NOT NULL ,
|
7 |
`user_status` tinyint(1) NOT
NULL DEFAULT
'0' ,
|
8 |
PRIMARY KEY
(`user_id`)
|
9 |
) ENGINE=InnoDB DEFAULT
CHARSET=latin1 AUTO_INCREMENT=1 ;
|
Rest API类:api.php
代码十分简单,你需要修改数据库配置信息,如数据库名、数据库账户以及密码。
1 |
require_once ( "Rest.inc.php" );
|
6 |
const DB_SERVER =
"localhost" ;
|
7 |
const DB_USER =
"Database_Username" ;
|
8 |
const DB_PASSWORD =
"Database_Password" ;
|
9 |
const DB =
"Database_Name" ;
|
13 |
public function
__construct()
|
15 |
parent::__construct();
|
20 |
private function
dbConnect()
|
22 |
$this ->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
|
24 |
mysql_select_db(self::DB, $this ->db);
|
29 |
public function
processApi()
|
31 |
$func =
strtolower (trim( str_replace ( "/" , "" , $_REQUEST [ 'rquest' ])));
|
32 |
if ((int)method_exists( $this , $func ) > 0)
|
35 |
$this ->response( '' ,404);
|
39 |
private function
login()
|
44 |
private function
users()
|
49 |
private function
deleteUser()
|
55 |
private function
json( $data )
|
58 |
return json_encode( $data );
|
提交登陆
通过访问REST API地址http://localhost/rest/login/ 显示从users表中查询出的用户数据。Restful API 的登录状态是根据状态码工作的。如果状态码为200,则登陆成功;否则状态码为204,会显示失败信息。更多的状态码信息请查看示例文件中的Rest.inc.php。
1 |
private function
login()
|
4 |
if ( $this ->get_request_method() !=
"POST" )
|
6 |
$this ->response( '' ,406);
|
9 |
$email =
$this ->_request[ 'email' ];
|
10 |
$password =
$this ->_request[ 'pwd' ];
|
13 |
if (! empty ( $email )
and ! empty ( $password ))
|
15 |
if (filter_var( $email , FILTER_VALIDATE_EMAIL)){
|
16 |
$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);
|
17 |
if (mysql_num_rows( $sql ) > 0){
|
18 |
$result = mysql_fetch_array( $sql ,MYSQL_ASSOC);
|
21 |
$this ->response( $this ->json( $result ), 200);
|
23 |
$this ->response( '' , 204);
|
28 |
$error =
array ( 'status'
=> "Failed" ,
"msg" => "Invalid Email address or Password" );
|
29 |
$this ->response( $this ->json( $error ), 400);
|
获取用户信息
通过访问REST API 地址http://localhost/rest/users/ 获取用户的信息。
1 |
private function
users()
|
4 |
if ( $this ->get_request_method() !=
"GET" )
|
6 |
$this ->response( '' ,406);
|
8 |
$sql = mysql_query( "SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1" ,
$this ->db);
|
9 |
if (mysql_num_rows( $sql ) > 0)
|
12 |
while ( $rlt
= mysql_fetch_array( $sql ,MYSQL_ASSOC))
|
17 |
$this ->response( $this ->json( $result ), 200);
|
19 |
$this ->response( '' ,204);
|
删除用户信息
根据user_id删除特定用户的信息,只需要访问REST API地址http://localhost/rest/deleteUser/
1 |
private function
deleteUser()
|
4 |
if ( $this ->get_request_method() !=
"DELETE" ){
|
5 |
$this ->response( '' ,406);
|
7 |
$id = (int) $this ->_request[ 'id' ];
|
10 |
mysql_query( "DELETE FROM users WHERE user_id = $id" );
|
11 |
$success =
array ( 'status'
=> "Success" ,
"msg" => "Successfully one record deleted." );
|
12 |
$this ->response( $this ->json( $success ),200);
|
16 |
$this ->response( '' ,204);
|
Chrome拓展
测试PHP restful API 响应的一个chrome的插件为Advanced REST client Application
.htaccess code
使用.htaccess使URL更加友好。在demo示例中修改htaccess.txt to .htaccess。
1 |
< IfModule
mod_rewrite.c>
|
3 |
RewriteCond %{REQUEST_FILENAME} !-d |
4 |
RewriteCond %{REQUEST_FILENAME} !-s |
5 |
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L] |
7 |
RewriteCond %{REQUEST_FILENAME} -d |
8 |
RewriteRule ^(.*)$ api.php [QSA,NC,L] |
10 |
RewriteCond %{REQUEST_FILENAME} -s |
11 |
RewriteRule ^(.*)$ api.php [QSA,NC,L] |
Demo示例下载:
PHP示例源码:REST
API示例(104)
原文出自:http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html
本文由PHP爱好者原创翻译!转载请注明链接!
分享到:
相关推荐
yii2-basic-rest-api-app rest api的示例应用程序
演讲演示项目地址: : 文档地址:语音识别: ://ai.baidu.com/docs#/ASR-API/top语音合成: ://ai.baidu.com/docs#/TTS-API/top百度语音rest api调用语音识别,语音合成示例Rest API接口为http访问,任意操作系统,...
Symfony 4 JWT REST API示例/样板文件/演示 这是使用JWT(JSON Web令牌)的Symfony 4 REST API的样板实现(在类固醇上)。 它是在考虑最佳REST API惯例的情况下创建的。 REST API交互或多或少遵循此出色文章提供的...
SLIM PHP中的REST API 带有的RESTful API示例。 这个简单的API可让您管理资源,例如:用户,任务和注释。 您也可以阅读。 使用的主要技术: PHP 7, Slim 3, MySQL, Redis, dotenv, PHPUnit and JSON Web Tokens. ...
PSX是用PHP编写的专用于构建REST API的框架。 它基于涵盖API生命周期许多方面的多个组件。 这些组件独立于框架,也可以在其他上下文中使用。 以下列表包含最著名的软件包: 解析并生成API规范格式(即OpenAPI,RAML...
WordPress的REST API :fire: 出色地 :front-facing_baby_chick: WordPress REST(表示状态传输)Api(应用程序编程接口)将使您能够从您的站点或任何其他站点中提取特定数据,并对这些数据进行任何处理。 但是在这些...
您可以通过以下浏览Itop REST API文档: //wiki.openitop.org/doku.php?id advancedtopics:rest_json 依存关系 Python> = 2.6 要求 用法 搜索 通过pitop模块中可用的搜索功能完成搜索/获取操作。 该函数返回从...
apirest示例:APIREST [PHP,MySql,Jquery,Ajax0]的实现
PHP中的示例RESTful Web服务 这是一个项目,您可以将其用作模板来创建和运行用PHP编写的新服务。 执行样本服务API 要执行示例服务,请执行以下步骤: 克隆项目 安装依赖项: ./initProject.sh ticketshop 调整....
SugarCRM-REST-API-Wrapper-Class, 用于 SugarCRM REST API的PHP包装类 的SugarCRM REST API 包装类以Kusuma为单位http://www.asakusuma.com/许可证:MIT电子邮件内容关于安装用法示例便笺get_note_attachment() ...
该插件的目的是为开发人员提供一个简单的代码块,用于“ hello-world-ing”新的WordPress JSON Rest API: : 从WordPress 4.0开始,JSON API不再是核心的一部分,因此,如果博客没有Ryan McCue的JSON API插件,则...
restVNBIG Rest Api客户端示例 目前只提供C++、C# 、Java、PHP、Python
该存储库包含MessageBird的REST API的开源PHP客户端。 可以在以下位置找到文档: : 要求 一个免费的MessageBird帐户 在开发人员部分中创建一个新的access_key PHP的MessageBird API客户端需要PHP> = 7.0。 安装 ...
已使用以下路由创建了JSON REST API类型的控制器: HTTP方法:GET: URI:/ api /产品| 返回所有可用的产品 URI:/ api / product / {id} | 按ID返回产品 HTTP方法:POST: URI:/ api /产品| 根据JSON请求中...
Symfony2 Rest API示例该项目旨在作为此处创建的教程的应用程序: : 建议读者通读提交的历史以及代码本身,因为它受到了严重的注释,以便为希望使用symfony2创建REST Api的人提供示例基础应用程序代码位于My...
REST API客户端 该SDK包括针对的REST客户端。 客户使用 客户端基于。 基本用法是使用您的API密钥进行构造并直接调用。 以下示例仅验证您的凭据: $ client = Loco \ Http \ ApiClient :: factory ([ 'key' => 'your...
适用于CodeIgniter后端REST API的示例 网址执行专案 或者 编辑将控制器路由到/Application/modules/api/controllers/v1/welcome.php HMVC 特征 智威汤逊 用户认证 示例模型 电子邮件: 密码:12345678 #示例头 ...
php_rest 带有PHP的示例rest-api
DoubleClick Ad Exchange Seller REST API的示例 这些代码示例按平台或语言进行组织。 java是一个命令行示例,显示了如何使用Java编写针对API的大多数调用。 php-clientlib-0.6是一组示例,显示了如何对用PHP编写...
PHP MVC REST API使用指南 什么是REST API? 如果您曾经在手机中使用过Facebook,Twitter或任何其他应用程序,则这些应用程序需要连接到Internet才能从其网站获取数据或向其网站发送数据。 新增路线 要创建新路由,...