blib/lib/API/Client.pm untested

filter: Statementstmt 0.0% 0 / 136 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 20 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod n/a totaltotal 0.0% 0 / 201 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package API::Client;
2  
3 use 5.014;
4  
5 use strict;
6 use warnings;
7  
8 use registry;
9 use routines;
10  
11 use Data::Object::Class;
12 use Data::Object::ClassHas;
13 use FlightRecorder;
14 use Mojo::Transaction;
15 use Mojo::UserAgent;
16 use Mojo::URL;
17  
18 with 'Data::Object::Role::Buildable';
19 with 'Data::Object::Role::Stashable';
20 with 'Data::Object::Role::Throwable';
21  
22 our $VERSION = '0.11'; # VERSION
23  
24 # ATTRIBUTES
25  
26 has 'debug' => (
27 is => 'ro',
28 isa => 'Bool',
29 def => 0,
30 );
31  
32 has 'fatal' => (
33 is => 'ro',
34 isa => 'Bool',
35 def => 0,
36 );
37  
38 has 'logger' => (
39 is => 'ro',
40 isa => 'InstanceOf["FlightRecorder"]',
41 new => 1,
42 );
43  
44 fun new_logger($self) {
45 FlightRecorder->new
46 }
47  
48 has 'name' => (
49 is => 'ro',
50 isa => 'Str',
51 new => 1,
52 );
53  
54 fun new_name($self) {
55 "@{[ref($self)]} (@{[$self->version]})"
56 }
57  
58 has 'retries' => (
59 is => 'ro',
60 isa => 'Int',
61 def => 0,
62 );
63  
64 has 'timeout' => (
65 is => 'ro',
66 isa => 'Int',
67 def => 10,
68 );
69  
70 has 'url' => (
71 is => 'ro',
72 isa => 'InstanceOf["Mojo::URL"]',
73 req => 1,
74 );
75  
76 has 'user_agent' => (
77 is => 'ro',
78 isa => 'InstanceOf["Mojo::UserAgent"]',
79 new => 1,
80 );
81  
82 fun new_user_agent($self) {
83 Mojo::UserAgent->new
84 }
85  
86 has 'version' => (
87 is => 'ro',
88 isa => 'Str',
89 new => 1,
90 );
91  
92 fun new_version($self) {
93 $self->VERSION || 0.01
94 }
95  
96 # BUILD
97  
98 method build_args($args) {
99 if (!$args->{url}) {
100 $args->{url} = join('/', @{$self->base(%$args)}) if $self->can('base');
101 }
102 if (!ref $args->{url}) {
103 $args->{url} = Mojo::URL->new($args->{url}) if $args->{url};
104 }
105  
106 return $args;
107 }
108  
109 # METHODS
110  
111 method create(Any %args) {
112  
113 return $self->dispatch(%args, method => 'post');
114 }
115  
116 method delete(Any %args) {
117  
118 return $self->dispatch(%args, method => 'delete');
119 }
120  
121 method dispatch(Str :$method = 'get', Any %args) {
122 my $log = $self->logger->info("@{[uc($method)]} @{[$self->url->to_string]}");
123  
124 my $result = $self->execute(%args, method => $method);
125  
126 $log->end;
127  
128 return $result;
129 }
130  
131 method fetch(Any %args) {
132  
133 return $self->dispatch(%args, method => 'get');
134 }
135  
136 method patch(Any %args) {
137  
138 return $self->dispatch(%args, method => 'patch');
139 }
140  
141 method update(Any %args) {
142  
143 return $self->dispatch(%args, method => 'put');
144 }
145  
146 method prepare(Object $ua, Object $tx, Any %args) {
147 $self->set_auth($ua, $tx, %args);
148 $self->set_headers($ua, $tx, %args);
149 $self->set_identity($ua, $tx, %args);
150  
151 return $self;
152 }
153  
154 method process(Object $ua, Object $tx, Any %args) {
155  
156 return $self;
157 }
158  
159 method resource(Str @segments) {
160 my $url;
161  
162 if (@segments) {
163 $url = $self->url->clone;
164  
165 $url->path->merge(
166 join '/', @{$self->url->path->parts}, @segments
167 );
168 }
169  
170 my $object = ref($self)->new(
171 %{$self->serialize}, ($url ? ('url', $url) : ())
172 );
173  
174 return $object;
175 }
176  
177 method serialize() {
178  
179 return {
180 debug => $self->debug,
181 fatal => $self->fatal,
182 name => $self->name,
183 retries => $self->retries,
184 timeout => $self->timeout,
185 url => $self->url->to_string,
186 };
187 }
188  
189 method set_auth($ua, $tx, %args) {
190 if ($self->can('auth')) {
191 $tx->req->url->userinfo(join ':', @{$self->auth});
192 }
193  
194 return $self;
195 }
196  
197 method set_headers($ua, $tx, %args) {
198 if ($self->can('headers')) {
199 $tx->req->headers->header(@$_) for @{$self->headers};
200 } else {
201 $tx->req->headers->header('Content-Type' => 'application/json');
202 }
203  
204 return $self;
205 }
206  
207 method set_identity($ua, $tx, %args) {
208 $tx->req->headers->header('User-Agent' => $self->name);
209  
210 return $self;
211 }
212  
213 method execute(Str :$method = 'get', Str :$path = '', Any %args) {
214 delete $args{method};
215  
216 my $ua = $self->user_agent;
217 my $url = $self->url->clone;
218  
219 my $query = $args{query} || {};
220 my $headers = $args{headers} || {};
221  
222 $url->path(join '/', $url->path, $path) if $path;
223 $url->query($url->query->merge(%$query)) if keys %$query;
224  
225 my @args;
226  
227 # data handlers
228 for my $type (sort keys %{$ua->transactor->generators}) {
229 push @args, $type, delete $args{$type} if $args{$type};
230 }
231  
232 # handle raw body value
233 push @args, delete $args{body} if exists $args{body};
234  
235 # transaction prepare hook
236 $ua->on(prepare => fun ($ua, $tx) {
237 $self->prepare($ua, $tx, %args);
238 });
239  
240 # client timeouts
241 $ua->max_redirects(0);
242 $ua->connect_timeout($self->timeout);
243 $ua->request_timeout($self->timeout);
244  
245 # transaction
246 my ($ok, $tx, $req, $res);
247  
248 # times to retry failures
249 my $retries = $self->retries;
250  
251 # transaction retry loop
252 for (my $i = 0; $i < ($retries || 1); $i++) {
253 # execute transaction
254 $tx = $ua->start($ua->build_tx($method, $url, $headers, @args));
255 $self->process($ua, $tx, %args);
256  
257 # transaction objects
258 $req = $tx->req;
259 $res = $tx->res;
260  
261 # determine success/failure
262 $ok = $res->code ? $res->code !~ /(4|5)\d\d/ : 0;
263  
264 # log activity
265 if ($req && $res) {
266 my $log = $self->logger;
267 my $msg = join " ", "attempt", ("#".($i+1)), ": $method", $url->to_string;
268  
269 $log->debug("req: $msg")->data({
270 request => $req->to_string =~ s/\s*$/\n\n\n/r
271 });
272  
273 $log->debug("res: $msg")->data({
274 response => $res->to_string =~ s/\s*$/\n\n\n/r
275 });
276  
277 # output to the console where applicable
278 $log->info("res: $msg [@{[$res->code]}]");
279 $log->output if $self->debug;
280 }
281  
282 # no retry necessary
283 last if $ok;
284 }
285  
286 # throw exception if fatal is truthy
287 if ($req && $res && $self->fatal && !$ok) {
288 my $code = $res->code;
289  
290 $self->stash(tx => $tx);
291 $self->throw([$code, uc "${code}_http_response"]);
292 }
293  
294 # return transaction
295 return $tx;
296 }
297  
298 1;
299  
300 =encoding utf8
301  
302 =head1 NAME
303  
304 API::Client
305  
306 =cut
307  
308 =head1 ABSTRACT
309  
310 HTTP API Thin-Client Abstraction
311  
312 =cut
313  
314 =head1 SYNOPSIS
315  
316 package main;
317  
318 use API::Client;
319  
320 my $client = API::Client->new(url => 'https://httpbin.org');
321  
322 # $client->resource('post');
323  
324 # $client->update(json => {...});
325  
326 =cut
327  
328 =head1 DESCRIPTION
329  
330 This package provides an abstraction and method for rapidly developing HTTP API
331 clients. While this module can be used to interact with APIs directly,
332 API::Client was designed to be consumed (subclassed) by higher-level
333 purpose-specific API clients.
334  
335 =head1 THIN CLIENT
336  
337 The thin API client library is advantageous as it has complete API coverage and
338 can easily adapt to changes in the API with minimal effort. As a thin-client
339 superclass, this module does not map specific HTTP requests to specific
340 routines, nor does it provide parameter validation, pagination, or other
341 conventions found in typical API client implementations; Instead, it simply
342 provides a simple and consistent mechanism for dynamically generating HTTP
343 requests. Additionally, this module has support for debugging and retrying API
344 calls as well as throwing exceptions when 4xx and 5xx server response codes are
345 returned.
346  
347 =cut
348  
349 =head1 INTEGRATES
350  
351 This package integrates behaviors from:
352  
353 L<Data::Object::Role::Buildable>
354  
355 L<Data::Object::Role::Stashable>
356  
357 L<Data::Object::Role::Throwable>
358  
359 =cut
360  
361 =head1 LIBRARIES
362  
363 This package uses type constraints from:
364  
365 L<Types::Standard>
366  
367 =cut
368  
369 =head1 SCENARIOS
370  
371 This package supports the following scenarios:
372  
373 =cut
374  
375 =head2 building
376  
377 # given: synopsis
378  
379 my $resource = $client->resource('get');
380  
381 # GET /get
382 my $get = $client->resource('get')->dispatch;
383  
384 # HEAD /head
385 my $head = $client->resource('head')->dispatch(
386 method => 'head'
387 );
388  
389 # PATCH /patch
390 my $patch = $client->resource('patch')->dispatch(
391 method => 'patch'
392 );
393  
394 [$get, $head, $patch]
395  
396 Building up an HTTP request is extremely easy, simply call the L</resource> to
397 create a new object instance representing the API endpoint you wish to issue a
398 request against.
399  
400 =cut
401  
402 =head2 chaining
403  
404 # given: synopsis
405  
406 # https://httpbin.org/users
407 my $users = $client->resource('users');
408  
409 # https://httpbin.org/users/c09e91a
410 my $user = $client->resource('users', 'c09e91a');
411  
412 # https://httpbin.org/users/c09e91a
413 my $new_user = $users->resource('c09e91a');
414  
415 [$users, $user, $new_user]
416  
417 Because each call to L</resource> returns a new object instance configured with
418 a path (resource locator) based on the supplied parameters, reuse and request
419 isolation are made simple, i.e., you will only need to configure the client
420 once in your application.
421  
422 =cut
423  
424 =head2 creating
425  
426 # given: synopsis
427  
428 my $tx1 = $client->resource('post')->create(
429 json => {active => 1}
430 );
431  
432 # is equivalent to
433  
434 my $tx2 = $client->resource('post')->dispatch(
435 method => 'post',
436 json => {active => 1}
437 );
438  
439 [$tx1, $tx2]
440  
441 This example illustrates how you might create a new API resource.
442  
443 =cut
444  
445 =head2 deleting
446  
447 # given: synopsis
448  
449 my $tx1 = $client->resource('delete')->delete(
450 json => {active => 1}
451 );
452  
453 # is equivalent to
454  
455 my $tx2 = $client->resource('delete')->dispatch(
456 method => 'delete',
457 json => {active => 1}
458 );
459  
460 [$tx1, $tx2]
461  
462 This example illustrates how you might delete a new API resource.
463  
464 =cut
465  
466 =head2 fetching
467  
468 # given: synopsis
469  
470 my $tx1 = $client->resource('get')->fetch(
471 query => {active => 1}
472 );
473  
474 # is equivalent to
475  
476 my $tx2 = $client->resource('get')->dispatch(
477 method => 'get',
478 query => {active => 1}
479 );
480  
481 [$tx1, $tx2]
482  
483 This example illustrates how you might fetch an API resource.
484  
485 =cut
486  
487 =head2 subclassing
488  
489 package Hookbin;
490  
491 use Data::Object::Class;
492  
493 extends 'API::Client';
494  
495 sub auth {
496 ['admin', 'secret']
497 }
498  
499 sub headers {
500 [['Accept', '*/*']]
501 }
502  
503 sub base {
504 ['https://httpbin.org/get']
505 }
506  
507 package main;
508  
509 my $hookbin = Hookbin->new;
510  
511 This package was designed to be subclassed and provides hooks into the client
512 building and request dispatching processes. Specifically, there are three
513 useful hooks (i.e. methods, which if present are used to build up the client
514 object and requests), which are, the C<auth> hook, which should return a
515 C<Tuple[Str, Str]> which is used to configure the basic auth header, the
516 C<base> hook which should return a C<Tuple[Str]> which is used to configure the
517 base URL, and the C<headers> hook, which should return a
518 C<ArrayRef[Tuple[Str, Str]]> which are used to configure the HTTP request
519 headers.
520  
521 =cut
522  
523 =head2 transacting
524  
525 # given: synopsis
526  
527 my $tx1 = $client->resource('patch')->patch(
528 json => {active => 1}
529 );
530  
531 # is equivalent to
532  
533 my $tx2 = $client->resource('patch')->dispatch(
534 method => 'patch',
535 json => {active => 1}
536 );
537  
538 [$tx1, $tx2]
539  
540 An HTTP request is only issued when the L</dispatch> method is called, directly
541 or indirectly. Those calls return a L<Mojo::Transaction> object which provides
542 access to the C<request> and C<response> objects.
543  
544 =cut
545  
546 =head2 updating
547  
548 # given: synopsis
549  
550 my $tx1 = $client->resource('put')->update(
551 json => {active => 1}
552 );
553  
554 # is equivalent to
555  
556 my $tx2 = $client->resource('put')->dispatch(
557 method => 'put',
558 json => {active => 1}
559 );
560  
561 [$tx1, $tx2]
562  
563 This example illustrates how you might update a new API resource.
564  
565 =cut
566  
567 =head1 ATTRIBUTES
568  
569 This package has the following attributes:
570  
571 =cut
572  
573 =head2 debug
574  
575 debug(Bool)
576  
577 This attribute is read-only, accepts C<(Bool)> values, and is optional.
578  
579 =cut
580  
581 =head2 fatal
582  
583 fatal(Bool)
584  
585 This attribute is read-only, accepts C<(Bool)> values, and is optional.
586  
587 =cut
588  
589 =head2 logger
590  
591 logger(InstanceOf["FlightRecorder"])
592  
593 This attribute is read-only, accepts C<(InstanceOf["FlightRecorder"])> values, and is optional.
594  
595 =cut
596  
597 =head2 name
598  
599 name(Str)
600  
601 This attribute is read-only, accepts C<(Str)> values, and is optional.
602  
603 =cut
604  
605 =head2 retries
606  
607 retries(Int)
608  
609 This attribute is read-only, accepts C<(Int)> values, and is optional.
610  
611 =cut
612  
613 =head2 timeout
614  
615 timeout(Int)
616  
617 This attribute is read-only, accepts C<(Int)> values, and is optional.
618  
619 =cut
620  
621 =head2 url
622  
623 url(InstanceOf["Mojo::URL"])
624  
625 This attribute is read-only, accepts C<(InstanceOf["Mojo::URL"])> values, and is optional.
626  
627 =cut
628  
629 =head2 user_agent
630  
631 user_agent(InstanceOf["Mojo::UserAgent"])
632  
633 This attribute is read-only, accepts C<(InstanceOf["Mojo::UserAgent"])> values, and is optional.
634  
635 =cut
636  
637 =head2 version
638  
639 version(Str)
640  
641 This attribute is read-only, accepts C<(Str)> values, and is optional.
642  
643 =cut
644  
645 =head1 METHODS
646  
647 This package implements the following methods:
648  
649 =cut
650  
651 =head2 create
652  
653 create(Any %args) : InstanceOf["Mojo::Transaction"]
654  
655 The create method issues a C<POST> request to the API resource represented by
656 the object.
657  
658 =over 4
659  
660 =item create example #1
661  
662 # given: synopsis
663  
664 $client->resource('post')->create(
665 json => {active => 1}
666 );
667  
668 =back
669  
670 =cut
671  
672 =head2 delete
673  
674 delete(Any %args) : InstanceOf["Mojo::Transaction"]
675  
676 The delete method issues a C<DELETE> request to the API resource represented by
677 the object.
678  
679 =over 4
680  
681 =item delete example #1
682  
683 # given: synopsis
684  
685 $client->resource('delete')->delete;
686  
687 =back
688  
689 =cut
690  
691 =head2 dispatch
692  
693 dispatch(Str :$method = 'get', Any %args) : InstanceOf["Mojo::Transaction"]
694  
695 The dispatch method issues a request to the API resource represented by the
696 object.
697  
698 =over 4
699  
700 =item dispatch example #1
701  
702 # given: synopsis
703  
704 $client->resource('get')->dispatch;
705  
706 =back
707  
708 =over 4
709  
710 =item dispatch example #2
711  
712 # given: synopsis
713  
714 $client->resource('post')->dispatch(
715 method => 'post', body => 'active=1'
716 );
717  
718 =back
719  
720 =over 4
721  
722 =item dispatch example #3
723  
724 # given: synopsis
725  
726 $client->resource('get')->dispatch(
727 method => 'get', query => {active => 1}
728 );
729  
730 =back
731  
732 =over 4
733  
734 =item dispatch example #4
735  
736 # given: synopsis
737  
738 $client->resource('post')->dispatch(
739 method => 'post', json => {active => 1}
740 );
741  
742 =back
743  
744 =over 4
745  
746 =item dispatch example #5
747  
748 # given: synopsis
749  
750 $client->resource('post')->dispatch(
751 method => 'post', form => {active => 1}
752 );
753  
754 =back
755  
756 =over 4
757  
758 =item dispatch example #6
759  
760 # given: synopsis
761  
762 $client->resource('put')->dispatch(
763 method => 'put', json => {active => 1}
764 );
765  
766 =back
767  
768 =over 4
769  
770 =item dispatch example #7
771  
772 # given: synopsis
773  
774 $client->resource('patch')->dispatch(
775 method => 'patch', json => {active => 1}
776 );
777  
778 =back
779  
780 =over 4
781  
782 =item dispatch example #8
783  
784 # given: synopsis
785  
786 $client->resource('delete')->dispatch(
787 method => 'delete', json => {active => 1}
788 );
789  
790 =back
791  
792 =cut
793  
794 =head2 fetch
795  
796 fetch(Any %args) : InstanceOf["Mojo::Transaction"]
797  
798 The fetch method issues a C<GET> request to the API resource represented by the
799 object.
800  
801 =over 4
802  
803 =item fetch example #1
804  
805 # given: synopsis
806  
807 $client->resource('get')->fetch;
808  
809 =back
810  
811 =cut
812  
813 =head2 patch
814  
815 patch(Any %args) : InstanceOf["Mojo::Transaction"]
816  
817 The patch method issues a C<PATCH> request to the API resource represented by
818 the object.
819  
820 =over 4
821  
822 =item patch example #1
823  
824 # given: synopsis
825  
826 $client->resource('patch')->patch(
827 json => {active => 1}
828 );
829  
830 =back
831  
832 =cut
833  
834 =head2 prepare
835  
836 prepare(Object $ua, Object $tx, Any %args) : Object
837  
838 The prepare method acts as a C<before> hook triggered before each request where
839 you can modify the transactor objects.
840  
841 =over 4
842  
843 =item prepare example #1
844  
845 # given: synopsis
846  
847 require Mojo::UserAgent;
848 require Mojo::Transaction::HTTP;
849  
850 $client->prepare(
851 Mojo::UserAgent->new,
852 Mojo::Transaction::HTTP->new
853 );
854  
855 =back
856  
857 =cut
858  
859 =head2 process
860  
861 process(Object $ua, Object $tx, Any %args) : Object
862  
863 The process method acts as an C<after> hook triggered after each response where
864 you can modify the transactor objects.
865  
866 =over 4
867  
868 =item process example #1
869  
870 # given: synopsis
871  
872 require Mojo::UserAgent;
873 require Mojo::Transaction::HTTP;
874  
875 $client->process(
876 Mojo::UserAgent->new,
877 Mojo::Transaction::HTTP->new
878 );
879  
880 =back
881  
882 =cut
883  
884 =head2 resource
885  
886 resource(Str @segments) : Object
887  
888 The resource method returns a new instance of the object for the API resource
889 endpoint specified.
890  
891 =over 4
892  
893 =item resource example #1
894  
895 # given: synopsis
896  
897 $client->resource('status', 200);
898  
899 =back
900  
901 =cut
902  
903 =head2 serialize
904  
905 serialize() : HashRef
906  
907 The serialize method serializes and returns the object as a C<hashref>.
908  
909 =over 4
910  
911 =item serialize example #1
912  
913 # given: synopsis
914  
915 $client->serialize;
916  
917 =back
918  
919 =cut
920  
921 =head2 update
922  
923 update(Any %args) : InstanceOf["Mojo::Transaction"]
924  
925 The update method issues a C<PUT> request to the API resource represented by
926 the object.
927  
928 =over 4
929  
930 =item update example #1
931  
932 # given: synopsis
933  
934 $client->resource('put')->update(
935 json => {active => 1}
936 );
937  
938 =back
939  
940 =cut
941  
942 =head1 AUTHOR
943  
944 Al Newkirk, C<awncorp@cpan.org>
945  
946 =head1 LICENSE
947  
948 Copyright (C) 2011-2019, Al Newkirk, et al.
949  
950 This is free software; you can redistribute it and/or modify it under the terms
951 of the The Apache License, Version 2.0, as elucidated in the L<"license
952 file"|https://github.com/iamalnewkirk/api-client/blob/master/LICENSE>.
953  
954 =head1 PROJECT
955  
956 L<Wiki|https://github.com/iamalnewkirk/api-client/wiki>
957  
958 L<Project|https://github.com/iamalnewkirk/api-client>
959  
960 L<Initiatives|https://github.com/iamalnewkirk/api-client/projects>
961  
962 L<Milestones|https://github.com/iamalnewkirk/api-client/milestones>
963  
964 L<Contributing|https://github.com/iamalnewkirk/api-client/blob/master/CONTRIBUTE.md>
965  
966 L<Issues|https://github.com/iamalnewkirk/api-client/issues>
967  
968 =cut