how to form an anonymous request to imgur's apiv3

  • Last Update :
  • Techknowledgy :

This is my working solution, at long last, for something that took me a day when I thought it'd take an hour at most:

def sideLoad(imgURL):
   img = urllib.quote_plus(imgURL)
req = urllib2.Request('https://api.imgur.com/3/image', 'image=' + img)
req.add_header('Authorization', 'Client-ID ' + clientID)
response = urllib2.urlopen(req)
response = json.loads(response.read())
return str(response[u 'data'][u 'link'])

In python 3.4 using urllib I was able to do it like this:

import urllib.request
import json

opener = urllib.request.build_opener()
opener.addheaders = [("Authorization", "Client-ID" + yourClientId)]
jsonStr = opener.open("https://api.imgur.com/3/image/" + pictureId).read().decode("utf-8")
jsonObj = json.loads(jsonStr)
#jsonObj is a python dictionary of the imgur json response.

Suggestion : 2

using imgur api v3 to upload images anonymously using php ,I am planning to upload images to imgur anonymously using its api, i registered my application in the anonymous upload category and got client id and client secret, How to use php to upload image to imgur and retrieve direct url to the image? can anyone suggest links to any example? this is what I have tried to do but i get the error "Fatal error: Maximum execution time of 30 seconds exceeded",This site uses cookies. We use them to improve the performance of our website and your interaction with it. Confirm your consent by clicking OK,programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

I am planning to upload images to imgur anonymously using its api, i registered my application in the anonymous upload category and got client id and client secret, How to use php to upload image to imgur and retrieve direct url to the image? can anyone suggest links to any example? this is what I have tried to do but i get the error "Fatal error: Maximum execution time of 30 seconds exceeded"

<?php

$client_id = :client_id; //put your api key here
$filename = "images/q401x74ua3402.jpg";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));

//$data is file data
$pvars   = array('image' => base64_encode($data), 'key' => $client_id);
$timeout = 30;
$curl    = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/upload.json');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
$xmlsimple = new SimpleXMLElement($xml);
echo '<img height="180" src="';
echo $xmlsimple->links->original;
echo '">';

curl_close ($curl);

?>
Copy code

Sending theclient_id in a post variable is the problem. It needs to be sent in the request header. Also, you're requesting a JSON response, but trying to parse it as XML.

<?php

$client_id = "FILLMEIN";
$image = file_get_contents("img/cool.jpg");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));

$reply = curl_exec($ch);
curl_close($ch);

$reply = json_decode($reply);
printf('<img height="180" src="%s" >', $reply->data->link);
Copy code

found the error, I need to send authorization details as header, eg code

< ? php
$client_id = 'xxxxxxxx';

$file = file_get_contents("test-image.png");

$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));

$curl = curl_init();

curl_setopt_array($curl, array(
   CURLOPT_URL => $url,
   CURLOPT_TIMEOUT => 30,
   CURLOPT_POST => 1,
   CURLOPT_RETURNTRANSFER => 1,
   CURLOPT_HTTPHEADER => $headers,
   CURLOPT_POSTFIELDS => $pvars
));

$json_returned = curl_exec($curl); // blank response
echo "Result: ".$json_returned;

curl_close($curl);

?
>
Copy code

Suggestion : 3

description and source-code_request = function (options) { var deferred = Q.defer(); request(options, function (err, res, body) { if (err) { deferred.reject(err); } else { deferred.resolve(res); } }); return deferred.promise; },example usage... }); ``` #### Creating an album: ```javascript imgur.createAlbum() .then(function(json) { console.log(json); }) .catch(function (err) { console.error(err.message); }); ...,description and source-codegetCredits = function () { var deferred = Q.defer(); imgur._imgurRequest('credits') .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; },description and source-codecreateAlbum = function () { var deferred = Q.defer(); imgur._imgurRequest('createAlbum', 'dummy') .then(function (json) { deferred.resolve(json); }) .catch(function (err) { deferred.reject(err); }); return deferred.promise; }

_getAuthorizationHeader = function() {
   var deferred = Q.defer();

   if (IMGUR_ACCESS_TOKEN) {
      deferred.resolve('Bearer ' + IMGUR_ACCESS_TOKEN);
   } else if (IMGUR_USERNAME && IMGUR_PASSWORD) {
      var options = {
         uri: 'https://api.imgur.com/oauth2/authorize',
         method: 'GET',
         encoding: 'utf8',
         qs: {
            client_id: IMGUR_CLIENT_ID,
            response_type: 'token'
         }
      };
      imgur._request(options).then(function(res) {
         var authorize_token = res.headers['set-cookie'][0].match('(^|;)[\s]*authorize_token=([^;]*)')[2];
         options.method = 'POST';
         options.json = true;
         options.form = {
            username: IMGUR_USERNAME,
            password: IMGUR_PASSWORD,
            allow: authorize_token
         };
         options.headers = {
            Cookie: 'authorize_token=' + authorize_token
         };
         imgur._request(options).then(function(res) {
            var location = res.headers.location;
            var token = JSON.parse('{"' + decodeURI(location.slice(location.indexOf('#') + 1)).replace(/"/g, '\\"').replace(/&/
               g, '","').replace(/=/g, '":"') + '"}');
            IMGUR_ACCESS_TOKEN = token.access_token;
            deferred.resolve('Bearer ' + IMGUR_ACCESS_TOKEN);
         }).catch(function(err) {
            deferred.reject(err);
         });
      }).catch(function(err) {
         deferred.reject(err);
      });
   } else {
      deferred.resolve('Client-ID ' + IMGUR_CLIENT_ID);
   }

   return deferred.promise;
}
n / a
_request = function(options) {
   var deferred = Q.defer();

   request(options, function(err, res, body) {
      if (err) {
         deferred.reject(err);
      } else {
         deferred.resolve(res);
      }
   });

   return deferred.promise;
}
clearClientId = function(path) {
   return imgur.saveClientId('', path);
}
...

if (commander.show) {

   console.log(imgur.getClientId());

} else if (commander.clear) {

   imgur.clearClientId()
      .fail(function(err) {
         console.error('Unable to clear client id (%s)', err.message);
      });

} else if (commander.save) {

   imgur.saveClientId(commander.save)
      ...