kkedzierski / rest-api-client
Rest Api 客户端库,用于发送 HTTP 请求并检索响应
1.0
2022-01-01 16:10 UTC
Requires (Dev)
- phpunit/phpunit: 9.5
This package is auto-updated.
Last update: 2024-09-29 06:08:43 UTC
README
库用于发送 HTTP 请求并检索响应对象
安装
要在其他项目中使用库,请在控制台编写
composer install
composer require kkedzierski/rest-api-client
用法
安装后,在文件顶部编写 composer requirements 以使用库
use RestApiClient\RestApiClient;
require_once __DIR__ . './vendor/autoload.php';
并创建具有基本 URI 的类的实例
例:
$RAC = new RestApiClient("https://api.github.com");
要添加到头部,请使用 addToHeader 方法,方法接受两个参数 类型 和 值
例:
$rac->addToHeader("User-Agent", "Test REST API Client");
要添加额外的参数,如 GET 或头部,请创建数组并将此数组作为请求方法的参数添加
例:
$additonalParamArr = [
"header" =>
["User-Agent: Test REST API Client",
"Authorization: token api_token"]
];
使用 get、post、put、patch、delete 方法进行 HTTP 请求
例:
$response = $RAC->get('/user/repos');
要指定 GET、PUT、PATCH 或 DELETE 方法的端点,您可以使用参数值参数
例:
$response = $RAC->get('/user/:id/repos', 123);
GET 方法参数
- 字符串 $resource 必须以 "/" 开头,例如 /products 或 /products/:id
- 字符串|int $parameterValue 如果资源中指定,则参数是必需的,默认 = ''
- 数组|null $additionalField 例如 header,默认 = null
POST 方法参数
- 字符串 $resource 必须以 "/" 开头,例如 /products 或 /products/:id
- 数组 $postData 要发送的数据
- 数组|null $additionalField 例如 header,默认 = null
PUT 和 PATCH 方法参数
- 字符串 $resource 必须以 "/" 开头,例如 /products 或 /products/:id
- 字符串|int $parameterValue 如果资源中指定,则参数是必需的,默认 = ''
- 数组 $updateData 要更新的数据
- 数组|null $additionalField 例如 header,默认 = null
DELETE 方法参数
- 字符串 $resource 必须以 "/" 开头,例如 /products 或 /products/:id
- 字符串|int $parameterValue 如果资源中指定,则参数是必需的,默认 = ''
- 数组|null $additionalField 例如 header,默认 = null
每个方法都返回带有方法的响应对象
- getUrl();
- getStatusCode();
- getHeader();
- getHeaderLine(string);
- getBody();
- getContent();
Rest Api Clinet 对象具有其他方法
- getUrl();
- getHeader();
- getHeaderLine(string);
示例用法
<?php
use RestApiClient\RestApiClient;
require_once __DIR__ . './vendor/autoload.php';
$RAC = new RestApiClient("https://api.github.com");
$additonalParamArr = [
"header" =>
["User-Agent: Test REST API Client",
"Authorization: token api_token"]
];
$response = $RAC->get('/user/repos', additionalField: $additonalParamArr);
// or
// $rac->addToHeader("User-Agent", "Test REST API Client");
// $rac->addToHeader("Authorization", "token api_token");
// $response = $RAC->get('/user/repos');
$response->getUrl();
$response->getStatusCode();
$response->getHeader();
$response->getHeaderLine("user-agent");
$response->getBody();
$response->getContent();