$client = new GuzzleHttp\Client(['base_url' => 'https://github.com']);
// Send a request to https://github.com/notifications
$response = $client->get('/notifications');
using Laravel 7's HTTP Client ? Or would the only way to achieve this using Laravel's HTTP Client is to build my own service class that handles it?
I want to be able to always have common headers set for every request to a particular client without needing to set them every time. I don't want to have to set withHeaders for every request to a specific client, for example:
Yeah I had seen that in the docs earlier. However, I don't think it gives me what I'm trying to achieve.
It looks as though withOptions still needs to be set on every request.
What I was hoping for was something where I could set common headers in a Service Provider for example and then those headers would always be attached to any request made throughout the application.
For example:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Http;
class HttpServiceProvider extends ServiceProvider
{
public function boot()
{
Http::defaults([
'headers' => [
'X-API-Key' => <api-key>,
'accept' => 'application/json, text/plain, */*'
]
]);
}
}
and then anywhere in the application where I call Http::get() it'll automatically attach those default headers.
Or perhaps withOptions gives that ability?
@getupkid203 Unpacking this... Your first question isn't related to the second part? ...and your question is not Guzzle vs. Laravel Http Client specific, right? You are just wondering how you would do this in general? Or, do have have a solution to this in Guzzle that has worked and you are trying to see how it is done in Laravel with the Http Client layer?
If you have an example of how you are currently doing this I could probably help modify the approach.
From my understanding you can't pass configuration options to Guzzle without already having an instantiation of the client. That said, yes you'd probably need service provider or trait or something to new up the instance with the header options you want to make this happen. Actually, that is your best bet I think.
If you want to dive into the available methods on Http Client's requests look here...
vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php
@fylzero sorry for the confusion haha. It was basically just general knowledge i.e. wondering if it could be done. But the more I think about it, the more I realise that it's not a really good idea to do. If you had 3 or 4 clients to access data from different APIs then yeah, setting global headers would be pointless. So yes, I think going the service provider approach is the best solution.