tags:

views:

28

answers:

3

Reading it at http://blog.programmableweb.com/2007/04/02/12-ways-to-limit-an-api/ I wondered how to accomplish time based limits (ie. 1 call per second). Well, if authentication required, the way is to compare the seconds tracked by PHP's time function (for instance, if ($previous_call_time == $current_call_time) { ... })? Any other suggestions?

A: 

Use a simple cache:

if(filemtime("cache.txt") < (int)$_SERVER["REQUEST_TIME"] - 3600) { // 3600 is one hour in seconds
    $data = file_get_contents("http://remote.api/url/goes/here");
    file_put_contents("cache.txt", $data);
} else
    $data = file_get_contents("cache.txt");

Something like this will save the value of the API and let you get the information whenever you want while still limiting how often you actually pull date from the feed.

Hope this helps!

mattbasta
A: 

The more general limitations criteria is "number of calls per 'period'". For example - per hour, like twitter does.

You can track number of currently performed requests by adding a record to mysql for each request.

The more performant solution in this way is to use memcached and to increment the "key" (user_id + current_hour).

zerkms
A: 

Something to consider: You can use an external service to do this instead of building it yourself. E.g. my company, WebServius ( http://www.webservius.com ) currently supports configurable per-API and per-API-key throttling, and we are likely going to be adding even more features such as "adaptive throttling" (automatically throttle usage when API becomes less responsive).

Eugene Osovetsky