package ClientRest; use Carp; use strict; use warnings; use Data::Dumper; use version; our $VERSION; $VERSION = qv('0.0.1'); use JSON; use REST::Client; use constant { PORT_MIN => 1, PORT_MAX => 65535, }; sub new { my $class = shift; my $self = { _host => shift, }; _parameterValidation($self); # instatiate Rest::Client and create constructor my $client = REST::Client->new({ host => $self->{_host}, timeout => 10, }); $self->{_client} = $client; bless $self, $class; return $self; } sub _parameterValidation { my( $self ) = @_; croak "Invalid host syntax: sample 'http://:' " unless ( $self->{_host} =~ /^http:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}$/ ); } sub getSnippets { my ($self) = @_; # Simple GET request for testing purposes $self->{_client}->GET('/snippets/'); if (index($self->{_client}->responseContent(), "Can\'t connect to") != -1) { my @array = split /[http:\/\/]/, $self->{_host}; @array = grep { $_ ne '' } @array; croak "Server is unavailable at IP: " .$array[0]." and Port: " .$array[1]; } return decode_json $self->{_client}->responseContent(); } # Module further implementation here 1; #### #!/usr/bin/perl use strict; use warnings; use Data::Dumper; use MyClientRest::ClientRest; my $host = "http://127.0.0.1:8000"; # instatiate class my $object = new ClientRest( $host ); my $data = $object->getSnippets(); print Dumper $data; __END__ $ perl restClient.pl $VAR1 = { 'count' => 2, 'previous' => undef, 'next' => undef, 'results' => [ { 'highlight' => 'http://127.0.0.1:8000/snippets/1/highlight/', 'language' => 'perl', 'id' => 1, 'url' => 'http://127.0.0.1:8000/snippets/1/', 'style' => 'emacs', 'code' => 'print "Test POST Request"', 'owner' => 'user', 'title' => 'Default Title', 'linenos' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ) }, { 'code' => 'print "Test POST Request"', 'owner' => 'user', 'title' => 'Test Title', 'linenos' => $VAR1->{'results'}[0]{'linenos'}, 'highlight' => 'http://127.0.0.1:8000/snippets/2/highlight/', 'language' => 'perl', 'id' => 2, 'url' => 'http://127.0.0.1:8000/snippets/2/', 'style' => 'emacs' } ] }; #### $ curl -i -X POST -H "Content-Type:application/json" -u user:password http://localhost:8000/snippets/ -d '{ > "title": "Test Title", > "code": "print \"Test POST Request\"", > "linenos": false, > "language": "perl", > "style": "emacs" > }' HTTP/1.0 201 Created Date: Fri, 06 Apr 2018 09:14:54 GMT Server: WSGIServer/0.1 Python/2.7.12 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN Content-Type: application/json Content-Length: 252 Allow: GET, POST, HEAD, OPTIONS {"url":"http://localhost:8000/snippets/2/","id":2,"highlight":"http://localhost:8000/snippets/20/highlight/","owner":"user","title":"Test Title","code":"print \"Test POST Request\"","linenos":false,"language":"perl","style":"emacs"} #### my $headers = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)};