Search code examples
laravelapiexternaljobs

Laravel how to deal with 120 calls to external apîs?


I am trying to figure how to use use multiple 120 calls on a paid apis 1 - should i store all response on db and call them from the db axcording to the connected user ? 2 - should i store all jsons on a folder and call them according to connected user ? I am confused about the way to deal with

When a user have valide subscription calls will be made to external apis as scheduled job


Solution

  • What you can do is cache the response you get from the paid API.

    $value = Cache::remember('cache-key', 'time-to-live-in-seconds', function () {
      // send request to paid api and return the data
    });
    

    Checkout the official docs (https://laravel.com/docs/9.x/cache#retrieving-items-from-the-cache).

    By default the cache driver is file, you can switch to redis or memcached if need be.

    Now what you need to understand is the cache key and time-to-live-in-seconds.

    1. Cache Key : This is the key Laravel will use to associate the cached data, so if the request is dependent on say, the logged in user, you can use the user id as the key here.
    2. Time to live in seconds : This tells how long the data should be cached. So you have to know how often the paid api changes so that you do not keep stale data for a long time.

    Now when you try to send a request, Laravel will first check if the data exists in cache, if it does, it will verify whether the data has expired based on time-to-live-in-seconds. It will return the cached data if its valid or send the paid api request and return the data if its not.