On my Laravel project (laravel version 9) I have to connect on a third part api using an apikey on the url and I have to get the response in json format.
To not having to repeat the same code over and over and over I’m trying to use the Http Client Macro for setting the base url, make sure I always get the response in JSON and add always the apikey to the url.
This api needs to get the apikey on the url like a query parameter something like this:
This is my macro function so far (this is at the AppServiceProvider.php):
/** * Bootstrap any application services. * * @return void */ public function boot() { Http::macro('materialservice', function () { return Http::baseUrl('https://demo.api')->acceptJson(); }); }
I have tried adding an options array at the end like this:
/** * Bootstrap any application services. * * @return void */ public function boot() { Http::macro('materialservice', function () { return Http::baseUrl('https://demo.api', ['key' => '123'])->acceptJson(); }); }
But this seems to not work as it’s not adding the api key to the url.
What I’m trying to do its that when I call the interceptor like this:
Http::materialservice()->get('/material?=3');
The macro should add the api to the url key like this:
https://demo.api/material=3&appid=123
For now it’s calling the correct url and I’m getting the response in JSON format but it’s not adding the apikey to the url.
I’ve checked the docs and couldn’t found any function to do this. Is there other function to achieve this?
Advertisement
Answer
I finnally found a solution.
On my macro I combine the query parameters of my request with a second one that contains the api key:
Http::macro('openweather', function ($options) { $options = array_merge($options, ['key' => '123']); return Http::baseUrl('https://demo.api')->withOptions(['query' => $options])->acceptJson(); });
And then on my controller I just run it with my query parameters:
$response = Http::openweather(['material' => '3'])->get('/data');