summaryrefslogtreecommitdiff
path: root/lib/REST/Client.pm
blob: 8db7b8508786835460091b77e9995d6f4ac7ce34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
package REST::Client;
#ABSTRACT: A simple client for interacting with RESTful http/https resources

our $VERSION = '280';



use strict;
use warnings;
use 5.008_000;

use constant TRUE => 1;
use constant FALSE => 0;

use URI;
use LWP::UserAgent;
use Carp qw(croak carp);


sub new {
    my $class = shift;
    my $config;

    $class->_buildAccessors();

    if(ref $_[0] eq 'HASH'){
        $config = shift;
    }elsif(scalar @_ && scalar @_ % 2 == 0){
        $config = {@_};
    }else{
        $config = {};
    }

    my $self = bless({}, $class);
    $self->{'_config'} = $config;

    $self->_buildUseragent();

    return $self;
}


sub addHeader {
    my $self = shift;
    my $header = shift;
    my $value = shift;
    
    my $headers = $self->{'_headers'} || {};
    $headers->{$header} = $value;
    $self->{'_headers'} = $headers;
    return;
}


sub buildQuery {
    my $self = shift;

    my $uri = URI->new();
    $uri->query_form(@_);
    return $uri->as_string();
}




sub GET {
    my $self = shift;
    my $url = shift;
    my $headers = shift;
    return $self->request('GET', $url, undef, $headers);
}


sub PUT {
    my $self = shift;
    return $self->request('PUT', @_);
}


sub PATCH {
    my $self = shift;
    return $self->request('PATCH', @_);
}


sub POST {
    my $self = shift;
    return $self->request('POST', @_);
}


sub DELETE {
    my $self = shift;
    my $url = shift;
    my $headers = shift;
    return $self->request('DELETE', $url, undef, $headers);
}


sub OPTIONS {
    my $self = shift;
    my $url = shift;
    my $headers = shift;
    return $self->request('OPTIONS', $url, undef, $headers);
}


sub HEAD {
    my $self = shift;
    my $url = shift;
    my $headers = shift;
    return $self->request('HEAD', $url, undef, $headers);
}


sub request {
    my $self = shift;
    my $method  = shift;
    my $url     = shift;
    my $content = shift;
    my $headers = shift;

    $self->{'_res'} = undef;
    $self->_buildUseragent();


    #error check
    croak "REST::Client exception: First argument to request must be one of GET, PATCH, PUT, POST, DELETE, OPTIONS, HEAD" unless $method =~ /^(get|patch|put|post|delete|options|head)$/i;
    croak "REST::Client exception: Must provide a url to $method" unless $url;
    croak "REST::Client exception: headers must be presented as a hashref" if $headers && ref $headers ne 'HASH';


    $url = $self->_prepareURL($url);

    my $ua = $self->getUseragent();
    if(defined $self->getTimeout()){
        $ua->timeout($self->getTimeout);
    }else{
        $ua->timeout(300);
    }
    my $req = HTTP::Request->new( $method => $url );

    #build headers
    if(defined $content && length($content)){
        $req->content($content);
        $req->header('Content-Length', length($content));
    }else{
        $req->header('Content-Length', 0);
    }

    my $custom_headers = $self->{'_headers'} || {};
    for my $header (keys %$custom_headers){
        $req->header($header, $custom_headers->{$header});
    }

    for my $header (keys %$headers){
        $req->header($header, $headers->{$header});
    }


    #prime LWP with ssl certfile if we have values
    if($self->getCert){
        carp "REST::Client exception: Certs defined but not using https" unless $url =~ /^https/;
        croak "REST::Client exception: Cannot read cert and key file" unless -f $self->getCert && -f $self->getKey;

        $ua->ssl_opts(SSL_cert_file => $self->getCert);
        $ua->ssl_opts(SSL_key_file => $self->getKey); 
    }
   
    #prime LWP with CA file if we have one     
    if(my $ca = $self->getCa){
        croak "REST::Client exception: Cannot read CA file" unless -f $ca;
        $ua->ssl_opts(SSL_ca_file => $ca);
    }

    #prime LWP with PKCS12 certificate if we have one
    if($self->getPkcs12){
        carp "REST::Client exception: PKCS12 cert defined but not using https" unless $url =~ /^https/;
        croak "REST::Client exception: Cannot read PKCS12 cert" unless -f $self->getPkcs12;

        $ENV{HTTPS_PKCS12_FILE}     = $self->getPkcs12;
        if($self->getPkcs12password){
            $ENV{HTTPS_PKCS12_PASSWORD} = $self->getPkcs12password;
        }
    }

    my $res = $self->getFollow ? 
        $ua->request( $req, $self->getContentFile ) : 
        $ua->simple_request( $req, $self->getContentFile );

    $self->{_res} = $res;

    return $self;
}


sub responseCode {
    my $self = shift;
    return $self->{_res}->code;
}


sub responseContent {
    my $self = shift;
    return $self->{_res}->content;
}


sub responseHeaders {
    my $self = shift;
    return $self->{_res}->headers()->header_field_names();
}




sub responseHeader {
    my $self = shift;
    my $header = shift;
    croak "REST::Client exception: no header provided to responseHeader" unless $header;
    return $self->{_res}->header($header);
}


sub responseXpath {
    my $self = shift;

    require XML::LibXML;

    my $xml= XML::LibXML->new();
    $xml->load_ext_dtd(0);

    if($self->responseHeader('Content-type') =~ /html/){
        return XML::LibXML::XPathContext->new($xml->parse_html_string( $self->responseContent() ));
    }else{
        return XML::LibXML::XPathContext->new($xml->parse_string( $self->responseContent() ));
    }
}

# Private methods

sub _prepareURL {
    my $self = shift;
    my $url = shift;

    # Do not prepend default host to absolute URLs.
    return $url if $url =~ /^https?:/;

    my $host = $self->getHost;
    if($host){
        $url = '/'.$url unless $url =~ /^\//;
        $url = $host . $url;
    }
    unless($url =~ /^\w+:\/\//){
        $url = ($self->getCert ? 'https://' : 'http://') . $url;
    }

    return $url;
}

sub _buildUseragent {
    my $self = shift;

    return if $self->getUseragent();

    my $ua = LWP::UserAgent->new;
    $ua->agent("REST::Client/$VERSION");
    $self->setUseragent($ua);

    return;
}

sub _buildAccessors {
    my $self = shift;

    return if $self->can('setHost');

    my @attributes = qw(Host Key Cert Ca Timeout Follow Useragent Pkcs12 Pkcs12password ContentFile);

    for my $attribute (@attributes){
        my $set_method = "
        sub {
        my \$self = shift;
        \$self->{'_config'}{lc('$attribute')} = shift;
        return \$self->{'_config'}{lc('$attribute')};
        }";

        my $get_method = "
        sub {
        my \$self = shift;
        return \$self->{'_config'}{lc('$attribute')};
        }";


        {
            no strict 'refs';
            *{'REST::Client::set'.$attribute} = eval $set_method ;
            *{'REST::Client::get'.$attribute} = eval $get_method ;
        }

    }

    return;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

REST::Client - A simple client for interacting with RESTful http/https resources

=head1 VERSION

version 280

=head1 SYNOPSIS

 use REST::Client;
 
 #The basic use case
 my $client = REST::Client->new();
 $client->GET('http://example.com/dir/file.xml');
 print $client->responseContent();
  
 #A host can be set for convienience
 $client->setHost('http://example.com');
 $client->PUT('/dir/file.xml', '<example>new content</example>');
 if( $client->responseCode() eq '200' ){
     print "Updated\n";
 }
  
 #custom request headers may be added
 $client->addHeader('CustomHeader', 'Value');
  
 #response headers may be gathered
 print $client->responseHeader('ResponseHeader');
  
 #X509 client authentication
 $client->setCert('/path/to/ssl.crt');
 $client->setKey('/path/to/ssl.key');
  
 #add a CA to verify server certificates
 $client->setCa('/path/to/ca.file');
  
 #you may set a timeout on requests, in seconds
 $client->setTimeout(10);
  
 #options may be passed as well as set
 $client = REST::Client->new({
         host    => 'https://example.com',
         cert    => '/path/to/ssl.crt',
         key     => '/path/to/ssl.key',
         ca      => '/path/to/ca.file',
         timeout => 10,
     });
 $client->GET('/dir/file', {CustomHeader => 'Value'});
  
 # Requests can be specificed directly as well
 $client->request('GET', '/dir/file', 'request body content', {CustomHeader => 'Value'});

 # Requests can optionally automatically follow redirects and auth, defaults to
 # false 
 $client->setFollow(1);

 #It is possible to access the L<LWP::UserAgent> object REST::Client is using to
 #make requests, and set advanced options on it, for instance:
 $client->getUseragent()->proxy(['http'], 'http://proxy.example.com/');
  
 # request responses can be written directly to a file 
 $client->setContentFile( "FileName" );

 # or call back method
 $client->setContentFile( \&callback_method );
 # see LWP::UserAgent for how to define callback methods

=head1 DESCRIPTION

REST::Client provides a simple way to interact with HTTP RESTful resources.

=head1 METHODS

=head2 Construction and setup

=head3 new ( [%$config] )

Construct a new REST::Client. Takes an optional hash or hash reference or
config flags.  Each config flag also has get/set accessors of the form
getHost/setHost, getUseragent/setUseragent, etc.  These can be called on the
instantiated object to change or check values.

The config flags are:

=over 4

=item host

A default host that will be prepended to all requests using relative URLs.
Allows you to just specify the path when making requests.

The default is undef - you must include the host in your requests.

=item timeout

A timeout in seconds for requests made with the client.  After the timeout the
client will return a 500.

The default is 5 minutes.

=item cert

The path to a X509 certificate file to be used for client authentication.

The default is to not use a certificate/key pair.

=item key

The path to a X509 key file to be used for client authentication.

The default is to not use a certificate/key pair.

=item ca

The path to a certificate authority file to be used to verify host
certificates.

The default is to not use a certificates authority.

=item pkcs12

The path to a PKCS12 certificate to be used for client authentication.

=item pkcs12password

The password for the PKCS12 certificate specified with 'pkcs12'.

=item follow

Boolean that determins whether REST::Client attempts to automatically follow
redirects/authentication.  

The default is false.

=item useragent

An L<LWP::UserAgent> object, ready to make http requests.  

REST::Client will provide a default for you if you do not set this.

=back

=head3 addHeader ( $header_name, $value )

Add a custom header to any requests made by this client.

=head3 buildQuery ( [...] )

A convienience wrapper around URI::query_form for building query strings from a
variety of data structures. See L<URI>

Returns a scalar query string for use in URLs.

=head2 Request Methods

Each of these methods makes an HTTP request, sets the internal state of the
object, and returns the object.

They can be combined with the response methods, such as:

 print $client->GET('/search/?q=foobar')->responseContent();

=head3 GET ( $url, [%$headers] )

Preform an HTTP GET to the resource specified. Takes an optional hashref of custom request headers.

=head3 PUT ($url, [$body_content, %$headers] )

Preform an HTTP PUT to the resource specified. Takes an optional body content and hashref of custom request headers.

=head3 PATCH ( $url, [$body_content, %$headers] )

Preform an HTTP PATCH to the resource specified. Takes an optional body content and hashref of custom request headers.

=head3 POST ( $url, [$body_content, %$headers] )

Preform an HTTP POST to the resource specified. Takes an optional body content and hashref of custom request headers.

=head3 DELETE ( $url, [%$headers] )

Preform an HTTP DELETE to the resource specified. Takes an optional hashref of custom request headers.

=head3 OPTIONS ( $url, [%$headers] )

Preform an HTTP OPTIONS to the resource specified. Takes an optional hashref of custom request headers.

=head3 HEAD ( $url, [%$headers] )

Preform an HTTP HEAD to the resource specified. Takes an optional hashref of custom request headers.

=head3 request ( $method, $url, [$body_content, %$headers] )

Issue a custom request, providing all possible values.

=head2 Response Methods

Use these methods to gather information about the last requset
performed.

=head3 responseCode ()

Return the HTTP response code of the last request

=head3 responseContent ()

Return the response body content of the last request

=head3 responseHeaders()

Returns a list of HTTP header names from the last response

=head3 responseHeader ( $header )

Return a HTTP header from the last response

=head3 responseXpath ()

A convienience wrapper that returns a L<XML::LibXML> xpath context for the body content.  Assumes the content is XML.

=head1 TODO

Caching, content-type negotiation, readable handles for body content.

=head1 AUTHORS

=over 4

=item *

Miles Crawford <mcrawfor@cpan.org>

=item *

Kevin L. Kane <kkane@cpan.org>

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2008 by Miles Crawford.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut