我们的客户端给了我一个REST API,我需要对它进行PHP调用。但事实上,API提供的文档非常有限,所以我真的不知道如何调用该服务。

我试着谷歌它,但唯一出现的是一个已经过期的雅虎!关于如何调用服务的教程。不要提及标题或任何深入的信息。

是否有关于如何调用REST API的适当信息或相关文档?因为即使在w3学校中,它们也只描述SOAP方法。在PHP中创建API的其他选项有哪些?


你可以通过php的cURL扩展访问任何REST API。但是,API文档(方法,参数等)必须由您的客户端提供!

例子:

// 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;
}

如果你有一个url并且你的php支持它,你可以调用file_get_contents:

$response = file_get_contents('http://example.com/path/to/api/call?param1=5');

如果$response是JSON,使用json_decode将其转换为php数组:

$response = json_decode($response);

如果$response是XML,使用simple_xml类:

$response = new SimpleXMLElement($response);

http://sg2.php.net/manual/en/simplexml.examples-basic.php

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);

实际上有很多客户。其中之一是佩斯,看看这个。请记住,这些REST调用是简单的http请求,具有各种方法:GET、POST、PUT和DELETE。

您可以使用file_get_contents来发出任何http POST/PUT/DELETE/OPTIONS/HEAD方法,除了函数名所示的GET方法之外。

如何在PHP中使用file_get_contents发布数据?

使用狂饮。它是一个“PHP HTTP客户端,可以很容易地使用HTTP/1.1,并消除使用web服务的痛苦”。使用Guzzle比使用cURL要容易得多。

下面是来自该网站的一个例子:

$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

您需要知道所调用的REST API是支持GET还是POST,还是同时支持两种方法。下面的代码对我来说是有用的,我正在调用我自己的web服务API,所以我已经知道API需要什么以及它将返回什么。它同时支持GET和POST方法,因此不太敏感的信息会进入URL (GET),而像用户名和密码这样的信息会作为POST变量提交。此外,所有内容都通过HTTPS连接。

在API代码中,我将一个数组编码为json格式,然后简单地使用PHP命令echo $my_json_variable使json字符串对客户端可用。

如您所见,我的API返回json数据,但您需要知道(或查看返回的数据以找出)API响应的格式。

这是我如何从客户端连接到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;
}

顺便说一句,我还尝试使用file_get_contents()方法,因为这里的一些用户建议,但这并不适合我。我发现旋度法更快更可靠。

如果您正在使用Symfony,有一个很棒的rest客户端包,它甚至包含了所有~100个异常,并抛出它们,而不是返回一些毫无意义的错误代码+消息。

你真的应该检查一下: https://github.com/CircleOfNice/CiRestClientBundle

我喜欢它的界面:

try {
    $restClient = new RestClient();
    $response   = $restClient->get('http://www.someUrl.com');
    $statusCode = $response->getStatusCode();
    $content    = $response->getContent();
} catch(OperationTimedOutException $e) {
    // do something
}

适用于所有http方法。

使用HTTPFUL

Httpful是一个简单的,可链接的,可读的PHP库,旨在使HTTP说话正常。它让开发人员专注于与api的交互,而不是筛选curl set_opt页面,是一个理想的PHP REST客户端。

Httpful包括……

可读HTTP方法支持(GET, PUT, POST, DELETE, HEAD和OPTIONS) 自定义标题 自动“智能”解析 自动负载序列化 基本认证 客户端证书认证 请求“模板”

Ex.

发送一个GET请求。获得自动解析的JSON响应。

库注意到响应中的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";

如果你愿意使用第三方工具,你可以看看这个: https://github.com/CircleOfNice/DoctrineRestDriver

这是一种使用api的全新方式。

首先,你定义了一个实体,它定义了传入和输出数据的结构,并用数据源注释它:

/*
 * @Entity
 * @DataSource\Select("http://www.myApi.com/products/{id}")
 * @DataSource\Insert("http://www.myApi.com/products")
 * @DataSource\Select("http://www.myApi.com/products/update/{id}")
 * @DataSource\Fetch("http://www.myApi.com/products")
 * @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
 */
class Product {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

现在,与REST API进行通信非常容易:

$product = new Product();
$product->setName('test');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();

$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();

正如@Christoph Winkler提到的,这是实现它的基类:

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;
}

}

然后你就可以包含这个文件并使用它,例如: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)

使用Postman,您可以为大多数语言(包括PHP)生成调用API的代码。以下是步骤:

步骤1

使用Postman UI来指定你的API调用规范,即URL,方法,头,参数,主体等。

步骤2

在最右边,有一个小按钮,您可以通过它查看生成的代码。

步骤3

从下拉菜单中选择您喜欢的语言(和库),然后就可以开始了!