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.

    For more information about getting a token, see the documentation:
 https://tech.yandex.ru/oauth/doc/dg/

    As an example, we'll call 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;

# The access token obtained from the oauth.yandex.com service
my $token = 'YANDEX-OAUTH-LOGIN-TOKEN';

# Login name of the account to get data 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 an error was returned by the Yandex.Direct API server
        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 during request sending
    die "HTTP error: ".$response->status_line;

}