【发布时间】:2023-03-08 00:24:01
【问题描述】:
所以我们想创建一个私有 API,允许其他人与我们的服务进行交互,例如通过 api 将某些内容保存在我们的数据库中或获取某些信息。
API 本身只需要可以通过任何编程语言传递给 API 的 JSON 数据。与 facebook 等其他 API 不同,我们不会向用户提供任何文件以供用户使用 API,例如 facebook 确实提供了不同语言的类以与他们的 api 交互。所以我们认为 api 用户可以使用任何语言向我们发送 json 数据,并且基于该 json 数据,我们可以通过他们通过查询字符串提供的use 参数调用 api 的某些函数。
以下是最基本的 API 代码,可让您了解其工作原理:
class Api
{
/**
* Default function called when API url is accessed
*
* @return mixed
* @throws Exception
*/
public function index()
{
$appId = isset($_GET['appId']) ? $_GET['appId'] : null;
$apiKey = $_GET['apiKey'] ? $_GET['apiKey'] : null;
$method = $_GET['use'] ? $_GET['use'] : null;
$data = json_decode(file_get_contents("php://input"), true);
if ($this->validateRequest($appId, $apiKey, $method)) {
return call_user_func_array(array($this, $method), array($data));
}
}
private function validateRequest($appId, $apiKey, $method)
{
# check referer
$requestUri = isset($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : null;
if (!$requestUri) {
$this->bye('HTTP_REFERER is required!');
}
# check if method exists
if (!$method || !method_exists('Apicall', $method)) {
$this->bye('Invalid \'use\' value!');
}
# check appId, apiKey and requestUri
if (!$appId) {
$this->bye('Invalid appId!');
}
if (!$apiKey) {
$this->bye('Invalid apiKey!');
}
$db = new DB();
$db->where('appid', $appId);
$db->where('apikey', $apiKey);
$db->where('request_uri', pathWithoutEndingSlash($requestUri));
$db->get();
if ($db->exists() && $db->result_count() > 0) {
return true;
}
$this->bye('Request Denied!');
}
private function bye($error)
{
echo json_encode(array('Error' => $error));
exit;
}
private function getIntervals()
{
$values = array('monthly', 'quarterly', 'yearly', 'single_payment');
echo json_encode($values);
}
}
可以看出,我们验证提供的appId、apiKey和requestURI是否存在于我们的数据库中(我们已经为api用户生成)然后调用通过use查询字符串变量指定的方法电话:
http://localhost/myapi/api.php?appId=local&apiKey=98a4d2e5b7fa21d424a0932c7f47a6943d57d64b&use=getIntervals
这是制作私有 API 的正确方法还是我仍然遗漏了什么?
【问题讨论】:
标签: php api standards web-standards