Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何构建RESTful API?_Php_Rest_Authentication_Restapi - Fatal编程技术网

Php 如何构建RESTful API?

Php 如何构建RESTful API?,php,rest,authentication,restapi,Php,Rest,Authentication,Restapi,问题是: 我有一个在PHP服务器上运行的web应用程序。我想为它构建一个RESTAPI。 我做了一些研究,发现RESTAPI对某些URI使用HTTP方法(GET、POST…)和身份验证密钥(不一定),信息以HTTP响应的形式呈现,信息为XML或JSON(我更喜欢JSON) 我的问题是: 作为应用程序的开发人员,我如何构建这些URI?我是否需要在该URI上编写PHP代码 如何构建JSON对象以作为响应返回 这与创建一个普通网站几乎相同 php网站的正常模式为: 用户输入一个url 服务器获取url

问题是: 我有一个在PHP服务器上运行的web应用程序。我想为它构建一个RESTAPI。
我做了一些研究,发现RESTAPI对某些URI使用HTTP方法(GET、POST…)和身份验证密钥(不一定),信息以HTTP响应的形式呈现,信息为XML或JSON(我更喜欢JSON)

我的问题是:

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

  • 这与创建一个普通网站几乎相同

    php网站的正常模式为:

  • 用户输入一个url
  • 服务器获取url,解析它并执行操作
  • 在此操作中,您将获取/生成页面所需的所有信息
  • 您可以使用操作中的信息创建html/php页面
  • 服务器生成一个完整的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));
    
    这就是api的全部内容。 对于客户端,您可以通过url调用api。如果api只支持get调用,我认为可以简单地进行一次检查(为了检查,我通常使用curl)

    但更常见的是使用curl库执行get和post调用。 如果你需要卷发的帮助,可以问我

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

    查看php文档中的json函数和文件内容

    卷曲:


    编辑

    不,等等,我不明白。“PHPAPI页面”这是什么意思

    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.
    }
    
    客户端您可以

        $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>
    
    $username=file_get_内容(您的/api/url/getUser/15);//通常应该使用curl,但对于示例来说更简单
    //因此,此特定url的函数将调用api,并触发getUserNameById(user_id),它将为您提供用户名。
    你好

    因此,客户端从不直接访问数据库,这是api的角色


    这更清楚吗?

    正如西蒙·马克所说,这个过程和你我浏览网站的过程差不多。如果您对使用Zend框架感到满意,那么有一些简单易懂的教程可以帮助您轻松地进行设置。构建restful api最困难的部分是它的设计,让它真正restful,从数据库的角度考虑CRUD

    可能您真的需要一个xmlrpc接口或其他类似的接口。您希望此接口允许您做什么

    --编辑

    这里是我开始使用RESTfulAPI和Zend框架的地方。


    简而言之,不要使用Zend rest服务器,它已经过时了。

    这里是一个简单php的简单示例

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

    这只是一个例子,它非常快速和肮脏,加上它已经有很长一段时间,因为我已经做了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
    }
    
    ?>
    
    <?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));
    
    ?>
    
    
    姓名:
    名字:
    年龄:
    
    api.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
    }
    
    ?>
    
    <?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));
    
    ?>
    

    在2013年,您应该使用或

    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(); 
    
    例如:

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

    另一个迄今尚未提及的框架是。一般来说,它非常适合构建PHP应用程序,但多亏了伟大的路由器,构建丰富的API变得非常舒适和简单。它可能不像slim或Sliex那样纤细,但它可以为您提供坚实的结构

    在YouTube和


    在NetTuts+

    上,我知道这个问题已经被接受,而且有点老了,但这可能会对一些仍然认为它相关的人有所帮助。尽管结果不是一个完整的RESTful API,但PHP允许您轻松地将MySQL数据库转换为可通过web访问的JSON API

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

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

    $apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    
    …获取文件名后URI中以斜杠分隔的值数组

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

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

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

    header('Content-Type: application/json');
    $myObject = (object) array( 'property' => 'value' ); // example
    echo json_encode($myObject); // outputs JSON text
    
    所有这些对于返回JSON的API来说都是好的,但下一个问题是:

    (3)如何使API保持RESTful?

    为此,我们将使用
    $\u SERVER['REQUEST\u METHOD']
    获取正在使用的方法,然后进行不同的操作