php 如何构建 RESTful API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4684075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:58:06  来源:igfitidea点击:

How to build a RESTful API?

phpapirestauthentication

提问by Sharon Haim Pour

The issue is this: I have a web application that runs on a PHP server. I'd like to build a REST api for it.
I did some research and I figured out that REST api uses HTTP methods (GET, POST...) for certain 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'd rather JSON).

问题是这样的:我有一个在 PHP 服务器上运行的 Web 应用程序。我想为它构建一个 REST api。
我做了一些研究,我发现 REST api 使用 HTTP 方法(GET、POST ...)使用身份验证密钥(不一定)为某些 URI 提供信息,并且信息作为 HTTP 响应返回,信息为 XML 或 JSON (我更喜欢 JSON)。

My question is:

我的问题是:

  1. How do I, as the developer of the app, build those URI's? Do I need to write a PHP code at that URI?
  2. How do I build the JSON objects to return as a response?
  1. 作为应用程序的开发人员,我如何构建这些 URI?我是否需要在该 URI 处编写 PHP 代码?
  2. 如何构建 JSON 对象以作为响应返回?

采纳答案by Simon marc

Here is a very simply example in simple php.

这是一个非常简单的 php 示例。

There are 2 files client.php& api.php. I put both files on the same url : http://localhost:8888/, so you will have to change the link to your own url. (the file can be on two different servers).

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

This is just an example, it's very quick and dirty, plus it has been a long time since I've done php. But this is the idea of an api.

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

client.php

客户端.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

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

?>

I didn't make any call to the database for this example, but normally that is what you should do. You should also replace the "file_get_contents" function by "curl".

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

回答by holographic-principle

In 2013, you should use something like Silexor Slim

在 2013 年,您应该使用SilexSlim 之类的东西

Silex example:

西莱克斯示例:

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

Slim example:

苗条的例子:

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

回答by Simon marc

That is pretty much the same as created a normal website.

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

Normal pattern for a php website is:

php 网站的正常模式是:

  1. The user enter a url
  2. The server get the url, parse it and execute a action
  3. In this action, you get/generate every information you need for the page
  4. You create the html/php page with the info from the action
  5. The server generate a fully html page and send it back to the user
  1. 用户输入网址
  2. 服务器获取url,解析它并执行一个动作
  3. 在此操作中,您将获取/生成页面所需的所有信息
  4. 您使用操作中的信息创建 html/php 页面
  5. 服务器生成一个完整的html页面并发回给用户

With a api, you just add a new step between 3 and 4. After 3, create a array with all information you need. Encode this array in json and exit or return this value.

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

$info = array("info_1" => 1; "info_2" => "info_2" ... "info_n" => array(1,2,3));
exit(json_encode($info));

That all for the api. For the client side, you can call the api by the url. If the api work only with get call, I think it's possible to do a simply (To check, I normally use curl).

这一切都是为了 api。对于客户端,您可以通过 url 调用 api。如果 api 仅适用于 get 调用,我认为可以做一个简单的(为了检查,我通常使用 curl)。

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

But it's more common to use the curl library to perform get and post call. You can ask me if you need help with curl.

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

Once the get the info from the api, you can do the 4 & 5 steps.

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

Look the php doc for json function and file_get_contents.

查看 php 文档中的 json 函数和 file_get_contents。

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

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



EDIT

编辑

No, wait, I don't get it. "php API page" what do you mean by that ?

不,等等,我不明白。“php API 页面”是什么意思?

The api is only the creation/recuperation of your project. You NEVER send directly the html result (if you're making a website) throw a api. You call the api with the url, the api return information, you use this information to create the final result.

api 只是您项目的创建/恢复。你永远不会直接发送 html 结果(如果你正在制作一个网站)抛出一个 api。你用url调用api,api返回信息,你用这个信息来创建最终的结果。

ex: you want to write a html page who say hello xxx. But to get the name of the user, you have to get the info from the api.

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

So let's say your api have a function who have user_id as argument and return the name of this user (let's say getUserNameById(user_id)), and you call this function only on a url like your/api/ulr/getUser/id.

因此,假设您的 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.
}

From the client sideyou do

客户端你做

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

So the client never access directly the databases, that the api's role.

因此客户端永远不会直接访问数据库,即 api 的角色。

Is that clearer ?

是不是更清楚了?

回答by Luke

(1) How do I ... build those URI's?Do I need to write a PHP code at that URI?

(1) 我如何……构建那些 URI?我是否需要在该 URI 处编写 PHP 代码?

There is no standard for how an API URI scheme should be set up, but it's common to have slash-separated values. For this you can use...

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

$apiArgArray = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

...to get an array of slash-separated values in the URI afterthe file name.

...获取文件名URI 中斜杠分隔值的数组。

Example: Assuming you have an API file api.phpin your application somewhere and you do a request for api.php/members/3, then $apiArgArraywill be an array containing ['members', '3']. You can then use those values to query your database or do other processing.

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

(2) How do I build the JSON objects to return as a response?

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

You can take any PHP object and turn it into JSON with json_encode. You'll also want to set the appropriate header.

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

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

All this is good for an API that returns JSON, but the next question you should ask is:

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

(3) How do I make my API RESTful?

(3) 如何让我的 API RESTful?

For that we'll use $_SERVER['REQUEST_METHOD']to get the method being used, and then do different things based on that. So the final result is something like...

为此,我们将使用$_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);

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

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

回答by zimt28

Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.

另一个尚未提及的框架是Laravel。它非常适合构建 PHP 应用程序,但由于出色的路由器,构建丰富的 API 非常舒适和简单。它可能不像 Slim 或 Sliex 那样纤薄,但它为您提供了坚固的结构。

See Aaron Kuzemchak - Simple API Development With Laravelon YouTube and

请参阅Aaron Kuzemchak -在 YouTube 上使用 Laravel进行简单的 API 开发

Laravel 4: A Start at a RESTful APIon NetTuts+

Laravel 4:NetTuts+上的 RESTful API 的开始

回答by Brannon

I know that this question is accepted and has a bit of age but this might be helpful for some people who still find it relevant. Although the outcome is not a full RESTful API the API Builder mini libfor PHP allows you to easily transform MySQL databases into web accessible JSON APIs.

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

回答by James Butler

As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.

正如 simon marc 所说,该过程与您或我浏览网站的过程大致相同。如果您对使用 Zend 框架感到满意,那么有一些易于遵循的教程可以使设置变得非常容易。构建 Restful api 最困难的部分是它的设计,并使其真正安静,从数据库的角度考虑 CRUD。

It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?

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

--EDIT

- 编辑

Here is where I got started with restful api and Zend Framework. Zend Framework Example

这是我开始使用 restful api 和 Zend Framework 的地方。 Zend 框架示例

In short don't use Zend rest server, it's obsolete.

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