Post local image file on tumblr via API with perl - perl

I've been messing around with the tumblr API with perl and have gotten several functions to work.
However, I can not get local image files to upload via perl.
Here is my code that works for URLs
use LWP::Authen::OAuth;
use JSON;
use Data::Dumper;
use strict;
my $ua = LWP::Authen::OAuth->new(
oauth_consumer_key => 'xxx',
oauth_consumer_secret => 'xxx',
oauth_token => 'xxx',
oauth_token_secret => 'xxx',
);
my $response;
$response = $ua->post( 'http://api.tumblr.com/v2/blog/mytumblr.tumblr.com/post', [
type => 'photo',
url => 'http://www.example.com/mypic.jpg' ,
caption => 'Test image 1',
]);
if ($response->is_success) {
print "it worked";
}
else {
print "it did not work \n \n \n \n";
print $response->as_string;
}
However, when i substitute "url" for "data" in the post parameters (as instructed in their API description here - http://www.tumblr.com/docs/en/api/v2#posting), I keep getting an error response from tumblr. I have tried several ways of entering the "data" parameter - as a path to the file, as a binary representation, as a URL encoded binary representation, as a url encoded base64 binary representation, stuck ech one of those values as a sole element in an array - I have tried all, and with each one I get a error message back from tumblr.
So, can someone please show me how to upload a local image file to tumblr?

I'm not entirely familiar with the tumblr API, but a quick googling found me this example: https://gist.github.com/derekg/1198576
I would try
$response = $ua->post( 'http://api.tumblr.com/v2/blog/mytumblr.tumblr.com/post', [
type => 'photo',
'data[0]' => $file_contents , ## LWP::Useragent should automatically urlencode this
caption => 'Test image 1',
]);
According to this answer https://stackoverflow.com/a/177866/810448, it's possible that "data[]" would also work in this situation.
I would also consider adding 'Content-type: application/x-www-form-urlencoded' to the request headers, if LWP::Useragent is not doing it already.

Related

POST request with multipart/form-data content type to download a file

There's a webpage which includes a button inside the form. Clicking on that button makes a POST request and a CSV file gets downloaded.
I'm trying to automate the CSV downloading process using LWP::UserAgent.
I noticed from Chrome Developer Tools that the Content-Type is multipart/form-data; boundary=---WebKitFormBoundary....
Any idea how can I send the exact Request Payload which developer tools is showing?
I generally do the below for x-www-form-urlencoded content type. But I have no idea how to submit multipart form data.
my $ua = LWP::UserAgent->new;
$ua->cookie_jar({ file => "cookie.txt", autosave => 1});
my $request = HTTP::Request->new('POST', $url);
#copy the form_data from chrome developer tools
my $form_data = 'key=val&key2=val2';
#the form_data is too big (and is in parts) in case of multipart content type
$request->content($form_data);
$request->header('Content-Type' => "application/x-www-form-urlencoded");
#I'll have to use `multipart/form-data; boundary=---WebKitFormBoundary....`
#add some other headers like 'Origin', 'Host' and 'Referer' in similar manner
#...
#...
push #{ $ua->requests_redirectable }, 'POST';
my $response = $ua->request($request);
#Get the file
Take a look at the entry on POST in the documentation for HTTP::Request::Common
You can generate a multipart/form-data request (instead of application/x-www-form-urlencoded) by passing a pseudo header value of Content_Type => 'form-data'
It would look like this
my $response = $ua->post(
$url,
Content_Type => 'form-data',
{
...; # Hash of form key/value pairs
}
);

I can't connect using an api

I'm quite new to API's so I don't know if this should be more straight forward.
I write the following perl script
use strict;
use LWP::UserAgent;
require HTTP::Request;
my $request = HTTP::Request->new(GET => 'http://api.elsevier.com/content/ev/results?apiKey=1234&query=stress&database=c&updateNumber=1&pageSize=1');
my $ua = LWP::UserAgent->new;
my $response = $ua->request($request);
then when I get my response and print it in the debugger I get the following
HTTP::Response=HASH(0x9aedff8)
'_content' => '{"service-error":{"status":{"statusCode":"AUTHENTICATION_ERROR","statusText":"Requestor configuration settings insufficient for access to this resource."}}}'
'_headers' => HTTP::Headers=HASH(0x9aedfe8)
'allow' => 'GET'
'client-date' => 'Wed, 29 Mar 2017 08:08:25 GMT'
'client-peer' => '198.185.19.118:80'
'client-response-num' => 1
'content-length' => 156
'content-type' => 'application/json;charset=UTF-8'
'date' => 'Wed, 29 Mar 2017 08:08:24 GMT'
'p3p' => 'CP="IDC DSP LAW ADM DEV TAI PSA PSD IVA IVD CON HIS TEL OUR DEL SAM OTR IND OTC"'
'server' => 'api.elsevier.com 9999'
'vary' => 'Origin'
'x-cnection' => 'close'
'x-els-apikey' => 'e688c9db4db0386581dbe4c4dda46164'
'x-els-reqid' => '0000015b190d89fe-a0d0'
'x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings insufficient for access to this resource.)'
'x-els-transid' => 'cbf787b4-d171-4e35-8237-8cab3c931205'
'x-re-ref' => '1 1490774904423414'
'_msg' => 'Forbidden'
'_protocol' => 'HTTP/1.1'
'_rc' => 403
'_request' => HTTP::Request=HASH(0x9fc3000)
'_content' => ''
'_headers' => HTTP::Headers=HASH(0x9ae73e0)
'user-agent' => 'libwww-perl/5.831'
'_method' => 'GET'
'_uri' => URI::http=SCALAR(0x9e25188)
-> 'http://api.elsevier.com/content/ev/results?apiKey=e688c9db4db0386581dbe4c4dda46164&query=stress&database=c&updateNumber=1&pageSize=1'
'_uri_canonical' => URI::http=SCALAR(0x9e25188)
-> REUSED_ADDRESS
one of the notable lines is
x-els-status' => 'AUTHENTICATION_ERROR(Requestor configuration settings insufficient for access to this resource.)'
I don't know how to get a proper response text. I tried searching their websites for examples, but I can't seem to get it. as well I'm not sure if the key is only for scopus but not engineering village which I'm trying to use.
There website is here. https://dev.elsevier.com/index.html?utm_expid=89327795-0.AtRZzToKQ2u1mZEyQ3n7OQ.0&utm_referrer=https%3A%2F%2Fdev.elsevier.com%2Ftecdoc_ev_retrieval_request.html
any help would be appreciated
To get the text out of your response, you need to call the $response->decoded_content method. That will give you the JSON string that you can see in _content in your debug output. I've indented it to make it easier to read.
{
"service-error" : {
"status" : {
"statusCode" : "AUTHENTICATION_ERROR",
"statusText" : "Requestor configuration settings insufficient for access to this resource."
}
}
}
You can use the JSON module to decode this into a Perl data structure.
use JSON 'from_json';
my $res = $ua->request($req);
my $json = from_json( $res->decoded_content );
The error message you get back clearly states that you are not authenticated properly. I've looked at this guide from the documentation you mentioned. It seems that the apiKey URL param works, if you have the right type of account. You should check with whoever made that account for you, or if that was you and you're not sure, the account manager at that service that is working with you. They'll tell you if you are using the right API key, and if this method of authentication works for you.
Since this API also offers to use a custom header X-ELS-APIKey: [apikey] for the authentication I would suggest using that. Your API key is a secret, and you shouldn't share it with anyone. It's like a password. If you put it into the URL, it might show up in log files. But as a header, it does usually not.
This is how you add a custom header to an HTTP request. Make sure you don't have the apiKey URL param any more if you do this.
my $req = HTTP::Request->new( GET => $url ); # no apiKey=123 here!
$req->header( 'X-ELS-APIKey' => 123 );
Now as a last step, you should check the HTTP response code of the response. A 200 (or most other codes that start with 2) means the request was successful. The 403 that you are getting back means unauthorized, which also hints at that you are not authenticated correctly.
Since it seems that this API returns JSON in both success and failure cases, you might need to decode it for both. If you care to examine the failure response, that makes sense. If not, you can skip that part. To do this, use $res->is_success, which is also used in the synopsis of the LWP::UserAgent documentation.
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON 'from_json';
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new( GET => 'http://api.elsevier.com/content/ev/results?query=stress&database=c&updateNumber=1&pageSize=1' );
$req->header( 'X-ELS-APIKey' => 123 );
if ($req->is_success) {
my $json = from_json( $res->decoded_content );
# ... do stuff with the response
} else {
# something went wrong
}

Transmitting POST-event to Google Calendar using Perl and Net::OAuth2

I'm developing a webapp in Perl and try to create events in user's Google Calendar with OAuth2. Authentication and requesting calendar-data is working fine, I'm just totally stuck when it comes to sending a POST-request and attaching JSON- or hash-data to it. Are there methods coming with the module for this? The documentation does not point me anywhere here.
I guess LWP would provide ways, but this seems like a lot of overhead.
Here is how i accomplished getting calendar-events so far (as a simple console-app for now):
use Net::OAuth2::Profile::WebServer;
my $auth = Net::OAuth2::Profile::WebServer->new
( name => 'Google Calendar'
, client_id => $id
, client_secret => $secret
, site => 'https://accounts.google.com'
, scope => 'https://www.googleapis.com/auth/calendar'
, authorize_path => '/o/oauth2/auth'
, access_token_path => '/o/oauth2/token'
, redirect_uri => $redirect
);
print $auth->authorize_response->as_string;
my $code=<STDIN>;
my $access_token = $auth->get_access_token($code);
my $response = $access_token->get('https://www.googleapis.com/calendar/v3/calendars/2j6r4iegh2u8o2409jk8k2g838#group.calendar.google.com/events');
$response->is_success
or die "error: " . $response->status_line;
print $response->decoded_content;
Thanks a lot for your time!
Markus
I guess it's time to answer my own question.
To transmit JSON in a POST-request (creating a calendar-event) I ended up using LWP::UserAgent and HTTP::Request. For setting the content-type I first had to create an HTTP::Request-object and set header and data:
my $req = HTTP::Request->new( 'POST', 'https://www.googleapis.com/calendar/v3/calendars/<calendarID>/events' );
$req->header( 'Content-Type' => 'application/json' );
$req->content( "{ 'summary': 'EventName', 'start': { 'dateTime': '2015-02-11T20:48:00+01:00' }, 'end': { 'dateTime': '2015-02-11T22:30:00+01:00' } }" );
Then I created an LWP::UserAgent-object, appended the OAuth2-token to it and let it fire the request:
my $apiUA = LWP::UserAgent->new();
$apiUA->default_header(Authorization => 'Bearer ' . $access_token->access_token() );
my $apiResponse = $apiUA->request( $req );
It's that simple. Would've been a lot nicer to do this all-in-one with Net::OAuth2, though.

Youtube API: Resume Upload *User Authentication Required*

Im very tired, three days without sleep and Im stuck at 1 thing,
this youtube upload thing.
this very simple POST procedure always leads to : "User Authentication Required"
this is what Im emulating:
POST /resumable/feeds/api/users/default/uploads HTTP/1.1
Host: uploads.gdata.youtube.com
Authorization: Bearer ACCESS_TOKEN
GData-Version: 2
X-GData-Key: key=adf15ee97731bca89da876c...a8dc
Content-Length: 0
Slug: my_file.mp4
so far this is what ive done:
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use LWP::Simple;
my $r = LWP::UserAgent->new()->post(
"https://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads",
Content_Type => "application/atom+xml; charset=UTF-8",
[
'POST /resumable/feeds/api/users/default/uploads HTTP/1.1',
Host => "uploads.gdata.youtube.com",
'Authentication' => "Bearer xxxxxx",
'GData-Version' => "2",
'X-GData-Key' => "key=xxxxx",
Content_Length => "0",
'Slug' => "C:/YouTube.wmv",
]
);
say $r->content;
I tried every Authentication, Oath2, clientLogin,
I can login and get access_token, problem is I can't upload,
I love perl and i hate the fact that there are no support libraries for youtube using perl (there is, but its extremely outdated and direct upload function is not clearly documented or maybe non at all)
please help me, i need this badly and Im really stuck at this, I don't know if the problem is in my part, or youtube's.
Thank you for taking the time to read this, really appreciate it.
Looks to me like you're using the wrong syntax for your call to post().
The documentation isn't really clear, but I think you want something like this:
my $r = LWP::UserAgent->new()->post(
'https://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads',
Content_Type => "application/atom+xml; charset=UTF-8",
[
Host => "uploads.gdata.youtube.com",
'Authentication' => "Bearer xxxxxx",
'GData-Version' => "2",
'X-GData-Key' => "key=xxxxx",
Content_Length => "0",
'Slug' => "C:/YouTube.wmv",
]
);
You don't need that line which explicitly calls POST(). The post() method does that does that for you.

Perl HTTP Request POST fails with TeamCity REST API

I've got a perl script backing up our TeamCity server via the REST API as follows:
use strict;
use LWP::UserAgent;
use HTTP::Request::Common qw{ POST GET }
# ... code ommitted for brevity ... #
my $url = 'http://teamcity:8080/httpAuth/app/rest/server/backup';
my $req = POST( $url . '?includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=' . $filename);
$req->authorization_basic($username, $password);
my $resp = $ua->request($req);
I tried posting the content more in line with the documentation for HTTP:Request, but for some reason it fails, complaining that I haven't specified a file name:
# This fails
my $req= POST( $url, [ 'includeConfigs' => 'true',
'includeDatabase' => 'true',
'includeBuildLogs' => 'true',
'fileName' => $filename,
] );
Yet, when I look at the backend REST log for TeamCity, the full request seems to have made it intact, and is identical to the one that passes above.
Log of successful command:
[2012-12-13 15:02:38,574] DEBUG [www-perl/5.805 ] - rver.server.rest.APIController - REST API request received: POST '/httpAuth/app/rest/server/backup?includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=foo', from client 10.126.31.219, authenticated as jsmith
Log of failed command:
[2012-12-13 14:57:00,649] DEBUG [www-perl/5.805 ] - rver.server.rest.APIController - REST API request received: POST '/httpAuth/app/rest/server/backup?includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=foo', from client 10.126.31.219, authenticated as jsmith
Is there any other hidden difference between the two methods of making a POST request that could be causing the failure?
UPDATE: Here is the result of each request when printed via Data::Dumper
Successful POST:
$VAR1 = bless( {
'_content' => '',
'_uri' => bless( do{\(my $o = 'http://teamcity:8080/httpAuth/app/rest/server/backup?includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=foo')}, 'URI::http' ),
'_headers' => bless( {
'content-type' => 'application/x-www-form-urlencoded',
'content-length' => 0,
'authorization' => 'Basic c3lzQnVpbGRTeXN0ZW1JOnBhaWQuZmFpdGg='
}, 'HTTP::Headers' ),
'_method' => 'POST'
}, 'HTTP::Request' );
Unsuccessful POST:
$VAR1 = bless( {
'_content' => 'includeConfigs=true&includeDatabase=true&includeBuildLogs=true&fileName=foo',
'_uri' => bless( do{\(my $o = 'http://teamcity:8080/httpAuth/app/rest/server/backup')}, 'URI::http' ),
'_headers' => bless( {
'content-type' => 'application/x-www-form-urlencoded',
'content-length' => 75,
'authorization' => 'Basic c3lzQnVpbGRTeXN0ZW1JOnBhaWQuZmFpdGg='
}, 'HTTP::Headers' ),
'_method' => 'POST'
}, 'HTTP::Request' );
I think your server-side script can only handle GET parameters encoded in the URL, not POST data transmitted via standard intput. Note that there are several different methods described by HTTP, these are GET, POST, HEAD, DELETE etc. And then there are two ways of passing data to an application on the server. Most often one of those ways is also called GET parameters and the other one is called POST data because the GET parameters are usually used with the HTTP GET method and POST data is usually used for the HTTP POST method. However, they don't have to. And I think you're mixing up the HTTP POST method with GET parameters in the successful case and with POST data in the unsuccessful case.
GET parameters are passed via the URL by, most often by appending ? to the URL followed by the actual key/value pais. Those are available via certain environment varialbes to the script running on the server. It's up to the script to split the variables at the &, split key/value pairs on = and undo the escaping.
For POST data the environment variable CONTENT_LENGTH tells the script how many bytes to read from its standard input. The actual key/value pairs are transmitted via a different encoding, usually as multipart encoded content. Yes, POST HTTP requests (mostly from HTML <form>s) can also be sent URL-encoded like GET parameters, but there's a length limit imposed by the HTTP standard on the URLs including all parameters. Hence the method of transferring the data via standard input, and not via the URL.
Now it looks like your server-side script can evaluate URL-encoded parameters (aka. GET parameters) parameters but not data posted to it via standard input. Even though you use the POST HTTP method/verb you don't actually transmit the values as POST data via standard input in your successful case. You could simply swap POST(...) for GET(...) in that case and it should still work.
In your unsuccessful case you use the POST HTTP method and the POST data way of transmitting the values.
My verbiage here may be wrong in cases, but the fundamentals should still be OK.
my $url= my $url = 'http://teamcity:8080/httpAuth/app/rest/server/backup';
my $req= POST( $url, { 'includeConfigs' => 'true',
'includeDatabase' => 'true',
'includeBuildLogs' => 'true',
'fileName' => $filename,
} );
Note the '{}' (hash ref, not array ref). Also not mixing the Query String (GET) syntax with the POST syntax goes a long way towards clarifying the issue.
Cheers.