HTTP-API-Client

 view release on metacpan or  search on metacpan

lib/HTTP/API/Client.pm  view on Meta::CPAN

for this call (any casing: C<Authorization>, C<authorization>, ...) is
left alone rather than overwritten. Called by C<new_request()> - there is
normally no need to call this directly.

=head2 basic_authenticator($request, $username, $password)

Sets HTTP Basic auth on C<$request> via
C<< $request->headers->authorization_basic >>. Override this in a subclass
to change how basic auth is applied without touching the rest of request
building.

=head2 kvp2json(%options) / kvp2str(%options)

The two body encoders C<convert_data> dispatches to. C<kvp2json> walks
C<%options>'s C<data> hashref and JSON::XS-encodes it, resolving any
C<CODE> values by calling them and unwrapping L<HTTP::API::DataTypeMarker>'s
C<xBOOLEAN>-family markers into their JSON form; an C<xCSV>-marked value
has no special JSON handling and just JSON-encodes as an ordinary array
(there's no C<key=value&key=value> repetition problem in JSON for it to
solve). C<kvp2str> produces a C<key=value&key=value> query string instead,
with C<xCSV>-marked values joined by commas instead of repeated per key.
An empty arrayref value is omitted from C<kvp2str>'s output entirely (an
empty array has no C<key=value> representation), the same as a key
mapped to C<undef>/missing already is - including an empty array nested
inside an C<xCSV(...)> list, which contributes nothing to the joined
string rather than leaving a blank comma segment behind. An C<xCSV()>
with no elements at all is different: it still emits C<key=> (present,
empty value) rather than being omitted - there is no join-corruption
risk to avoid the way there is for a nested empty array, and C<key=> is
valid, parseable form data distinct from the key being absent.
Both respect an C<< $events->{keys} >> callback to control which keys are
included and in what order - its return value is deduplicated (first
occurrence wins, order otherwise preserved, not sorted) before use, so a
repeated key is processed once rather than once per occurrence; without
that, a C<CODE> value at that key would fire once per repeat and
C<kvp2str> would emit the same key twice with two different computed
values (HAC-129). Both also accept a C<skip_key> hashref in
C<%options> (same reachability caveat as C<new_request()>'s
C<skip_headers> above - only useful from a direct call, e.g. a C<data>
callback recursively re-invoking C<kvp2str()>/C<kvp2json()> on itself to
build its own value without infinite-looping on its own key; see
F<t/04_callbacks.t>) to exclude a key from the encoded body.

C<kvp2str> alone also fires C<< $events->{before_sorting_keys} >> and
C<< $events->{after_sorting_keys} >>, each called with C<< keys => \@keys
>> - an arrayref of the field names about to be (respectively, just
were) sorted. Both are genuinely live: a callback that mutates
C<@$keys> in place (push/splice/grep out an element) changes what
C<kvp2str> actually encodes, as long as C<< $events->{keys} >> isn't
also set (which replaces C<@keys> outright, discarding
C<before_sorting_keys>' mutation). See F<t/21_before_events.t> and
F<t/33_before_sorting_keys_mutation.t>. C<kvp2json> has no equivalent
hook - its C<@keys> is either C<< $events->{keys} >>'s return value or
an unsorted C<keys %$data>, with no separate sorting step to hook into.

C<kvp2json> encodes a numeric-looking string value as a genuine JSON
number rather than a quoted string - but only when doing so loses
nothing (stringifying the number back reproduces the original value
exactly). A value like C<"5"> becomes C<5>, but C<"00501"> (a US zip
code) or C<"5.0"> stays a string, since numifying either would silently
discard meaningful formatting. A value like C<"NaN">, C<"Inf">, or
C<"-Inf"> also stays a string even though it round-trips losslessly as
a Perl number - JSON has no valid representation for a non-finite
number, and numifying it would make C<kvp2json> emit the bareword
C<nan>/C<inf>/C<-inf>, which is not valid JSON and no parser (including
this module's own JSON::XS) can decode. C<kvp2str> never numifies at
all - a query string has no separate number/string type, so there was
never a reason to risk altering the original representation.

=head2 kvp2json_each(%options) / kvp2str_each(%options)

The per-value helpers C<kvp2json()>/C<kvp2str()> recurse into for each key
via C<%options>'s C<value> (and C<key> - the field's own key, available
to a C<CODE> value's callback via C<%options>; C<kvp2json_each> passes it
through at every level, including a nested hash value's own key, not
just the top-level field's). Resolves a C<CODE> value by calling it,
unwraps L<HTTP::API::DataTypeMarker> markers (C<xCSV>/C<xBOOLEAN> and
friends), and recurses into plain array values. There is normally no
need to call these directly - they exist as public methods so a
C<data>/C<value> callback can recursively re-invoke them on itself (see
C<kvp2json()>/C<kvp2str()> above).

These two are not symmetric on invalid input, in two ways. First,
C<kvp2json_each> dies if a raw-bytes (non-UTF8-flagged) value is not
valid UTF-8, rather than silently corrupting it into C<U+FFFD>
replacement characters - JSON has no way to represent arbitrary bytes.
C<kvp2str_each> has no such restriction; a query string can carry any
byte sequence unescaped-safe via percent-encoding, so the same input
that dies in the JSON path passes through the form-urlencoded path
unchanged. Second, a plain hash value recurses in C<kvp2json_each> (JSON
has a native object type for it) but dies in C<kvp2str_each> - a query
string has no standard convention for representing a nested hash.

C<undef> is also handled differently by nesting depth, deliberately left
this way rather than made symmetric. C<kvp2json()>'s own top-level loop
omits a key entirely when its value is C<undef> (see
L</"kvp2json(%options)"> above). A nested hash value's own
C<undef> sub-value is not: C<kvp2json_each>'s recursion into a hash value
has no equivalent skip step, so an C<undef> sub-value becomes an empty
JSON string (C<"">) rather than disappearing from the encoded object -
C<< kvp2json(data => { a => { x => 1, y => undef } }) >> encodes as
C<< {"a":{"x":1,"y":""}} >>, keeping C<y>, while the same C<undef> at the
top level would have dropped the key outright.

Both die - with the same message, naming the offending ref type and
pointing at C<xBOOLEAN()> - on any other reference type neither of them
otherwise recognizes, most commonly a bare (not C<xBOOLEAN>-wrapped)
scalar ref: a value like C<< \$flag >> passed directly, typically from
forgetting to call C<xBOOLEAN(\$flag)> around it. Before this die was
added, C<kvp2str_each> silently stringified such a value as
C<SCALAR(0x...)>, and C<kvp2json_each> reached the same outcome only by
accident of JSON::XS itself refusing to encode an arbitrary scalar ref
- with a message that never mentioned this module's own vocabulary.

C<kvp2str_each>'s C<%options> also accepts C<no_key>, set internally when
recursing into an ARRAY or C<xCSV> element: when true, the returned
fragment omits the leading C<key=> prefix (a plain scalar, C<xCSV>, and
C<xBOOLEAN>-marked value all honor this identically) so a CSV/array
element joins as a bare value rather than a spurious embedded
C<key=value> pair.

lib/HTTP/API/Client.pm  view on Meta::CPAN


    if (length($u) || length($p)) {
        $self->basic_authenticator( $request,
            _encode_if_utf8_flagged($u), _encode_if_utf8_flagged($p) );
    }
    elsif (length($at)) {
        $headers->{authorization} = $at
            unless grep { lc($_) eq 'authorization' } keys %$headers;
    }

    return $request;
}

sub _tune_utf8 {
    my ($content) = @_;

    my $req = HTTP::Request->new( POST => "http://find-encoding.com" );

    try {
        $req->content($content);
    }
    catch {
        my $error = $_;
        if ( $error =~ /content must be bytes/ ) {
            eval { $content = Encode::encode( utf8 => $content ); };
        }
    };
    return $content;
}

sub _should_skip_key {
    my (%o) = @_;
    my ($key, $data) = @o{qw(key data)};
    return $o{skip_key}{$key} || !exists $data->{$key} || !defined $data->{$key};
}

sub _encode_if_utf8_flagged {
    my ($v) = @_;
    return utf8::is_utf8($v) ? Encode::encode( utf8 => $v ) : $v;
}

sub _uri_escape_bytes_or_chars {
    my ($v) = @_;
    return uri_escape( _encode_if_utf8_flagged($v) );
}

sub _json_validate_utf8 {
    my ($v) = @_;
    return $v if utf8::is_utf8($v);
    my $decoded = eval { Encode::decode( utf8 => $v, Encode::FB_CROAK ) };
    die sprintf(
        "kvp2json_each: value is not valid UTF-8, refusing to silently corrupt it into JSON (raw bytes: %v02x)\n",
        $v
    ) if !defined $decoded;
    return $decoded;
}

sub _numify_if_lossless {
    my ($v) = @_;
    return $v if !looks_like_number($v);
    # NaN/Infinity have no valid JSON representation - JSON::XS's utf8-mode
    # encoder emits them as the bareword nan/inf/-inf, which is not valid
    # JSON. Leave the original string untouched rather than numifying into
    # a token no JSON parser (including JSON::XS itself) can decode.
    return $v if isnan($v + 0) || isinf($v + 0);
    # Compare against a throwaway stringified copy, not $v+0 itself - comparing
    # a number with eq caches a string form on that same scalar (SvPOK), and
    # JSON::XS then encodes it as a JSON string instead of a JSON number.
    my $stringified = ($v + 0) . '';
    return $v eq $stringified ? $v + 0 : $v;
}

sub convert_data {
    my ($self, %o) = @_;

    my ($data, $events) = @o{qw(data events)};

    my $content_type = $self->get_content_type(%o);

    if ($content_type =~ m/json/) {
        return $self->kvp2json(%o);
    }
    elsif ($content_type =~ m{^application/x-www-form-urlencoded(?:;|$)}) {
        return $self->kvp2str(%o);
    }
    else {
        return '' if !%$data;
        die "Unable to convert data for content_type: $content_type\n";
    }
}

sub kvp2json {
    my ($self, %o) = @_;

    my ($data, $events) = @o{qw(data events)};

    my $json = _apply_charset( $self->json, $self->charset );

    my @keys;

    if (my $do = $events->{keys}) {
        my %seen;
        @keys = grep { !$seen{$_}++ } $self->$do(%o);
    }
    else {
        @keys = keys %$data;
    }

    my %data = ();

    foreach my $key(@keys) {
        if ($events->{not_include}{$key}) {
            next
        }
        next if _should_skip_key(%o, key => $key);
        $data{$key} = $self->kvp2json_each(%o, key => $key, value => $data->{$key});
    }

    return $json->encode(\%data);
}



( run in 2.770 seconds using v1.01-cache-2.11-cpan-60884a8df76 )