02/22/2015 8:24 PM
post4270
|
It took me a little while to figure out how to connect to the new server successfully in Perl. Some of this may be
useful in other languages/tools, especially if you had a script that was working with the previous test server and you
need to update for the new test server.
First, you have to encode your user name and authorization token and add it to the request headers. When I read the API
document, it said to separate the user name and authorization token with a semicolon, but it actually needs a colon
(which was correct in the example and has been fixed in the text), then it needs to be base64 encoded.
If you just pass the string to the encode_base64 function, it appends a linefeed at the end of the encoded string, which
creates an invalid header line. So you have to pass a second parameter to specify an empty string for the end-of-line.
When you set the default header for the encoded Authorization token, note also that the type of authorization parameter
is now Basic (it was Token for the previous test server).
Next you need to get the correct URL. The email just listed the server, but all of the request URLs have to have /api/v1
.0 appended before the other request parameters. This is specified in the latest API document, and the version field was
added after the email went out.
Finally, the staging server doesn't have a proper certificate, so the HTTPS request will fail. To disable the
certificate check, you need to set an environment variable. NOTE: be sure to remove this when we get the production
server with a properly signed certificate or you'll be vulnerable to a man-in-the-middle attack.
I like JSON, so I also add a default header to specify that.
Below is a sample Perl script that get the season info, decodes it, and prints it to standard out. The script is also
available here as a file attachment.
--- sample FRC API script ---
#! /usr/bin/perl -w
use strict;
use warnings FATAL => qw( all );
use JSON;
use MIME::Base64;
use LWP::UserAgent;
use Data::Dumper;
$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0; # hack for bad cert
my $tokenAuth = encode_base64('<username>:<authorzation-token>', '');
my $ua = LWP::UserAgent->new;
$ua->default_header('Authorization' => "Basic $tokenAuth");
$ua->default_header(accept => "application/json");
my $response = $ua->get('https://frc.staging.api.usfirst.org/api/v1.0/2015');
die unless $response->is_success(); # actual error handling advised
my $data = decode_json($response->content);
print Dumper($data);
--- expected output ---
$VAR1 = {
'rookieStart' => 5400,
'gameName' => 'RECYCLE RUSH',
'kickoff' => '2015-01-03T15:30:00Z',
'teamCount' => 2900,
'frcChampionship' => '2015-04-22T00:00:00',
'eventCount' => 118
};
|
|
|