bonuscred/rest-client

处理HTTP请求和响应的API客户端管理器

v1.1.1 2024-06-24 17:24 UTC

This package is auto-updated.

Last update: 2024-09-24 18:03:00 UTC


README

使用cURL进行HTTP请求管理的工具

安装

通过Composer安装此依赖。

composer require bonuscred/rest-client

使用

$req = new RestClient\Request;
$res = $req->get('https://api.github.com/repos/dnlfranklin/rest-client');

echo $res->getHeaderLine('content-type');
echo $res->get_http_code();
echo $res->get_data(); 

请求

方法

HTTP调用

所有HTTP调用都返回一个Response对象。

静态方法调用
$res = new RestClient\Request::run('https://api.github.com/repos/dnlfranklin/rest-client', 'GET'); // Objeto Response
回调钩子
$req = new RestClient\Request;

// Callback chamado em caso em requisições bem sucedidas
$req->onSuccess(function(Response $response){
    echo 'Success: '.$response->get_http_code();
});

// Callback chamado em caso de erro de requisição
$req->onError(function(Response $response){
    echo 'Error: '.$response->get_errmessage();
});

// Callback chamado após finalização de requisição
$req->onComplete(function(Response $response){
    echo $response->get_body();
});

$res = $req->get('https://api.github.com/repos/dnlfranklin/rest-client');

方法拼接

$req = new RestClient\Request;

$res_data = $req->baseUrl('https://api.github.com')
                ->buildIndexedQueries(true)
                ->requestFormat('json')
                ->responseFormat('json')
                ->userAgent('Minha API/1.0.0')
                ->onError(function(Response $response){
                    echo 'Error: '.$response->get_errmessage();
                })
                ->get('/repos/dnlfranklin/rest-client')
                ->get_data();            

响应

解码

目前支持json和xml作为自动解码,如果header(content-type)中或通过responseFormat()传递,则返回缩进数组。

$res = new RestClient\Request::run('https://api.github.com/repos/dnlfranklin/rest-client');

$data = $res->get_data(); // Array de atributos recebidos no formato json

可以通过回调进行格式化。

$res = new RestClient\Request::run('https://api.github.com/repos/dnlfranklin/rest-client');

$data = $res->decode(function($body){
    //Tratamento específico de decode
});

属性

可以直接通过属性或通过封装函数(get_)访问请求/响应的所有数据。以下为可用属性列表

要求

  • PHP 8.0或更高版本
  • libcurl包版本7.29.0或更高