在PHP中调用REST API [英] Call a REST API in PHP

查看:350
本文介绍了在PHP中调用REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的客户给了我一个REST API,而我需要做一个PHP调用。但作为事实上的API提供的资料非常有限,所以我真的不知道如何调用该服务。

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.

我试图谷歌,但想出的唯一的事情就是一个已经过期如何调用该服务的Yahoo!教程。不提的深度信息的报头或任何东西。

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.

有没有解决如何调用REST API,或关于它的一些文件什么像样的信息?因为即使在W3Schools的,他们只描述了SOAP方法。什么是使REST API在PHP中不同的选项?

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?

推荐答案

您可以访问PHP的卷曲扩展的REST API。然而,API文档(方法,参数等),必须由您的客户提供!

You can access any REST API with PHPs cURL Extension. However, the API Documentation (Methods, Parameters etc.) must be provided by your Client!

例如:

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

这篇关于在PHP中调用REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆