Third-party API requests

I’m developing an API and I got to a part of the system where I need to use a third party API. The idea is to use axios for this, the doubt is - what would be the best way to work having to request several url from third party endpoints?

A Service Provider responsible for these requests, a helper, etc …

Do you mean you want a wrapper that would wrap and encapsulate for you the details of axios calls to http://some.thirdparty.api.com?

So that you could call it like this?:

const thirdpartyAPI = use('ThirdpartyAPI');
const response = await thirdpartyAPI.post(/*some request data*/);
// here do things with response

If so then architecturally this piece of code would be a layered architecture application service - see Layering after the mid 90s section in a form of a Facade design pattern.

Under DDD’s Hexagonal (ports & adapters) Architecture this piece of code would be an outgoing adapter for HTTP port in the same Facade form.

As for code design, in more generic case, if the facade were more complicated then just wrapping Axios object, the code would live in a separate module somewhere in your-adonis-api/services/facades/http/ThirdPartyAPIFacade.js if implemented under layered architecture. Or in your-adonis-api/domain-driven/ports/adapters/outgoing/http/ThirdPartyAPIFacade.js module if implemented under DDD’s ports & adapters approach.

In the case of Axios wrapper the facade is quite short so that it can live unserparated within a service provider like this:

// in 'your-adonis-api/providers/YourAdonisAPIServiceProvider.js'
register() {
    const Config = this.app.use('Adonis/Src/Config')
    this.app.singleton('ThirdPartyAPIFacade', () => {
        const axiosInstance = axios.create({
            baseURL: 'http://some.thirdparty.api.com',
            timeout: 1000,
            // Depending on how the authentication is organized on the API side;
            headers: { 'Api-Token': 'third-party-api-token' } 
        });
        return axiosInstance;
    });
}

Then you would use it somewhere like in the topmost code snippet.

Of course you would have to create and register the service provider (see IoC Container and Service Providers) YourAdonisAPIServiceProvider beforehand.

1 Like