API-Client
view release on metacpan or search on metacpan
lib/API/Client.pm view on Meta::CPAN
# client timeouts
$ua->max_redirects(0);
$ua->connect_timeout($self->timeout);
$ua->request_timeout($self->timeout);
# transaction
my ($ok, $tx, $req, $res);
# times to retry failures
my $retries = $self->retries;
# transaction retry loop
for (my $i = 0; $i < ($retries || 1); $i++) {
# execute transaction
$tx = $ua->start($ua->build_tx($method, $url, $headers, @args));
$self->process($ua, $tx, %args);
# transaction objects
$req = $tx->req;
$res = $tx->res;
# determine success/failure
$ok = $res->code ? $res->code !~ /(4|5)\d\d/ : 0;
# log activity
if ($req && $res) {
my $log = $self->logger;
my $msg = join " ", "attempt", ("#".($i+1)), ": $method", $url->to_string;
$log->debug("req: $msg")->data({
request => $req->to_string =~ s/\s*$/\n\n\n/r
});
$log->debug("res: $msg")->data({
response => $res->to_string =~ s/\s*$/\n\n\n/r
});
# output to the console where applicable
$log->info("res: $msg [@{[$res->code]}]");
$log->output if $self->debug;
}
# no retry necessary
last if $ok;
}
# throw exception if fatal is truthy
if ($req && $res && $self->fatal && !$ok) {
my $code = $res->code;
$self->stash(tx => $tx);
$self->throw([$code, uc "${code}_http_response"]);
}
# return transaction
return $tx;
}
1;
=encoding utf8
=head1 NAME
API::Client
=cut
=head1 ABSTRACT
HTTP API Thin-Client Abstraction
=cut
=head1 SYNOPSIS
package main;
use API::Client;
my $client = API::Client->new(url => 'https://httpbin.org');
# $client->resource('post');
# $client->update(json => {...});
=cut
=head1 DESCRIPTION
This package provides an abstraction and method for rapidly developing HTTP API
clients. While this module can be used to interact with APIs directly,
API::Client was designed to be consumed (subclassed) by higher-level
purpose-specific API clients.
=head1 THIN CLIENT
The thin API client library is advantageous as it has complete API coverage and
can easily adapt to changes in the API with minimal effort. As a thin-client
superclass, this module does not map specific HTTP requests to specific
routines, nor does it provide parameter validation, pagination, or other
conventions found in typical API client implementations; Instead, it simply
provides a simple and consistent mechanism for dynamically generating HTTP
requests. Additionally, this module has support for debugging and retrying API
calls as well as throwing exceptions when 4xx and 5xx server response codes are
returned.
=cut
=head1 INTEGRATES
This package integrates behaviors from:
L<Data::Object::Role::Buildable>
L<Data::Object::Role::Stashable>
L<Data::Object::Role::Throwable>
=cut
( run in 1.885 second using v1.01-cache-2.11-cpan-3d66aa2751a )