So far I have come up with this:
use GuzzleHttp\Client;
class RestAPI
{
protected $url;
Protected $accessToken;
protected $client;
protected $headers;
public function __construct(Client $client)
{
$this->url = 'https://gorest.co.in/public-api/';
$this->accessToken = env('GOREST_ACCESS_TOKEN');
$this->client= $client;
$this->headers = [
'cache-control' => 'no-cache',
'content-type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Bearer ' . $this->accessToken,
];
}
public function getRequest(string $uri = null, array $query = [])
{
$full_path = $this->url;
$full_path .= $uri
$request = $this->client->get($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
'query' => $query
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
public function postRequest(string $uri = null, array $post_params = [])
{
$full_path = $this->url;
$full_path .= $uri;
$request = $this->client>post($full_path, [
'headers' => $this->headers,
'timeout' => 30,
'connect_timeout' => true,
'http_errors' => true,
'form_params' => $post_params,
]);
$response = $request ? $request->getBody()->getContents() : null;
$status = $request ? $request->getStatusCode() : 500;
if ($response && $status === 200 && $response !== 'null') {
return (object) json_decode($response);
}
return null;
}
Ok how is this looking? Could it be done better?