Doing Http Requests from Laravel to an External API

Doing HTTP requests FROM Laravel to an external API

Based upon an answer of a similar question here:
https://stackoverflow.com/a/22695523/1412268

Take a look at Guzzle

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....

How to pass parameter in URL to external API using Http - Laravel

To add parameter to Http client:

$response = Http::::withHeaders($headers)->get($apiURL, [
'id' => $id,
'some_another_parameter' => $param
]);

As error said you don't have Description key for response array ($data). You have to foreach $data to access your desired key like:

 @foreach($data as $data)
<td>{{ $data['Description'] }}</td>
@endforeach

How to use Laravel's service provider for external API usage which utilizes user based credentials

I assume all of your application will be using this Client service. If so, you can keep using the singleton design pattern for it (to stop further oauth requests), but try to separate the logic from the provider register method. You can instanciate the Client class after calling a private method that returns a valid access_token (checks the DB / Cache if there's a valid token by the expires_in timestamp value and returns it, or requests a new one with the user client/secret and returns it)

    /**
* Register any application services.
*
* @return void
*/
public function register(): void
{
$this->app->singleton(Client::class, function () {
return new Client(
accessToken: $this->getUserToken()->access_token
);
});
}

/**
* Tries to get the user token from the database.
*
* @return ClientCredentials
*/
private function getUserToken(): ClientCredentials
{
$credentials = ClientCredentials::query()
->latest()
->find(id: auth()->user()->id);

if ($credentials === null || now() > $credentials->expires_at) {
$credentials = $this->requestUserToken();
}

return $credentials;
}

/**
* Requests a new token for the user & stores it in the database.
*
* @return ClientCredentials
*/
private function requestUserToken(): ClientCredentials
{
$tokenResponse = API::requestToken(
client: auth()->user()->client,
secret: auth()->user()->secret,
);

return ClientCredentials::query()->create(
attributes: [
'user_id' => auth()->user()->id,
'access_token' => $tokenResponse['access_token'],
'refresh_token' => $tokenResponse['refresh_token'],
'token_type' => 'Bearer',
'expires_at' => new DateTime(datetime: '+' . $tokenResponse['expires_in'] . ' seconds')
],
);
}


Related Topics



Leave a reply



Submit