且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何建立一个RESTful API?

更新时间:2023-11-30 13:08:40

下面是简单的PHP非常简单的例子。

有2个文件的 client.php &安培; api.php 。我把两个文件在同一网址:的http://本地主机:8888 / ,所以你必须将链接改为自己的URL。 (该文件可以在两台不同的服务器)。

这只是一个例子,这是非常快速和肮脏的,再加上它已经很长一段时间,因为我已经做了PHP。但是,这是一个API的想法。

client.php

 < PHP/ ***这是客户*** /
如果(使用isset($ _ GET [行动])及和放大器;使用isset($ _ GET [身份证])及和放大器; $ _GET [行动] ==GET_USER)//如果get参数动作是GET_USER,如果ID设置,调用API来获取用户信息
{
  $ USER_INFO =的file_get_contents(的http://本地主机:8888 / api.php行动= GET_USER和ID ='$ _GET [身份证]);
  $ USER_INFO = json_de code($ USER_INFO,真正的);  //这是非常快速和肮脏的!!!!!
  ?>
    <表>
      &所述; TR>
        &所述; TD>名称:其中; / TD>&下; TD> <?PHP的echo $ USER_INFO [姓氏]>< / TD>
      < / TR>
      &所述; TR>
        &所述; TD>首先名称:其中; / TD>&下; TD> <?PHP的echo $ USER_INFO [如first_name]>< / TD>
      < / TR>
      &所述; TR>
        < TD>年龄:< / TD>< TD> <?PHP的echo $ USER_INFO [时代]>< / TD>
      < / TR>
    < /表>
    < A HREF =HTTP://本地主机:8888 / client.php行动= get_userlistALT =用户列表>返回到用户列表< / A>
  < PHP
}
其他还有//把用户列表
{
  $ USER_LIST =的file_get_contents(的http://本地主机:8888 / api.php行动= get_user_list?');
  $ USER_LIST = json_de code($ USER_LIST,真正的);
  //这是非常快速和肮脏的!!!!!
  ?>
    < UL>
    ?< PHP的foreach($ USER_LIST为$用户):>
      <立GT;
        < A HREF =< PHP回声的http://本地主机:8888 / client.php行动= GET_USER和ID =? $用户[ID]&GT?; ALT =<?PHP的回声用户_。 $用户_ [ID]>>< PHP的echo $用户[名]>< / A>
    < /李>
    < PHP endforeach; ?>
    < / UL>
  < PHP
}?>

api.php

 < PHP//这是API来显示可能的用户列表,并显示通过行动的特定用户。功能get_user_by_id($ ID)
{
  $ USER_INFO =阵列();  //使数据库的调用。
  开关($编号){
    情况1:
      $ USER_INFO =阵列(FIRST_NAME=>中马克,姓氏=>中西门,年龄= GT; 21); //让我们说名字,姓氏,年龄
      打破;
    案例2:
      $ USER_INFO =阵列(FIRST_NAME=>中弗雷德里克,姓氏=>中Zannetie,年龄= GT; 24);
      打破;
    案例3:
      $ USER_INFO =阵列(FIRST_NAME=>中劳拉,姓氏=>中Carbonnel,年龄= GT; 45);
      打破;
  }  返回$ USER_INFO;
}功能get_user_list()
{
  $ USER_LIST =阵列(阵列(ID=> 1,名=>中西蒙),阵列(ID=> 2,名=>中Zannetie),阵列(编号=→3,姓名=>中Carbonnel)); //调用数据库,这里我提出3的用户列表。  返回$ USER_LIST;
}$ POSSIBLE_URL =阵列(get_user_list,GET_USER);$值=发生错误;如果(使用isset($ _ GET [行动])及和放大器; in_array($ _ GET [行动],$ POSSIBLE_URL))
{
  开关($ _GET [行动])
    {
      案get_user_list:
        $值= get_user_list();
        打破;
      案GET_USER:
        如果(使用isset($ _ GET [ID]))
          $值= get_user_by_id($ _ GET [身份证]);
        其他
          $值=失踪的说法;
        打破;
    }
}出口(json_en code($值));?>

我没有到数据库在这个例子中的任何呼叫,但通常这是你应该做的。你还应该以卷曲取代的file_get_contents功能。

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

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?

Here is a very simply example in simple 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).

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.

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

?>

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".