2017 © Pedro Peláez
 

library hyper-http

HTTP client for PHP

image

rexlabs/hyper-http

HTTP client for PHP

  • Monday, July 30, 2018
  • by itsmejodie
  • Repository
  • 4 Watchers
  • 3 Stars
  • 13 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 3 Versions
  • 550 % Grown

The README.md

Deprecated

This library isn't in active development., (*1)

Please consider guzzlehttp/guzzle or another library instead., (*2)

Bug fixes only., (*3)

Hyper Http Client

License: MIT Packagist, (*4)

Overview

Hyper is an HTTP Client that aims to provide a simple, but powerful interface for making HTTP calls and fetching and manipulating API data., (*5)

Why use Hyper

  • Extremely simple interface Hyper::get('http://some/url').
  • Also supports object style Hyper::make(...)->get('http://some/url').
  • Provides a Response object which provides useful information like HTTP status code, body and headers.
  • Every Response mixes in rexlabs\array-object which allows you to easily interrogate API responses.
  • Throws a limited set of exceptions (with access to the request and/or response) when things go wrong.
  • You have access to the original Request via $response->getRequest().
  • Supports all of Guzzle client functionality including streams.
  • Allows you to dump cURL requests for reproducing from the command-line.
  • Easily log all requests

Usage

<?php
use Rexlabs\HyperHttp\Hyper;

$response = Hyper::get('http://openlibrary.org/subjects/love.json');

// The first book for 'love' is: Wuthering Heights
echo "The first book for '{$response->name}' is: {$response->works->first()->title}\n";

echo "Total works: {$response->works->count()} books\n";

Installation

To install in your project:, (*6)

composer require rexlabs/hyper-http

Examples

The RESTful methods all return a Response object which makes interacting with responses simple., (*7)

Example: Using static methods

<?php
use Rexlabs\HyperHttp\Hyper;

$response = Hyper::get('https://example.com/url');
echo 'Status Code: '.$response->getStatusCode()."\n";
echo (string)$response; // Output the response body

Example: Working with a JSON API

Since responses mixin ArrayObject you can easily fetch and manipulate values from the response:, (*8)

<?php
use Rexlabs\HyperHttp\Hyper;

// Fetch historical price via CryptoCompare's public API for Ethereum
$response = Hyper::get('https://min-api.cryptocompare.com/data/pricehistorical', [
    'fsym' => 'ETH',
    'tsyms' => 'BTC,USD',
    'ts' => '1452680400',
]);

// Output prices
printf("ETH->USD: %s\n", $response->get('ETH.USD'));
printf("ETH->BTC: %s\n", $response->get('ETH.BTC'));

Example: Set global headers and pass in a logger

Use make() to simplify instantiation and then setup the object for future requests:, (*9)

<?php
use Rexlabs\HyperHttp\Hyper;
use Rexlabs\Logger\CustomLogger;

$hyper = Hyper::make()
    ->setBaseUri('http://example.com/api/v1')
    ->setHeader('X-App-Identity', 'Some App')
    ->setHeader('X-Correlation-Id', '12345')
    ->setLogger(new CustomLogger);
  • $hyper = Hyper::make(array $config = [], \GuzzleHttp\Client $guzzle, \Psr\Log\LoggerInterface $logger)

Example: Instantiation via constructor

To get complete control over instantiation, use the constructor and pass in a Guzzle instance:, (*10)


<?php use Rexlabs\HyperHttp\Client; use GuzzleHttp\Client as GuzzleClient; use Psr\Log\NullLogger; $hyper = new Client(new GuzzleClient(), new NullLogger(), [ 'base_uri' => 'http://example.com/api/v1', 'headers' => [ 'X-App-Identity' => 'Some App', ], ]); $response = $hyper->get('/messages');

Example: Dumping a cURL request

You can easily generate a cURL request for running from the command-line to reproduce your last request:, (*11)

<?php
use Rexlabs\HyperHttp\Hyper;

echo Hyper::get('https://example.com/api/v1/resources')
    ->getCurlRequest();

Output:, (*12)

curl \
  'https://min-api.cryptocompare.com/data/pricehistorical?fsym=ETH&tsyms=BTC%2CUSD&ts=1452680400&extraParams=your_app_name' \
  -H 'Content-Type: application/json' -H 'Accept: application/json'

Http Methods

Hyper provides the following methods for interacting with remote endpoints:, (*13)

get()

get(mixed $uri, array $query = [], array $headers = [], array $options = []): Response, (*14)

Send an HTTP GET request, and return the Response:, (*15)

$response = Hyper::get('https://example.com', ['sort' => 'latest'], ['X-Greeting' => 'Hello!']);

$response = $hyper->get('/v1/people');
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $query is an optional array of query parameters which will be appended to the uri.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

post()

post(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response, (*16)

Send an HTTP POST request, and return the Response:, (*17)

$response = Hyper::post('https://example.com/fruit', 'apples');

$response = $hyper->post('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $body is the payload. If you provide an array, it will be converted and transported as json.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

Alternative methods:, (*18)

  • $response = $hyper->postForm($uri, $formParams, $headers, $options);
  • $response = $hyper->postMultipartForm($uri, $formParams, $headers, $options);

put()

put(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response, (*19)

Send an HTTP PUT request, and return the Response:, (*20)

$response = Hyper::put('https://example.com/fruit', 'apples');

$response = $hyper->put('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $body is the payload. If you provide an array, it will be converted and transported as json.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

patch()

patch(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response, (*21)

Send an HTTP PATCH request, and return the Response:, (*22)

$response = Hyper::patch('https://example.com/fruit', 'apples');

$response = $hyper->patch('/v1/people', ['name' => 'Bob', 'age' => 25]);
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $body is the payload. If you provide an array, it will be converted and transported as json.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

delete()

delete(mixed $uri, mixed $body = null, array $headers = [], array $options = []): Response, (*23)

Send an HTTP DELETE request, and return the Response:, (*24)

$response = Hyper::delete('https://example.com/fruit', 'apples');

$response = $hyper->delete('/v1/people/1');
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $body is the optional payload. If you provide an array, it will be converted and transported as json.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

call()

call(string $method, mixed $uri, mixed $body, array $headers, array $options): Response, (*25)

Send a generic HTTP request by specifying the method as the first argument., (*26)

// Statically
$response = Hyper::call('MOVE', 'myfile1234', ['new_location' => 'some_folder']);

// Http method verbs may also be invoked via method name
$response = Hyper::move('myfile1234', ['new_location' => 'some_folder']);
$response = Hyper::somethingelse(...);

// Via object
$response = $hyper->call('MOVE', 'myfile1234', ['new_location' => 'some_folder']);
  • $method is the HTTP verb. Eg. GET or something not part of the standard.
  • $uri is a string or a Uri. If the string is not absolute it will be appended to the base uri.
  • $body is the optional payload. If you provide an array, it will be converted and transported as json.
  • $headers is an optional array of headers (indexed by header name) that will be merged with any global headers.
  • $options is an optional array of Guzzle client options.

Request Methods

Methods available from the Rexlabs\HyperHttp\Message\Request object:, (*27)

getUri()

Return the UriInterface object which encapsulates the URI/URL for this request., (*28)

getMethod()

Return the HTTP method verb for this Request., (*29)

getHeaders()

Retur an array of headers for this Request, (*30)

getCurl()

Return a cURL request (string) suitable for running from the command-line. Useful for debugging requests., (*31)

Response Methods

Methods available from the Rexlabs\HyperHttp\Message\Response object:, (*32)

getRequest()

Return the Rexlabs\HyperHttp\Message\Request object associated with the Response, (*33)

getCurlRequest()

Return a cURL request (string) suitable for running from the command-line. Useful for debugging requests., (*34)

getStatusCode()

Return the HTTP status code for this Response. EG. 200, (*35)

getReasonPhrase()

Return the HTTP reason phrase associated with the status code. EG. "OK", (*36)

isJson()

Returns true if this is a JSON response., (*37)

toArray()

Converts a JSON response to an array and returns the array., (*38)

toObject()

Converts a JSON response to an ArrayObject, (*39)

ArrayObject

Every Response object has all of the methods and functionality of the ArrayObject class from the rexlabs\array-object package., (*40)

This means based on the following response payload:, (*41)

{
  "books": [
    {
      "id": 1,
      "title": "1984",
      "author": "George Orwell"
    },
    {
      "id": 2,
      "title": "Pride and Prejudice",
      "author": "Jane Austen"
    }
  ]
}

You can perform the following functions:, (*42)

$response->books; // Instance of ArrayObject
$response->books->pluckArray('author'); // array [ 'George Orwell', 'Jane Austen' ]
$response->pluckArray('books.author'); // array [ 'George Orwell', 'Jane Austen' ]
$response->books->count(); // 2
$response->books->isCollection(); // true
$response->books[0]; // Instance of ArrayObject
$response->books[0]->isCollection(); // false
$response->books[0]->id; // 1
$response->get('books.1.title');    // "Pride and Prejudice"
foreach ($response->books as $book) {
    echo "{$book->title} by {$book->author}\n";
}

You can also call:, (*43)

$obj = $response->toObject();   // Instance of Arraybject

Config

Set default config for all client's (defaults to []), (*44)

Hyper::setDefaultConfig($config);

Set config for this client (values will override / merge with default), (*45)

$client = Hyper::make($config);

Default Logger

Set the default logger used by all clients that don't provide one.
Must implement LoggerInterface (defaults to NullLogger), (*46)

Hyper::setDefaultLogger($logger);

Log Curl

Log the curl string for all requests (requires a logger set), (*47)

$config = [
    'log_curl' => true,
];

Guzzle config

Set the config passed to the underlying GuzzleClient, (*48)

$config = [
    'guzzle' => [
        'verify' => false,
    ],
];

// Set for all clients
Hyper::setDefaultConfig($config);

// Set for one client
$client = Hyper::make($config);

Tests

To run tests:, (*49)

composer tests

To run coverage report:, (*50)

composer coverage

Coverage report is output to ./tests/report/index.html, (*51)

Extending

Hyper allows extension for custom clients by:, (*52)

  • Storing separate instances for each subclass of Hyper for static use
    • Static use of MyHyperSubclass will return the correct instance created by MyHyperSubclass
    • Static use of Hyper will return the correct instance created by Hyper
  • Override protected static function makeClient to customise client class (eg replace new Client with new MyClient)
  • Override protected static function makeConfig to customise default client config
  • Override protected static function makeGuzzleConfig to customise default guzzle client
  • Override protected static function getBaseUri to provide a default base_uri to the client

Contributing

Contributions are welcome, please submit a pull-request or create an issue. Your submitted code should be formatted using PSR-1/PSR-2 standards., (*53)

About

  • Author: Jodie Dunlop
  • License: MIT
  • Copyright (c) 2018 Rex Software Pty Ltd

The Versions

30/07 2018

dev-master

9999999-dev

HTTP client for PHP

  Sources   Download

MIT

The Requires

 

The Development Requires

by Jodie Dunlop

api json library http request restful post fluent

18/07 2018

2.0.0

2.0.0.0

HTTP client for PHP

  Sources   Download

MIT

The Requires

 

The Development Requires

by Jodie Dunlop

api json library http request restful post fluent

28/02 2018

1.0.0

1.0.0.0

HTTP client for PHP

  Sources   Download

MIT

The Requires

 

The Development Requires

by Jodie Dunlop

api json library http request restful post fluent