基于php构建APi流程,php – 如何构建一个RESTful API?
這里是一個非常簡單的例子在簡單的php。
有2個文件client.php& api.php。我把這兩個文件放在同一個url:http:// localhost:8888 /,所以你必須更改鏈接到你自己的網址。 (文件可以在兩個不同的服務器上)。
這只是一個例子,它非常快速和骯臟,加上它已經很長時間,因為我做了php。但這是一個api的想法。
client.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 !!!!!
?>
| Name: | <?php echo $user_info["last_name"] ?> |
| First Name: | <?php echo $user_info["first_name"] ?> |
| Age: | <?php echo $user_info["age"] ?> |
Return to the user list
}
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 !!!!!
?>
alt=<?php echo "user_" . $user_["id"] ?>><?php echo $user["name"] ?>
}
?>
api.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”函數。
總結
以上是生活随笔為你收集整理的基于php构建APi流程,php – 如何构建一个RESTful API?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通信设备指的是什么 一般分为有线和无线
- 下一篇: java 默认网关,java 获得默认网