NAME
HTTP::API::Client - API Client
USAGE
use HTTP::API::Client;
my $ua1 = HTTP::API::Client->new;
my $ua2 = HTTP::API::Client->new(base_url => URI->new( $url ), pre_defined_headers => { X_COMPANY => 'ABC LTD' } );
my $ua3 = HTTP::API::Client->new(base_url => URI->new( $url ), pre_defined_data => { api_key => 123 } );
$ua->send( $method, $url, \%data, \%header );
Send short hand methods - get, post, head, put and delete
Example:
$ua->get( $url ) same as $ua->send( GET, $url );
$ua->post( $url, \%data, \%headers ) same as $ua->send( GET, $url, \%data, \%headers );
Get Json Data - grab the content body from the response and json decode
$ua = HTTP::API::Client->new(base_url => URI->new("http://google.com"));
$ua->get("/search" => { q => "something" });
my $hashref_from_decoded_json_string = $ua->json_response;
## ps. this is just an example to get json from a rest api
Send a query string to server
$ua = HTTP::API::Client->new( content_type => "application/x-www-form-urlencoded" );
$ua->post("http://google.com", { q => "something" });
my $response = $ua->last_response; ## is a HTTP::Response object
At the moment, only support query string and json data in and out
ATTRIBUTES
All constructor arguments below are also read-write accessors ($ua->base_url("http://new-host")), except engine which is read-only after construction. Several fall back to an environment variable (see "ENVIRONMENT VARIABLES") when not passed explicitly.
- base_url
-
Prefixed onto every
$pathpassed tosend()(and the shorthand methods). Not set by default - a bare path is used as-is. - username / password
-
HTTP Basic auth credentials. If either is set, Basic auth is used and
auth_tokenis ignored. Default fromHTTP_USERNAME/HTTP_PASSWORD. - auth_token
-
Sent verbatim as the
Authorizationheader whenusername/passwordare both unset. Default fromHTTP_AUTH_TOKEN. - content_type
-
Forces the request content type. Left unset, GET defaults to
application/x-www-form-urlencodedand every other method defaults toapplication/json; charset=$charset. - charset
-
Used to build the default JSON content-type header and to decide whether UTF-8 byte-encoding is applied to the request body. Default
utf8, fromHTTP_CHARSET. - timeout
-
Request timeout in seconds, passed to the underlying LWP::UserAgent. Default
60, fromHTTP_TIMEOUT. - ssl_verify
-
Passed through as
verify_hostnameto LWP::UserAgent'sssl_opts. Default off (0), fromSSL_VERIFY. - pre_defined_data / pre_defined_headers / pre_defined_events
-
Hashrefs merged underneath the
%data/%headers/%eventspassed to each individual call - set once at construction time for values every request should carry (an API key, a fixed header, a standing callback), then override per-call as needed. - engine
-
Read-only. Defaults to
"LWP::UserAgent", the only enginesend()actually dispatches requests through -_build_uawill call a same-named method on a subclass to build an alternate UA object, butsend()itself does not yet know how to use anything other than LWP::UserAgent with it (seet/12_unsupported_engine.t: setting a different engine fails with a clear error rather than silently doing nothing). - last_response
-
Read-write. The most recent HTTP::Response, set by
send()and read by "json_response"/"kvp_response".undefuntil the first request.
ENVIRONMENT VARIABLES
These enviornment variables expose the controls without changing the existing code.
HTTP VARIABLES
HTTP_USERNAME - basic auth username
HTTP_PASSWORD - basic auth password
HTTP_AUTH_TOKEN - basic auth token string
HTTP_CHARSET - content type charset. default utf8
HTTP_TIMEOUT - timeout the request for ??? seconds. default 60 seconds.
SSL_VERIFY - verify ssl url. default is off
DEBUG VARIABLES
DEBUG_IN_OUT - print out request and response in string to STDERR
DEBUG_SEND_OUT - print out request in string to STDERR
DEBUG_RESPONSE - print out response in string to STDERR
DEBUG_RESPONSE_HEADER_ONLY - print out response header only without the body
DEBUG_RESPONSE_IF_FAIL - narrows DEBUG_IN_OUT/DEBUG_RESPONSE to only print
on a failed response. Does nothing by itself -
DEBUG_IN_OUT or DEBUG_RESPONSE must also be set.
RETRY VARIABLES
RETRY_FAIL_RESPONSE - number of time to retry if resposne comes back is failed. default 0 retry
RETRY_FAIL_STATUS - only retry if specified status code. e.g. 500,404
RETRY_DELAY - retry with wait time of ??? seconds in between
METHODS
get / post / put / head / delete ($path, \%data, \%headers, \%events)
Shorthand for send($METHOD, $path, \%data, \%headers, \%events). $path is appended to the base_url attribute if one was given. Returns whatever send() returns - normally an HTTP::Response.
send($method, $path, \%data, \%headers, \%events)
Builds and sends one HTTP request, retrying per "ENVIRONMENT VARIABLES" if configured. %data and %headers are merged over pre_defined_data and pre_defined_headers. %events are the per-call callbacks documented under new_request() below. Sets and returns the last_response attribute.
Passing $events->{test_request_object} = 1 makes it return the built HTTP::Request instead of sending it - the way this module's own test suite inspects what would have gone out.
json_response
Decode the last_response body as JSON and return the resulting hashref. Never dies - a missing response or invalid JSON comes back as { status => "error", error => $message } instead.
kvp_response
Parse the last_response body as a key=value&key=value query string and return it as a hashref. Returns {} if no request has been made yet, or the response body is empty.
new_request(%options)
Builds the HTTP::Request for one call. This is where the %events callbacks passed to send() are read: before_headers, headers_keys / add_headers_keys (which header keys to consider, in what order), before_header/after_header keyed by header name, and after_header_keys - the hooks used to compute things like a signature header from other data at build time. See t/04_callbacks.t for a worked example (API key + signature).
%options also accepts skip_headers, a hashref of header names to exclude from the request no matter what %headers or the events above say. Only reachable by calling new_request() directly with it - send() never sets it, and setting it inside an %events callback has no effect (a callback receives a snapshot copy of %options, not the one new_request() itself is iterating). See t/23_skip_headers.t.
convert_data(%options)
Turn %options's data hashref into the request body, according to content type: JSON via kvp2json() if the content type contains json, a query string via kvp2str() if it is exactly application/x-www-form-urlencoded. Any other content type returns an empty string for empty data, or dies naming the content type - there is no generic way to serialize arbitrary data into an arbitrary content type.
prepare_request(%options)
Builds the bare HTTP::Request (method, URL, content-type header) and applies authentication: username/password take priority and are sent as HTTP Basic auth via basic_authenticator(); auth_token is used only if neither is set, and is sent as a raw Authorization header value verbatim (no Bearer prefix is added for you - include it in the token itself if the API expects one). Called by new_request() - there is normally no need to call this directly.
basic_authenticator($request, $username, $password)
Sets HTTP Basic auth on $request via $request->headers->authorization_basic. Override this in a subclass to change how basic auth is applied without touching the rest of request building.
kvp2json(%options) / kvp2str(%options)
The two body encoders convert_data dispatches to. kvp2json walks %options's data hashref and JSON::XS-encodes it, resolving any CODE values by calling them and unwrapping HTTP::API::DataTypeMarker markers (xCSV/xBOOLEAN and friends) into their JSON form. kvp2str does the same but produces a key=value&key=value query string instead, with xCSV-marked values joined by commas instead of repeated per key. Both respect an $events->{keys} callback to control which keys are included and in what order, and both accept a skip_key hashref in %options (same reachability caveat as new_request()'s skip_headers above - only useful from a direct call, e.g. a data callback recursively re-invoking kvp2str()/kvp2json() on itself to build its own value without infinite-looping on its own key; see t/04_callbacks.t) to exclude a key from the encoded body.