【CI 框架】CI 框架编写 REST API 小记

1、地址接收参数

地址参数的两种形式

(1)/users/{user_id}


编写时候,需要在 /application/config/routers.php 中增加路由指向(这里的user_id是纯数字):


$route['users/(:num)']='users/user_id/$1';

然后在名为 users 的 controller中,


<?php
class Users extends CI_Controller {
	public function user_id($id){
		// 这里的 $id 就是地址上传的 {user_id} 参数了
	}
}
?>


(2)/users?group_id = {group_id}


这里就用普通的 $_GET['group_id'] 即可取到参数



2、接收传递的方法,

REST API 中有 POST,GET,PUT和DELETE 等方法

需要接收传递过来的方法加以判断

假设有这两个接口,

删除用户: DELETE /users/{user_id}

修改用户: PUT /users/{user_id}


用到 1 中提到的router的修改,并且在controller中可以这样判断


public function user_id($id){
	$method = $_SERVER['REQUEST_METHOD'];

	if($method == 'DELETE'){
		// delete user
	}else if($method == 'PUT'){
		// update user
	}else{
		// wrong method
	}
}


3、接收在body中传过来的参数


比如这样一个登录接口,就需要在body中传name和password参数:

curl -kis 'http://api.example.com/v1/login' -d '{"name":"admin","password":"000000"}'


通过这个方法可以拿到body中的内容

$data_str = file_get_contents('php://input');
$data_arr = json_decode($data_str,true);

然后通过 $data_arr['name'],$data_arr['password'] 分别可以访问到



4、返回


通常

GET对应的返回是200,500等

POST、PUT对应的返回是201,500等

DELETE对应的返回是204,500等


header("HTTP/1.1 200 OK");
header("Content-type: application/json");
echo json_encode($return);


header("HTTP/1.1 201 Created");
header("Content-type: application/json");
echo json_encode($return);


header("HTTP/1.1 201 Updated");
header("Content-type: application/json");
echo json_encode($return);


header("HTTP/1.1 204 No content");
header_remove("Content-type"); 

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-09-25 16:28  snow_finland  阅读(1075)  评论(0编辑  收藏  举报