如何构建RESTful API?

Sha*_*our 73 php authentication api rest

问题是:我有一个在PHP服务器上运行的Web应用程序.我想为它构建一个REST api.
我做了一些研究,我发现REST api使用HTTP方法(GET,POST ...)为某些带有身份验证密钥的URI(不一定),并将信息作为HTTP响应呈现回来,信息为XML或JSON (我宁愿JSON).

我的问题是:

  1. 作为应用程序的开发人员,我如何构建这些URI?我需要在该URI上编写PHP代码吗?
  2. 如何构建JSON对象作为响应返回?

Sim*_*arc 67

这是一个简单的PHP中一个非常简单的例子.

client.phpapi.php有2个文件.我将两个文件放在同一个网址上:http://localhost:8888/,因此您必须将链接更改为您自己的网址.(该文件可以位于两个不同的服务器上).

这只是一个例子,它非常快速和肮脏,而且自从我完成php以来已经很长时间了.但这是api的想法.

client.php

<?php

/*** this is the client ***/


if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] == "get_user") // if the get parameter action is get_user and if the id is set, call the api to get the user information
{
  $user_info = file_get_contents('http://localhost:8888/api.php?action=get_user&id=' . $_GET["id"]);
  $user_info = json_decode($user_info, true);

  // THAT IS VERY QUICK AND DIRTY !!!!!
  ?>
    <table>
      <tr>
        <td>Name: </td><td> <?php echo $user_info["last_name"] ?></td>
      </tr>
      <tr>
        <td>First Name: </td><td> <?php echo $user_info["first_name"] ?></td>
      </tr>
      <tr>
        <td>Age: </td><td> <?php echo $user_info["age"] ?></td>
      </tr>
    </table>
    <a href="http://localhost:8888/client.php?action=get_userlist" alt="user list">Return to the user list</a>
  <?php
}
else // else take the user list
{
  $user_list = file_get_contents('http://localhost:8888/api.php?action=get_user_list');
  $user_list = json_decode($user_list, true);
  // THAT IS VERY QUICK AND DIRTY !!!!!
  ?>
    <ul>
    <?php foreach ($user_list as $user): ?>
      <li>
        <a href=<?php echo "http://localhost:8888/client.php?action=get_user&id=" . $user["id"]  ?> alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?></a>
    </li>
    <?php endforeach; ?>
    </ul>
  <?php
}

?>
Run Code Online (Sandbox Code Playgroud)

api.php

<?php

// This is the API to possibility show the user list, and show a specific user by action.

function get_user_by_id($id)
{
  $user_info = array();

  // make a call in db.
  switch ($id){
    case 1:
      $user_info = array("first_name" => "Marc", "last_name" => "Simon", "age" => 21); // let's say first_name, last_name, age
      break;
    case 2:
      $user_info = array("first_name" => "Frederic", "last_name" => "Zannetie", "age" => 24);
      break;
    case 3:
      $user_info = array("first_name" => "Laure", "last_name" => "Carbonnel", "age" => 45);
      break;
  }

  return $user_info;
}

function get_user_list()
{
  $user_list = array(array("id" => 1, "name" => "Simon"), array("id" => 2, "name" => "Zannetie"), array("id" => 3, "name" => "Carbonnel")); // call in db, here I make a list of 3 users.

  return $user_list;
}

$possible_url = array("get_user_list", "get_user");

$value = "An error has occurred";

if (isset($_GET["action"]) && in_array($_GET["action"], $possible_url))
{
  switch ($_GET["action"])
    {
      case "get_user_list":
        $value = get_user_list();
        break;
      case "get_user":
        if (isset($_GET["id"]))
          $value = get_user_by_id($_GET["id"]);
        else
          $value = "Missing argument";
        break;
    }
}

exit(json_encode($value));

?>
Run Code Online (Sandbox Code Playgroud)

我没有为这个例子调用数据库,但通常这就是你应该做的.您还应该用"curl"替换"file_get_contents"函数.

  • 这只使用"GET"而不会查看请求方法,所以它不是*RESTful*.有关示例,请参见http://stackoverflow.com/a/897311/1766230,以及http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services (6认同)

hol*_*ple 34

在2013年,你应该使用像SilexSlim这样的东西

Silex示例:

require_once __DIR__.'/../vendor/autoload.php'; 

$app = new Silex\Application(); 

$app->get('/hello/{name}', function($name) use($app) { 
    return 'Hello '.$app->escape($name); 
}); 

$app->run(); 
Run Code Online (Sandbox Code Playgroud)

苗条的例子:

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
$app->run();
Run Code Online (Sandbox Code Playgroud)

  • @IlkerBaltaci使用Silex,您可以将控制器提取到类中.这是一篇很好的文章,以及使用微框架与全栈框架的一些优点和缺点https://igor.io/2012/11/09/scaling-silex.html.我个人更喜欢Silex,因为它给了我最重要的东西,让我选择其余的堆栈. (2认同)

Sim*_*arc 10

这与创建普通网站几乎相同.

php网站的正常模式是:

  1. 用户输入网址
  2. 服务器获取URL,解析它并执行操作
  3. 在此操作中,您将获得/生成页面所需的所有信息
  4. 您可以使用操作中的信息创建html/php页面
  5. 服务器生成一个完整的html页面并将其发送回用户

使用api,您只需在3和4之间添加一个新步骤.3之后,创建一个包含所需信息的数组.在json中对此数组进行编码并退出或返回此值.

$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));
Run Code Online (Sandbox Code Playgroud)

这一切都是针对api的.对于客户端,您可以通过URL调用api.如果api仅用于调用,我认为可以简单地执行(要检查,我通常使用curl).

$info = file_get_contents(url);
$info = json_decode($info);
Run Code Online (Sandbox Code Playgroud)

但是使用curl库来执行get和post调用更常见.你可以问我是否需要帮助卷曲.

从api获取信息后,您可以执行4和5步骤.

查看php doc for json function和file_get_contents.

卷曲:http://fr.php.net/manual/fr/ref.curl.php


编辑

不,等等,我不明白."php API页面"你的意思是什么?

api只是你项目的创建/恢复.你永远不要直接发送html结果(如果你正在建立一个网站)扔一个api.您使用url调用api,api返回信息,您使用此信息创建最终结果.

例如:你想写一个html页面,他们说你好xxx.但要获取用户的名称,您必须从api获取信息.

所以假设你的api有一个函数谁有user_id作为参数并返回这个用户的名字(比如说getUserNameById(user_id)),你只在你的/ api/ulr/getUser/id之类的url上调用这个函数.

Function getUserNameById(user_id)
{
  $userName = // call in db to get the user
  exit(json_encode($userName)); // maybe return work as well.
}
Run Code Online (Sandbox Code Playgroud)

客户端你做

    $username = file_get_contents(your/api/url/getUser/15); // You should normally use curl, but it simpler for the example
// So this function to this specifique url will call the api, and trigger the getUserNameById(user_id), whom give you the user name.
    <html>
    <body>
    <p>hello <?php echo $username ?> </p>
    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

所以客户端永远不会直接访问数据库,即api的角色.

那更清楚了吗?


Luk*_*uke 6

(1)我如何...构建这些URI?我需要在该URI上编写PHP代码吗?

关于如何设置API URI方案没有标准,但通常有斜杠分隔值.为此您可以使用......

$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
Run Code Online (Sandbox Code Playgroud)

... 在文件名后面的URI中获取一系列斜杠分隔值.

示例:假设您api.php的应用程序中有一个API文件并且您请求api.php/members/3,那么$apiArgArray将是一个包含的数组['members', '3'].然后,您可以使用这些值来查询数据库或执行其他处理.

(2)如何构建JSON对象以作为响应返回?

您可以使用任何PHP对象并使用json_encode将其转换为JSON .您还需要设置适当的标题.

header('Content-Type: application/json');
$myObject = (object) array( 'property' => 'value' ); // example
echo json_encode($myObject); // outputs JSON text
Run Code Online (Sandbox Code Playgroud)

这一切对于返回JSON的API都有好处,但您应该问的下一个问题是:

(3)如何使我的API RESTful?

为此我们将使用$_SERVER['REQUEST_METHOD']获取方法,然后根据它做不同的事情.所以最后的结果是......

header('Content-Type: application/json');
$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
$returnObject = (object) array();
/* Based on the method, use the arguments to figure out
   whether you're working with an individual or a collection, 
   then do your processing, and ultimately set $returnObject */
switch ($_SERVER['REQUEST_METHOD']) {
  case 'GET':
    // List entire collection or retrieve individual member
    break;
  case 'PUT':       
    // Replace entire collection or member
    break;  
  case 'POST':      
    // Create new member
    break;
  case 'DELETE':    
    // Delete collection or member
    break;
}
echo json_encode($returnObject);
Run Code Online (Sandbox Code Playgroud)

来源:https://stackoverflow.com/a/897311/1766230http://en.wikipedia.org/wiki/Representational_state_transfer#Applied_to_web_services