Best location in Laravel for third-party API connection
Asked Answered
H

2

6

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();
Hilmahilt answered 30/10, 2017 at 3:8 Comment(2)
Service ContainerInsipience
The above code should live in a Model class that is instantiated using a custom ServiceProvider that is then added to the service container. You ultimately consume it in a Controller Class. Don't worry if that sounds confusing. It's a lot of abstraction and takes awhile to get a handle on if you are not familiar with the laravel way of doing things.Ferromagnetic
F
1

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

Ferromagnetic answered 28/6, 2020 at 17:26 Comment(0)
A
3

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.

Archibold answered 4/3, 2018 at 20:20 Comment(2)
Any good reference for the proper way todo this? There are several articles, such as jeffochoa's article on medium and dylanjpierce's article on his blog but none of them really dive into a complete example of creating a service/provider for use with a general end point. Didnt feel this needed its own question here, but maybe it does?Legman
I don't think so. All the articles that you pointed answer the bases of how to structure the service in different ways (there's no accuracy to point which is the best - it depends of your problem) Try to keep it simple, you only need a interface for services/providers (like with HTTP verbs methods) and your application will not handle the request, the service will.Monoplane
F
1

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

Ferromagnetic answered 28/6, 2020 at 17:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.