tumblr / tumblr.php

Tumblr API v2 PHP Client
Apache License 2.0
407 stars 115 forks source link

RATE LIMITING HEADERS #93

Open AnonDev1312 opened 6 years ago

AnonDev1312 commented 6 years ago

Using this library how can I get the rate limiting headers

x_ratelimit_api_followers_limit x_ratelimit_api_followers_remaining x_ratelimit_api_followers_reset

thanks

jasonpenny commented 6 years ago

It doesn't look like there's a built-in way to get these values, but you can get them by overriding the requestHandler

<?php
require_once 'vendor/autoload.php';

class RequestHandlerInterceptor extends Tumblr\API\RequestHandler {
    public $rateLimits;

    public function request($method, $path, $options) {
        $result = parent::request($method, $path, $options);

        $this->rateLimits = array();
        foreach ($result->headers as $key => $value) {
            if (substr($key, 0, 6) === 'X-Rate') {
                $this->rateLimits[$key] = $value[0];
            }
        }

        return $result;
    }
}

list($consumerKey, $consumerSecret, $token, $secret) = array(
    '...',
    '...',
    '...',
    '...',
);
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$client->requestHandler = new RequestHandlerInterceptor();
$client->requestHandler->setConsumer($consumerKey, $consumerSecret);
$client->requestHandler->setToken($token, $secret);

$unused = $client->getFollowedBlogs();
//var_dump($unused);
//echo "\n";

echo "---------------------------------------\n";
printf(
    "API Requests Daily Limit:                   %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Perday-Limit']
);
printf(
    "API Requests Remaining Today:               %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Perday-Remaining']
);
echo "---------------------------------------\n";
printf(
    "API Requests Hourly Limit:                  %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Perday-Limit']
);
printf(
    "API Requests Remaining This Hour:           %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Perday-Remaining']
);
echo "---------------------------------------\n";
printf(
    "Following API Requests Hourly Limit:        %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Api-Following-Limit']
);
printf(
    "Following API Requests Remaining This Hour: %s\n",
    $client->requestHandler->rateLimits['X-Ratelimit-Api-Following-Remaining']
);