package MW_API; use Mouse; use Mojo::UserAgent; use Carp; # MW API url has 'api_url' => (is => 'ro', isa => 'Str', default => 'https://api.microworkers.com' ); # your api key has 'api_key' => (is => 'ro', isa => 'Str', required => 1); # user agent has 'ua' => (is => 'ro', isa => 'Object', lazy => 1, default => sub { my $self = shift; my $ua = Mojo::UserAgent->new(); $ua->on(start => sub { my ($ua, $tx) = @_; # pass required header $tx->req->headers->header('MicroworkersApiKey' => $self->api_key); }); return $ua; } ); # do request sub do_request { my ($self, $method, $action, $params) = @_; $method = lc $method; if ($method ne 'get' && $method ne 'put' && $method ne 'post' && $method ne 'delete'){ croak qq{Method: "$method" is not supported}; } my %form; if ($params){ %form = ('form' => $params); } my $tx = $self->ua->$method($self->api_url . $action, %form); if (my $res = $tx->success) { if ($res->json){ return {'type' => 'json', 'value' => $res->json}; } else{ return {'type' => 'body', 'value' => $res->body}; } } return {'type' => 'error', 'value' => $tx->error}; } 1;