(1)/users/{user_id}php
编写时候,须要在 /application/config/routers.php 中增长路由指向(这里的user_id是纯数字):json
$route['users/(:num)']='users/user_id/$1';
而后在名为 users 的 controller中,api
<?php class Users extends CI_Controller { public function user_id($id){ // 这里的 $id 就是地址上传的 {user_id} 参数了 } } ?>
(2)/users?group_id = {group_id}app
这里就用普通的 $_GET['group_id'] 便可取到参数
curl
二、接收传递的方法,
REST API 中有 POST,GET,PUT和DELETE 等方法url
须要接收传递过来的方法加以判断
假设有这两个接口,
删除用户: DELETE /users/{user_id}code
修改用户: PUT /users/{user_id}
router
用到 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 } }
三、接收在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);
四、返回
一般
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");