Solital has a component to manipulate the HTTP client, useful for consuming API and making HTTP requests.
Before, you will need to install the component using the command below:
composer require solital/http-client
To make basic use of the component, you will need to instantiate the HttpClient
class. Then, call the request
function, passing the method (GET, POST, ...) and the url as a parameter. Then return the data.
use Solital\HttpClient;
$client = new HttpClient();
$client->request("GET", "http://api.url.com");
$res = $client->toJson();
pre($res);
HttpClient supports the methods below.
You can return the answer in json, array or object. The methods below show an example.
$client = new HttpClient();
$client->request("GET", "http://api.url.com");
/** Return json */
$res = $client->toJson();
/** Return array */
$res = $client->toArray();
/** Return object */
$res = $client->toObject();
pre($res);
If you are using a POST or PUT request, for example, and need to send data to the HTTP header, you can pass an array with the values in the request
method.
$client = new HttpClient();
$res = $client->request("PUT", "http://api.url.com", [
'data' => 'your_data_values'
])->toJson();
echo $res;
By default, HttpClient has the following headers:
To add other headers to the request, use an array in the constructor on the instance.
$headers = [
'Content-Type: application/pdf'
];
$client = new HttpClient($headers);
#...
HttpClient by default does not perform SSL verification. To enable verification, use the enableSSL
method.
$client = new HttpClient();
$client->enableSSL();
#...
To perform authentication on an API that requires basic authentication, you can use the second parameter to inform the user and password. It is necessary to inform an array containing the indexes user
andpass
.
$client = new HttpClient(null, [
'user' => 'username',
'pass' => '123'
]);
$client->request("GET", "http://api.url.com");
$res = $client->toJson();
pre($res);
Basic authentication requires the username and password in the class constructor. If an index other than user
andpass
is informed, an exception will be thrown.
You can protect your routes through basic authentication as shown below.
use Solital\Http\Auth\HttpAuth;
$auth = new HttpAuth([
'user' => 'username',
'pass' => '123'
]);
$auth->basic();
In digest authentication, it is not necessary to inform anything in the constructor, just pass the allowed users with their respective passwords as a parameter in the digest
method.
use Solital\Http\Auth\HttpAuth;
$auth = new HttpAuth();
# 'username' => 'password'
$auth->digest(['admin' => 'pass1', 'admin2' => 'pass2', ...]);