Using Roles to Build Perl Web Service Clients

Using Roles to Build Perl Web Service Clients

Slides for a talk delivered at YAPC::NA 2014 in Orlando, FL

7330b65ea54e1b90a987a552e5c5cf32?s=128

Mark Allen

June 24, 2014
Tweet

Transcript

  1. Using  Roles  to     Build  Web  Service  Clients  

    Mark  Allen   mrallen1@yahoo.com   @bytemeorg  
  2. None
  3. None
  4. None
  5. None
  6. h@ps://flic.kr/p/4ZJ9ms  

  7. h@ps://flic.kr/p/9g1aZc  

  8. None
  9. h@ps://flic.kr/p/8J3cKz  

  10. None
  11. You're Welcome!

  12. None
  13. None
  14. None
  15. h@ps://flic.kr/p/38vsE3  

  16. None
  17. h@ps://flic.kr/p/6uRpjb  

  18. h@ps://flic.kr/p/3EBJg9  

  19. h@ps://flic.kr/p/2zWmyv  

  20. use strict; package WebService::Foobar::Request; use Moo::Role; use warnings NONFATAL =>

    'all'; use HTTP::Tiny; use Carp qw(confess); has 'ua' => ( is => 'ro', lazy => 1, default => sub { HTTP::Tiny->new( agent => 'WebService-Foobar ', default_headers => { 'Content-Type' => 'application/json' }, ) }, ); has 'base_url' => ( is => 'ro', lazy => 1, default => sub { 'http://api.foobar.io/v1/' }, );
  21. # package WebService::Foobar::Request; # ... sub _request { my ($self,

    $op, $data) = @_; # ideally $data is already serialized my $url = $self->_build_url($op) or confess "Couldn't build url for $op\n"; my $result = $self->ua->request('POST', $url, {content=>$data}); if ( $result->{success} ) return $result; } else { confess "Request to $url failed. Got (" . $result->{status} . ") " . $result->{content} . "\n"; } }
  22. use strict; package WebService::Foobar::JSON; use Moo::Role; use warnings NONFATAL =>

    'all'; use JSON; use Carp qw(confess); has 'serializer' => ( is => 'ro', lazy => 1, default => sub { JSON->new() }, ); sub encode { my ($self, $ref) = @_; $self->serializer->encode($ref); } sub decode { my ($self, $data) = @_; $self->serializer->decode($data); }
  23. use strict; package WebService::Foobar::Data; use Moo; use warnings NONFATAL =>

    'all'; use Storable qw(dcopy); with 'WebService::Foobar::JSON'; has 'bar' => ( 'is' => 'rw' ); has 'baz' => ( 'qux' => 'ro' ); sub qux { my $self = shift; print $self->bar . " and " . $self->baz; } sub _serialize { my $self = shift; my $copy = dcopy($self); $self->encode($copy); }
  24. None
  25. Public  domain  

  26. h@ps://flic.kr/p/7ABQ56  

  27. h@p://commons.wikimedia.org/wiki/File%3ATed_Gundersons_FBI_BADGE_inside.jpg  

  28. h@p://commons.wikimedia.org/wiki/File:Synopsis_hist%C3%B3rica_chronologica_de_Espa%C3%B1a_-­‐_1775-­‐1791.jpg  

  29. None
  30. h@ps://flic.kr/p/58vQCQ  

  31. THANK  YOU!   Slides:  h@ps://speakerdeck.com/mrallen1/   Email:  mrallen1  at  yahoo

     dot  com   Twi-er:  @bytemeorg   Github:  h@ps://github.com/mrallen1