How to prevent too many api calls?

So I’ve just completed local weather app using freecodecamp’s weather api. FCC’s api seemed buggy (Shuzengi city showing half of the time) but still at least it had no api calls limit apparently.

Well I was searching for other APIs and I saw that most show a limit on how many API calls you can do before rejecting any further API requests. Assuming I used one of these APIs, what would be a good method to prevent unnecessary API requests. (for example if someone visits from London and my app fetch’s London’s weather for the given hour, then someone else visits from London the SAME hour, my app would fetch London’s weather data again, but it wasn’t necessary if I knew a way to prevent it).

For example,
If I’m making a prayer timing app.
Prayer times only need to be updated once everyday.
Someone from a particular area visits my app.
I fetch data of that area. Since I don’t need to update the data of this area for another 24 hours. If someone is from same area, How can my app show this same data without the need for making an API call.

You would probably need a database (redis could be used as well.) And each time a request comes, look at the data stored in the database. You could store a timestamp for an expiration date. Then a simple conditional logic, if the data is stale hit the API, else database data is ok to use.

1 Like

Thanks. :slight_smile: btw can I do something like this (connect to database and work with it) in codepen?

No, but Glitch is a good alternative. And mLab offers a free tier for MongoDB.

Of course, you can develop the project on your local machine and then host it on Now or Heroku.

1 Like

Got it. Thank you so much sir :slight_smile:

1 Like

as @Implaier said if you have your own database and backend you could cache similar calls to prevent hitting the API for every user.
Ontop of this or alternatively you could cache the request on the user’s device daily using localStorage so if the user comes back into the app in the same “day” you can show them the cached data without calling your own backend, further preventing extra calls.

LocalStorage would allow you to save the actual data with a timestamp/date which can be compared with the current date and time. If its still the same day as the previous value you can just use the cached value. If it isn’t, then clear the local storage, call the API again and save the response for any subsequent calls during the day. This wouldn’t be as efficient as the database method, but is a lot easier and only requires a front-end todo.

1 Like