'Reducing authentication calls on external API (Laravel 5.6)

My app requires data to be gathered from an external API.

  • I am using Guzzle.
  • My API methods are written into a separate class stored in a library folder.
  • I have a model and controller to use for connecting my app to the API and pulling information back into my database.

The API requires an authentication call to retrieve a token on each call. This is valid for 72 hours, however at the moment I make this call every time.

Are there any ways I can reduce the number of calls required without saving the token to a database?

I have seen tutorials around creating service providers for API's. Will this help my issue? Is there any need to create a service provider if a class is just being used from within a single model/controller and has few dependencies?

Can anyone offer some advice on best practice for laying out an REST api to external services in Larval 5?



Solution 1:[1]

There are a number of options you could take. I think my preference would be storing the token in Laravel's cache. With this option, you could provide it with an expiry time and you don't need to create any physical files yourself.

So you could do something like;

$seconds = 3600; // seconds (=> 1 hour) until it expires 
$value = Cache::remember('myToken', $seconds, function () {
    $token = some code to obtain the token ...
    return $token;
});

If 'myToken' doesn't exist, it will call the closure, otherwise it will return what you've already stored.

You could always save the token to a local file, but this would be slower than caching most likely, especially if you're caching using something like the redis driver.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 P.R.