PerlMonkey22 has asked for the wisdom of the Perl Monks concerning the following question:

Hello everyone, I got a task to write a Perl script to test our API. So far so good code below

use strict; use warnings; use JSON; use JSON::Parse 'parse_json'; print "Loading API.\n"; my $json = `curl -k --silent -u admin:password https://url...`; print "API is loaded.\n"; my $decoded_json = parse_json ($json); my $input = $ARGV[0]; chomp $input; my ($item, $mac, $value); foreach $item (@$decoded_json) { $mac = $item->{address}; if ($input eq "active") { $value = $item->{active}; if ($value eq 1){ print ("Device with the MAC-Adress: $mac is active!\n"); }elsif($value eq ""){ print ("Device with the MAC-Adress: $mac is disabled!\n"); }}else{ print ("Device with the MAC-Adress: $mac, the value of $input +is: ", $item->{$input}, "\n"); } };

Is it possible to replace the loop and if statments, so the asked parameter like "active=true", with curl? So the true values get saved in $json. Basicly, execute the request with just curl code. For example if I start it: perl test.pl active=true, so it outputs only the active true values?

Replies are listed 'Best First'.
Re: Getting values with help of curl
by Corion (Patriarch) on Sep 01, 2022 at 10:53 UTC

    If you don't want to change the URL yourself, you could convert the curl invocation to Perl code (using, for example, curl2lwp, written by me):

    #!perl use strict; use warnings; use HTTP::Tiny; my $ua = HTTP::Tiny->new(); my $res = $ua->request( 'GET' => 'https://url.../', { headers => { 'Accept' => '*/*', 'User-Agent' => 'curl/7.55.1', 'Authorization' => 'Basic YWRtaW46cGFzc3dvcmQ=' }, }, ); __END__ Created from curl command line curl -k --silent -u admin:password https://url...

    Simply appending &active=true to the URL might also work.

      Thanks! Is there any option to implement it just in the curl -s -k -u admin:pass https://url../GetDeviceInfo? So I can prompt it just with the console command?

        I'm not sure what "it" is. If you simply want to change the URL, you can do that in the Perl code. But I'm not sure what your URLs are, or where the active=true part plays any role.

        I think it would help if you show us the two URLs you want and the behaviours you want. My current vague interpretation is that you want something like the following maybe:

        my $url = "https://url../GetDeviceInfo"; if( ... whatever condition ...) { $url .= "&active=true"; } say "Requesting $url"; my $output = `curl -s -k -u admin:password "$url"`; ...