develooper Front page | perl.beginners | Postings from April 2020

Re: Help with REST API interaction.

Thread Previous | Thread Next
Gil Magno
April 24, 2020 23:01
Re: Help with REST API interaction.
Message ID:
Hi Francisco,

2020-04-22 11:21:31 -0300 Francisco Acuña:
> Good day, I've been getting familiarized with Perl for the last couple of
> days due to a RT integration project I've been handed. I've also been doing
> a lot of research and a lot of asking around in forums for pointers on how
> to properly achieve this.
> I'm glad to say that I managed to get all my basic scrips up and running,
> retrieving all the values I needed and updating all the fields I wanted to
> update. I now need to get to the part of actually interacting with the
> external RESTful API.
> If what I understood from my research is correct, I will be working with
> the REST::Client and JSON modules. And what I need to do is:
>    1. Encode the values I want to pass over to the API into a JSON object.
>    2. Do some coding on the other side in order to achieve my desired
>    funcionalities and pass some values back to RT (for this I won't need your
>    help since the coding won't be done in Perl, sadly)
>    3. Decode the response I get back to Perl and use those values in RT to
>    do some more updating.
> I would greatly appreciate if you could provide me with some pointers and
> code examples of this being done. Choosing the values I need to pass,
> encoding them, passing them over to the API, and then decoding the response.
> Needless to say, I am documenting all my work and will gladly share my
> experience in this project and all the coding work in any forum.

One way to do it is like this:

use strict;
use warnings;
use feature 'say';
use LWP::UserAgent;
use JSON;

my $ua = LWP::UserAgent->new;
my $uri = '';
my %headers = ('Content-Type' => 'application/json');

# here are the values to pass to the API
my %values = (number => 1, name => 'etc');

my $res = $ua->post(
    Content => JSON::encode_json(\%values)

if ($ua->is_success) {
    # if you're receiving a JSON
    my $data = JSON::decode_json $res->content;
    # now $data is a Perl data structure; it's the decoded JSON

    # but if you're receiving (say) HTML
    say $res->decoded_content;
else {
    # handle errors here

See these docs for the modules' details:

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About