如何建立一个RESTful API? [英] How to build a RESTful API?

查看:157
本文介绍了如何建立一个RESTful API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是这样的:
我有一个PHP的服务器上运行的Web应用程序。我想建立一个REST API它。结果
我做了一些研究,我想通了,REST API使用HTTP方法(GET,POST ...)对于某些URI与验证密钥(不一定)和信息psented追溯到与信息作为HTTP响应$ P $ XML或JSON(我宁愿JSON)。

我的问题是:


  1. 如何,作为应用程序的开发者,构建这些URI的?我是否需要在该URI来写一个PHP code?

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


解决方案

下面是简单的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".

这篇关于如何建立一个RESTful API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆