使用PHP创建一个API服务器,从另一个api获取某些数据(例如:api.themoviedb.org)

问题描述 投票:-2回答:1

我正在创建一个用于获取某些数据的API(比如来自api.themoviedb.org的某些电影)然后我需要将这些数据作为JSON对象返回。我想知道是否有人对我如何解决这个问题有一些意见,因为我迷路了。

我知道我需要从我的api,公共API,以某些搜索条件和显然是api密钥发出GET请求。然后,我需要将此数据返回给发出搜索请求的用户。

有关如何解决此问题的任何建议吗?

php json server api-design
1个回答
2
投票

像通常那样设计你的API,我的意思是端点,路由,输出格式等。

对于从其他网络资源中检索数据,您可以使用:

<?php
$postData = 'whatever';
$headers = [
    'Content-Type: application/json',
    'Auth: depends-on-your-api',
];
$ch = curl_init("http://your-remote-api.url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

// for POST request:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// end for POST request

$response = curl_exec($ch);
$apiResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
<?php    
$postData = 'whatever';
$contextData = [
    'http' => [
        'method' => 'POST',
        'header'=> "Content-type: application/json\r\n"
            . "Auth: depends-on-your-api\r\n",
        'content' => $postData
    ]
];
$response = file_get_contents(
    'http://your-remote-api.url',
    false,
    context_create_stream($contextData)
);

这些链接针对PHP文档的特定部分,可以提示如何继续前进。

© www.soinside.com 2019 - 2024. All rights reserved.