在 PHP 中调用 REST API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9802788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a REST API in PHP
提问by Michiel
Our client had given me a REST API to which I need to make a PHP call to. But as a matter of fact the documentation given with the API is very limited, so I don't really know how to call the service.
我们的客户给了我一个 REST API,我需要对它进行 PHP 调用。但事实上,API 提供的文档非常有限,所以我真的不知道如何调用该服务。
I've tried to Google it, but the only thing that came up was an already expired Yahoo! tutorial on how to call the service. Not mentioning the headers or anything in depth information.
我试图用谷歌搜索它,但唯一出现的是一个已经过期的雅虎!关于如何调用服务的教程。没有提到标题或任何深入的信息。
Is there any decent information around how to call a REST API, or some documentation about it? Because even on W3schools, they only describes the SOAP method. What are different options for making rest API in PHP?
是否有关于如何调用 REST API 或有关它的一些文档的任何体面的信息?因为即使在 W3schools 上,他们也只描述了 SOAP 方法。在 PHP 中制作 rest API 有哪些不同的选择?
回答by Christoph Winkler
You can access any REST API with PHPs cURL
Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!
您可以使用 PHPcURL
扩展访问任何 REST API 。但是,API 文档(方法、参数等)必须由您的客户提供!
Example:
例子:
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
回答by Andreas Wong
If you have a url and your php supports it, you could just call file_get_contents:
如果你有一个 url 并且你的 php 支持它,你可以调用 file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into php array:
如果 $response 是 JSON,则使用 json_decode 将其转换为 php 数组:
$response = json_decode($response);
if $response is XML, use simple_xml class:
如果 $response 是 XML,请使用 simple_xml 类:
$response = new SimpleXMLElement($response);
回答by colan
Use Guzzle. It's a "PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services". Working with Guzzle is much easier than working with cURL.
使用狂饮。它是一个“PHP HTTP 客户端,可以轻松使用 HTTP/1.1 并消除使用 Web 服务的痛苦”。使用 Guzzle 比使用 cURL 容易得多。
Here's an example from the Web site:
以下是来自网站的示例:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode(); // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
var_export($res->json()); // Outputs the JSON decoded data
回答by Broncha
CURL is the simplest way to go. Here is a simple call
CURL 是最简单的方法。这是一个简单的调用
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
回答by Somnath Muluk
Use HTTPFUL
使用HTTPFUL
Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.
Httpful 是一个简单的、可链接的、可读的 PHP 库,旨在使 HTTP 说话变得理智。它让开发人员专注于与 API 交互,而不是筛选 curl set_opt 页面,并且是理想的 PHP REST 客户端。
Httpful includes...
Httpful 包括...
- Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
- Custom Headers
- Automatic "Smart" Parsing
- Automatic Payload Serialization
- Basic Auth
- Client Side Certificate Auth
- Request "Templates"
- 可读的 HTTP 方法支持(GET、PUT、POST、DELETE、HEAD 和 OPTIONS)
- 自定义标题
- 自动“智能”解析
- 自动有效载荷序列化
- 基本认证
- 客户端证书认证
- 请求“模板”
Ex.
前任。
Send off a GET request. Get automatically parsed JSON response.
发送 GET 请求。获取自动解析的 JSON 响应。
The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.
该库会注意到响应中的 JSON Content-Type 并自动将响应解析为原生 PHP 对象。
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
回答by Derek Gogol
You will need to know if the REST API you are calling supports GET
or POST
, or both methods. The code below is something that works for me, I'm calling my own web service API, so I already know what the API takes and what it will return. It supports both GET
and POST
methods, so the less sensitive info goes into the URL (GET)
, and the info like username and password is submitted as POST
variables. Also, everything goes over the HTTPS
connection.
您需要知道您正在调用的 REST API 是否支持GET
或POST
,或这两种方法。下面的代码对我有用,我正在调用我自己的 Web 服务 API,所以我已经知道 API 需要什么以及它将返回什么。它同时支持GET
和POST
方法,因此不太敏感的信息进入URL (GET)
,并且用户名和密码等信息作为POST
变量提交。此外,一切都通过HTTPS
连接。
Inside the API code, I encode an array I want to return into json format, then simply use PHP command echo $my_json_variable
to make that json string availabe to the client.
在 API 代码中,我将要返回的数组编码为 json 格式,然后只需使用 PHP 命令echo $my_json_variable
即可将该 json 字符串提供给客户端。
So as you can see, my API returns json data, but you need to know (or look at the returned data to find out) what format the response from the API is in.
如您所见,我的 API 返回 json 数据,但您需要知道(或查看返回的数据以找出)来自 API 的响应采用的格式。
This is how I connect to the API from the client side:
这是我从客户端连接到 API 的方式:
$processed = FALSE;
$ERROR_MESSAGE = '';
// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass"); // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);
// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);
if ($obj->{'code'} == '1')
{
$processed = TRUE;
}else{
$ERROR_MESSAGE = $obj->{'data'};
}
...
if (!$processed && $ERROR_MESSAGE != '') {
echo $ERROR_MESSAGE;
}
BTW, I also tried to use file_get_contents()
method as some of the users here suggested, but that din't work well for me. I found out the curl
method to be faster and more reliable.
顺便说一句,我也尝试使用file_get_contents()
这里的一些用户建议的方法,但这对我来说效果不佳。我发现这种curl
方法更快更可靠。
回答by deadrunk
回答by Chuan Ma
You can use file_get_contents
to issue any http POST/PUT/DELETE/OPTIONS/HEAD
methods, in addition to the GET
method as the function name suggests.
除了函数名称所暗示的方法之外,您还可以使用它file_get_contents
来发出任何 httpPOST/PUT/DELETE/OPTIONS/HEAD
方法GET
。
回答by Tobias
If you are using Symfony there's a great rest client bundle that even includes all of the ~100 exceptions and throws them instead of returning some meaningless error code + message.
如果您使用的是 Symfony,则有一个很棒的 rest 客户端包,它甚至包含所有 ~100 个异常并抛出它们而不是返回一些无意义的错误代码 + 消息。
You should really check it: https://github.com/CircleOfNice/CiRestClientBundle
你真的应该检查一下:https: //github.com/CircleOfNice/CiRestClientBundle
I love the interface:
我喜欢这个界面:
try {
$restClient = new RestClient();
$response = $restClient->get('http://www.someUrl.com');
$statusCode = $response->getStatusCode();
$content = $response->getContent();
} catch(OperationTimedOutException $e) {
// do something
}
Works for all http methods.
适用于所有 http 方法。
回答by d1jhoni1b
as @Christoph Winkler mentioned this is a base class for achieving it:
正如@Christoph Winkler 提到的,这是实现它的基类:
curl_helper.php
curl_helper.php
// This class has all the necessary code for making API calls thru curl library
class CurlHelper {
// This method will perform an action/method thru HTTP/API calls
// Parameter description:
// Method= POST, PUT, GET etc
// Data= array("param" => "value") ==> index.php?param=value
public static function perform_http_request($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
//curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
//curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
}
Then you can always include the file and use it e.g.: any.php
然后你总是可以包含文件并使用它,例如:any.php
require_once("curl_helper.php");
...
$action = "GET";
$url = "api.server.com/model"
echo "Trying to reach ...";
echo $url;
$parameters = array("param" => "value");
$result = CurlHelper::perform_http_request($action, $url, $parameters);
echo print_r($result)