首页 文章

在PHP中调用REST API

提问于
浏览
256

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

我试过谷歌它,但唯一出现的是已经过期的雅虎!关于如何调用服务的教程 . 没有提到 Headers 或任何深度信息 .

是否有关于如何调用REST API或有关它的一些文档的正确信息?因为即使在W3schools上,他们也只描述了SOAP方法 . 在PHP中制作rest API有哪些不同的选择?

12 回答

  • 4

    您可以使用POSTMAN,这是一个简化API的应用程序 . 填写请求字段,然后它将以不同的语言为您生成代码 . 只需点击右侧的代码,然后选择您喜欢的语言 .

  • 9

    正如@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)
    
  • 146

    如果你有一个网址并且你的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

  • 1

    您需要知道要调用的REST API是否支持 GETPOST ,或两种方法 . 下面的代码对我有用,我正在调用我自己的Web服务API,所以我已经知道API需要什么以及它将返回什么 . 它支持 GETPOST 方法,因此不太敏感的信息会进入 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() 方法作为这里建议的一些用户,但这对我来说效果不错 . 我发现 curl 方法更快更可靠 .

  • 3

    如果您愿意使用第三方工具,请查看此工具: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();
    
  • 1

    使用Guzzle . 这是"PHP HTTP client that makes it easy to work with HTTP/1.1 and takes the pain out of consuming web services" . 使用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
    
  • 4

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

    您可以使用PHP cURL Extension访问任何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;
    }
    
  • 126

    如果您正在使用Symfony,那么一个很棒的休息客户端包甚至包含所有~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方法 .

  • 1

    除了函数名称建议的 GET 方法之外,您还可以使用 file_get_contents 发出任何http POST/PUT/DELETE/OPTIONS/HEAD 方法 .

    How to post data in PHP using file_get_contents?

  • 15

    实际上有很多客户 . 其中一个是Pest - 看看这个 . 请记住,这些REST调用是使用各种方法的简单http请求:GET,POST,PUT和DELETE .

  • 348

    使用HTTPFUL

    Httpful是一个简单,可链接,可读的PHP库,旨在使HTTP健全 . 它允许开发人员专注于与API交互,而不是通过curl set_opt页面进行筛选,是一个理想的PHP REST客户端 .

    Httpful包括......

    • 可读的HTTP方法支持(GET,PUT,POST,DELETE,HEAD和OPTIONS)

    • 自定义 Headers

    • 自动"Smart"解析

    • 自动有效负载序列化

    • Basic Auth

    • 客户端证书验证

    • 索取"Templates"

    防爆 .

    Send off a GET request. Get automatically parsed JSON response.

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

相关问题