首页 文章

如何构建RESTful API?

提问于
浏览
73

问题是这样的:我有一个在PHP服务器上运行的Web应用程序 . 我想为它构建一个REST api .
我做了一些研究,我发现REST api使用HTTP方法(GET,POST ...)来获取某些URI 's with an authentication key (not necessarily) and the information is presented back as a HTTP response with the info as XML or JSON (I'而不是JSON) .

我的问题是:

  • 作为应用程序的开发人员,我如何构建这些URI?我需要在该URI上编写PHP代码吗?

  • 如何构建JSON对象以作为响应返回?

7 回答

  • 6

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

    有2个文件 client.phpapi.php . 我将两个文件放在同一个网址: 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
    }
    
    ?>
    

    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));
    
    ?>
    

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

  • 32

    在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();
    

    苗条的例子:

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

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

    php网站的正常模式是:

    • 用户输入网址

    • 服务器获取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仅用于调用,我认为可以简单地执行(要检查,我通常使用curl) .

    $info = file_get_contents(url);
    $info = json_decode($info);
    

    但是使用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结果(如果你正在 Build 一个网站)扔一个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.
    }
    

    client side 你做

    $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>
    

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

    那更清楚了吗?

  • 2

    (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对象作为响应返回?

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

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

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

    (3) How do I make my 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);
    

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

  • 67

    到目前为止尚未提及的另一个框架是Laravel . 它构建丰富的API非常舒适和简单 . 它可能不像Slim或Sliex那么纤薄,但它给你一个坚固的结构 .

    请参阅YouTube上的Aaron Kuzemchak - Simple API Development With Laravel

    Laravel 4: A Start at a RESTful API在NetTuts上

  • 0

    我知道这个问题已被接受并且有一点年龄,但这对于仍然认为相关的人来说可能会有所帮助 . 虽然结果不是一个完整的RESTful API,但是API Builder mini lib for PHP允许您轻松地将MySQL数据库转换为Web可访问的JSON API .

  • 10

    正如simon marc所说,这个过程与你或我浏览网站的过程非常相似 . 如果您对使用Zend框架感到满意,可以使用一些易于学习的教程,使生活变得非常容易 . 设计一个宁静的api最困难的部分是设计在数据库术语中考虑CRUD,并使其真正变得安静 .

    可能你真的想要一个xmlrpc接口或类似的东西 . 你希望这个界面允许你做什么?

    • 编辑

    这是我开始使用restful api和Zend Framework的地方 . Zend Framework Example

    总之不要使用Zend休息服务器,它已经过时了 .

相关问题