在PHP中调用REST API

本文翻译自:Call a REST API in PHP

Our client had given me a REST API to which I need to make a PHP call to. 我们的客户给了我一个REST API,我需要对它进行PHP调用。 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. 但事实上,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? 是否有关于如何调用REST API或有关它的一些文档的正确信息? Because even on W3schools, they only describes the SOAP method. 因为即使在W3schools上,他们也只描述了SOAP方法。 What are different options for making rest API in PHP? 在PHP中制作rest API有哪些不同的选择?


#1楼

参考:https://stackoom.com/question/F89u/在PHP中调用REST-API


#2楼

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. 除了函数名称建议的GET方法之外,您还可以使用file_get_contents发出任何http POST/PUT/DELETE/OPTIONS/HEAD方法。

How to post data in PHP using file_get_contents? 如何使用file_get_contents在PHP中发布数据?


#3楼

Use Guzzle . 使用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". 它是一个“PHP HTTP客户端,可以轻松使用HTTP / 1.1并消除使用Web服务的痛苦”。 Working with Guzzle is much easier than working with cURL. 使用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

#4楼

You will need to know if the REST API you are calling supports GET or POST , or both methods. 您需要知道要调用的REST API是支持GET还是POST ,还是两种方法。 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. 下面的代码对我有用,我正在调用我自己的Web服务API,所以我已经知道API需要什么以及它将返回什么。 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. 它支持GETPOST方法,因此不太敏感的信息会进入URL (GET) ,而用户名和密码等信息则作为POST变量提交。 Also, everything goes over the HTTPS connection. 此外,一切都通过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. 顺便说一句,我也尝试使用file_get_contents()方法作为这里建议的一些用户,但这对我来说效果不错。 I found out the curl method to be faster and more reliable. 我发现curl方法更快更可靠。


#5楼

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,那么一个很棒的休息客户端捆绑包甚至包含所有~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方法。


#6楼

Use HTTPFUL 使用HTTPFUL

Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. Httpful是一个简单,可链接,可读的PHP库,旨在使HTTP健全。 It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client. 它允许开发人员专注于与API交互,而不是通过curl set_opt页面进行筛选,是一个理想的PHP REST客户端。

Httpful includes... Httpful包括......

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS) 可读的HTTP方法支持(GET,PUT,POST,DELETE,HEAD和OPTIONS)
  • Custom Headers 自定义标题
  • Automatic "Smart" Parsing 自动“智能”解析
  • Automatic Payload Serialization 自动有效负载序列化
  • Basic Auth 基本认证
  • Client Side Certificate Auth 客户端证书身份验证
  • Request "Templates" 请求“模板”

Ex. 防爆。

Send off a GET request. 发送GET请求。 Get automatically parsed JSON response. 获取自动解析的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";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值