Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best location in Laravel for third-party API connection

I'm writing a Laravel application using one or more third-party APIs when it suddenly dawned on me. Where is the best place within the Laravel application structure to set up the API connection to consume it from my Controller? Would you use a Service or put the logic somewhere else?

$this->api = new RestApi();
    ->setUrl(getenv('API_REST_URL'))
    ->setUsername(getenv('API_USERNAME'))
    ->setPassword(getenv('API_PASSWORD'))
    ->connect();
like image 371
Karl Hill Avatar asked Oct 30 '17 03:10

Karl Hill


2 Answers

Using services would be the better approach in Laravel, once your third party is not a direct route or content in your API, per se, it should not be in your Controller. You may want to use a Service with Guzzle.

like image 160
Valéria Barros Avatar answered Oct 27 '22 08:10

Valéria Barros


I think the best answer is that it depends on the size of your project and what you are doing.

This post lists 3 of the most common ways. I would go with Method 3 myself (Register the API with the service container), even for simple things. It abstracts it away nicely so should work best in all situations.

https://desertebs.com/laravel/how-to-consume-external-third-party-api-in-laravel-5

like image 38
fred Avatar answered Oct 27 '22 07:10

fred