JSON

Interacting with the API in Perl using the JSON library.

This example demonstrates calling the GetClientInfo method.

#!/usr/bin/perl -w=head1 NAME    Yandex.Direct API usage example in Perl        using the JSON library=head1 DESCRIPTION    This sample uses recommended syntax for accessing the Yandex.Direct API        in Perl using the JSON protocol.

    Note that all textual data must be UTF8-encoded.

    Read more about obtaining a token in the documentation:
        https://tech.yandex.com/oauth/doc/dg/

    This example demonstrates calling the GetClientInfo method, which returns information about the specified login name.

=cut


use strict;

use JSON qw/to_json from_json/;
use Encode qw/decode_utf8/;

use HTTP::Request::Common;
use HTTP::Response;
use LWP::UserAgent;

use Data::Dumper;

# OAuth token issued by the oauth.yandex.com service
my $token = 'YANDEX-OAUTH-LOGIN-TOKEN';

# Login of the account to get information for
my $login = 'YANDEX-LOGIN';

my $url = "https://api.direct.yandex.ru/v4/json/";

# Preparing request data
my $data = {};
$data->{param} = [$login];
$data->{method} = 'GetClientInfo';

$data->{token} = $token;

my $json_data = to_json($data);

my $ua = new LWP::UserAgent( timeout => 600 );

my $request = HTTP::Request->new('POST', $url, undef, $json_data);

# Request to the server
my $response = $ua->request($request);

# for debug
# warn $request->as_string, "\n";
# warn $response->as_string, "\n";

if ($response->is_success) {

    my $result = from_json(Encode::decode_utf8($response->decoded_content())) || {};

    if (defined $result->{error_code}) {

        # If the Yandex.Direct API server returned an error
        die join "\n"
                    , "API error:"
                    , "Code: ".$result->{error_code}
                    , "Describe: ".$result->{error_str}
                    , "Detail:".($result->{error_detail} || '');

    } elsif (defined $result->{data}) {

        print Dumper {result => $result};

    }

} else {

    # If an error occurred when sending the request
    die "HTTP error: ".$response->status_line;

}