日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

基于php构建APi流程,php – 如何构建一个RESTful API?

發(fā)布時間:2024/9/27 php 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于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?的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。