GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
JSON::API(3) User Contributed Perl Documentation JSON::API(3)

JSON::API - Module to interact with a JSON API

  use JSON::API;
  my $api = JSON::API->new("http://myapp.com/");
  my $obj = { name => 'foo', type => 'bar' };
  if ($api->put("/add/obj", $obj) {
    print "Success!\n";
  } else {
    print $api->errstr . "\n";
  }

This module wraps JSON and LWP::UserAgent to create a flexible utility for accessing APIs that accept/provide JSON data.

It supports all the options LWP supports, including authentication.

Creates a new JSON::API object for connecting to any API that accepts and provide JSON data.

Example:

        my $api = JSON::API->new("https://myapp.com:8443/path/to/app",
                user => 'foo',
                pass => 'bar',
                realm => 'my_protected_site',
                agent => 'MySpecialBrowser/1.0',
                cookie_jar => '/tmp/cookie_jar',
        );

Parameters:

base_url
The base URL to apply to all requests you send this api, for example:

https://myapp.com:8443/path/to/app

parameters
This is a hash of options that can be passed in to an LWP object. Additionally, the user, pass, and realm may be provided to configure authentication for LWP. You must provide all three parameters for authentication to work properly.

Specifying debug => 1 in the parameters hash will also enable debugging output within JSON::API.

Additionally you can specify predecodehook in the parameters hash with a reference to a subroutine. The subroutine will then be called with the received raw content as only parameter before it is decoded. It then can preprocess the content e.g. alter it to be valid json. An example use case for this is calling a JSON API that prefixes the json with garbage to prevent CSRF. The pre-decode hook can then strip the garbage from the raw content before the JSON data is being decoded.

Perform an HTTP action (GET|POST|PUT|DELETE) against the given API. All methods take the path to the API endpoint as the first parameter. The put() and post() methods also accept a second data parameter, which should be a reference to be serialized into JSON for POST/PUTing to the endpoint.

All methods also accept an optional apphdr parameter in the last position, which is a hashref. The referenced hash contains header names and values that will be submitted with the request. See HTTP::Headers. This can be used to provide If-Modified or other headers required by the API.

If called in scalar context, returns the deserialized JSON content returned by the server. If no content was returned, returns an empty hashref. To check for errors, call errstr or was_success.

If called in list context, returns a two-value array. The first value will be the HTTP response code for the request. The second value will either be the deserialized JSON data. If no data is returned, returns an empty hashref.

Performs an HTTP GET on the given path. path will be appended to the base_url provided when creating this object. If given a data object, this will be turned into querystring parameters, with URI encoded values.

  my $obj = $api->get('/objects/1');
  # Automatically add + encode querystring params
  my $obj = $api->get('/objects/1', { param => 'value' });

Performs an HTTP PUT on the given path, with the provided data. Like get, this will append path to the end of the base_url.

  $api->put('/objects/', $obj);

Performs an HTTP POST on the given path, with the provided data. Like get, this will append path to the end of the base_url.

  $api->post('/objects/', [$obj1, $obj2]);

Performs an HTTP DELETE on the given path. Like get, this will append path to the end of the base_url.

  $api->del('/objects/first');

Returns the last "HTTP::Response", or undef if none or if the last request didn't generate one. This can be used to obtain detailed status.
With no argument, "header" returns a list of the header fields in the last response. If a field name is specified, returns the value(s) of the named field. A multi-valued field will be returned comma-separated in scalar context, or as separate values in list context. See "HTTP::Header".

This snippet can be used to dump all the response headers:

 print "$_ => ", scalar $api->header($_), "\n" foreach ($api->header);

Returns the current error string for the last call.

Returns whether or not the last request was successful.

Returns the complete URL of a request, when given a path.

This is a more advanced example of accessing the GitHub API. It uses a custom request header and conditional GET requests for efficiency. It falls-back to unconditional GET when necessary.

This code uses constants and methods from "IO::SOCKET::SSL" and "Storable". Error handling and logging have been omitted for clarity.

  my $repo = eval { lock_retrieve( "repo.status" ) };
  my $api = JSON::API->new( 'https://api.github.com/repos/user/app',
                            agent => "$prog/$VERSION",
                            protocols_allowed => [ qw/https/ ],
                            env_proxy => 1,
                            ssl_opts => { verify_hostname => $vhost || 0,
                                          SSL_verify_mode => ( $vhost?
                                                               SSL_VERIFY_PEER :
                                                               SSL_VERIFY_NONE ) },
                          );
  my($rc, $tags) = ( $repo && $repo->{tags_etag} )?
      $api->get( '/tags', undef, { Accept => 'application/vnd.github.v3+json',
                                   If_None_Match => $repo->{tags_etag}, } ) :
      $api->get( '/tags', undef, { Accept => 'application/vnd.github.v3+json' } );
  unless( ref $tags && $api->was_success ) {
      exit( 1 );
  }
  if( $api->can( 'header' ) ) {
      if( $rc == HTTP_NOT_MODIFIED ) {
          $tags = $repo->{tags};
      } else {
          $repo ||= {};
          $repo->{tags_etag} = $api->header( 'ETag' );
          $repo->{tags} = $tags;
          eval { lock_store( $repo, 'repo.status' ) };
      }
  }

<https://github.com/geofffranks/json-api>

    Geoff Franks <gfranks@cpan.org>

Copyright 2014, Geoff Franks

This library is licensed under the GNU General Public License 3.0

2022-04-08 perl v5.32.1

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.