CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
How to access an API with Perl?

 



jxm28
New User

Aug 11, 2017, 6:45 AM

Post #1 of 8 (1236 views)
How to access an API with Perl? Can't Post

One of our suppliers has an API which lets customers interrogate their DB and retrieve certain information like stock level or price.

I have used their API test tool which lets you type in the relevent code to make sure it is working.

That all seems to work fine, but how do I actually do that from a perl script?

Their system can accept requests, and send the response in the following formats -

Application/json
Text/json
Application/XML
Text/XML

Will I be able to get perl to talk to the API using json/xml, if so how, as I don't have the fisst clue where to start.


Laurent_R
Veteran / Moderator

Aug 12, 2017, 3:06 AM

Post #2 of 8 (1224 views)
Re: [jxm28] How to access an API with Perl? [In reply to] Can't Post

You sure should be able to generate JSON and XML in Perl (using the relevant modules from the CPAN), but you don't say enough about the API. Is it a Web-like interface, a Web service or collection or Web services, or something similar?


jxm28
New User

Aug 12, 2017, 3:30 AM

Post #3 of 8 (1222 views)
Re: [Laurent_R] How to access an API with Perl? [In reply to] Can't Post

It looks like it uses curl like so -


Code
curl -X GET --header 'Accept: text/json' --header 'Ocp-Apim-Subscription-Key: xxx' 'https://services.xxx.com/apisandbox/product/detail?customerNumber=xxx&itemNumber=xxx&partNumberType=1&region=1'


so can curl be used from perl? and how would you capture the response?


ogit2
Novice

Aug 15, 2017, 7:07 AM

Post #4 of 8 (1169 views)
Re: [jxm28] How to access an API with Perl? [In reply to] Can't Post

Hi

You can capture output using backticks `<command>` .

Not sure this is helpful but my next post will hopefully get both of us closer to a result.


ogit2
Novice

Aug 15, 2017, 7:12 AM

Post #5 of 8 (1168 views)
Re: [jxm28] How to access an API with Perl? [In reply to] Can't Post

Hi not sure exactly what you are after but one simple way to access web services if the service provider allows is below. $content can then be interrogated as a string.


Code
use POSIX; 
use LWP::Simple;

my $url = "http://www.services.com/version_001.asmx/Logon?Username=$username&Password=$password";
my $content = get($url);



ogit2
Novice

Aug 15, 2017, 7:24 AM

Post #6 of 8 (1166 views)
Re: [jxm28] How to access an API with Perl? [In reply to] Can't Post

Hi

Another way is below. This is where I too need help as we need to use restful web services with bearer token. The first set of code is my attempt to replicate c# code (which works) using perl. What am I doing incorrectly? I have not copied the entire c# program but just the key part I am trying to replicate. The perl program is not sending the data correctly so the response I get back is 'error' => 'unsupported_grant_type. I am guessing I have not put the text 'application/x-www-form-urlencoded' or '/token' in the right places in my attempts.

non-coder so limited understanding of c# or perl.

Perl Code Attempt 1
-----------

Code
use JSON; 
use MIME::Base64;
use REST::Client;
use Data::Dumper;

my $username = 'someusername';
my $password = 'somepassword';
my $headers = {Accept => 'application/x-www-form-urlencoded', grant_type => "password", username => $username, password => $password};
my $client = REST::Client->new();
$client->setHost('https://api.service.com');
$client->GET(
'/token',
$headers
);
my $response = from_json($client->responseContent());

print Dumper($response);


Perl Code Attempt 2

Code
use JSON; 
use MIME::Base64;
use REST::Client;
use Data::Dumper;

my $username = 'someusername';
my $password = 'somepassword';
my $headers = {grant_type => 'password', username => $username, password => $password};
my $client = REST::Client->new();
$client->setHost('https://api.service.com');
$client->addHeader('Content-Type', 'application/x-www-form-urlencoded' );
$client->POST ('/token','',$headers);

my $response = from_json($client->responseContent());

print Dumper($response);


c# Equivalent Code - This Works
--------------------------------------

Code
        public async Task<TokenResponse> Login() 
{
using (var client = new HttpClient())
{
client.BaseAddress = this.baseUri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

var content =
new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", this.username),
new KeyValuePair<string, string>("password", this.password)
});

var response = await client.PostAsync("/token", content);

if (response.StatusCode != HttpStatusCode.OK)
{
return this.userObject;
}

var responseContent = await response.Content.ReadAsStringAsync();

this.userObject = new JavaScriptSerializer().Deserialize<TokenResponse>(responseContent);

return this.userObject;
}
}



(This post was edited by ogit2 on Aug 15, 2017, 7:55 AM)


ogit2
Novice

Aug 15, 2017, 9:48 AM

Post #7 of 8 (1157 views)
Re: [jxm28] How to access an API with Perl? [In reply to] Can't Post

I've fixed my code with the following perl. So here is another valid way of accessing web services. I've cut it down and the error was that the web service was expecting the data in the body not the headers. Once I understood the format they were expecting it worked. In the code below the access_token is returned. Dumper simply shows all the data.


Code
use JSON; 
use MIME::Base64;
use REST::Client;
use Data::Dumper;

my $client = REST::Client->new();
$client->setHost('https://api.service.com');
$client->addHeader('Content-Type','application/x-www-form-urlencoded');
$client->POST ('/token','grant_type=password&username=$username&password=$password');

my $response = from_json($client->responseContent());

print $response->{'access_token'};
print "\n";
print Dumper($response);



jxm28
New User

Aug 16, 2017, 1:03 AM

Post #8 of 8 (1145 views)
Re: [ogit2] How to access an API with Perl? [In reply to] Can't Post

Thanks, I'll give that a try when I get a chance.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives