PHP Classes

PHP REST Client Class: Send REST request to a HTTP server

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStarStar 72%Total: 956 All time: 3,772 This week: 75Up
Version License PHP version Categories
rest 1.0.14MIT/X Consortium ...5.3.3HTTP, PHP 5, Web services
Description 

Author

This package can send REST request to a HTTP server.

It can send HTTP GET, POST, PUT, DELETE, PATCH REST requests to a given API server

The package provide encoders and decoders for the parameters to be passed to the server and the responses returned to the client.

Currently it supports encoders and decoders for JSON and XML formats, so can take parameters and encode in those formats before sending to the server, as well take data in those formats from the server responses and decode them to restore the original values.

Innovation Award
PHP Programming Innovation award nominee
April 2016
Number 5


Prize: One subscription to the PDF edition of the PHP Architect magazine
PHP REST APIs are well disseminated by now. Sending API calls to REST APIs is easy.

However, often you need to encode data you send and decode data you receive into PHP variables.

This class makes that process easier by providing filters that can automatically encode request data and decode responses that come in JSON or XML formats.

Manuel Lemos
Picture of Unay Santisteban
  Performance   Level  
Name: Unay Santisteban is available for providing paid consulting. Contact Unay Santisteban .
Classes: 7 packages by
Country: Spain Spain
Age: 35
All time rank: 73316 in Spain Spain
Week rank: 15 Up1 in Spain Spain Up
Innovation award
Innovation award
Nominee: 3x

Winner: 2x

Example

<?php

require_once '../vendor/autoload.php';

try {

   
$api = new \OtherCode\Rest\Rest(new \OtherCode\Rest\Core\Configuration(array(
       
'url' => 'http://jsonplaceholder.typicode.com/',
    )));
   
$api->setDecoder("json");

   
$response = $api->get("posts/1");
   
var_dump($response);

} catch (\
Exception $e) {

    print
$e->getMessage();

}



Details

Rest Client

Build Status Latest Stable Version License Total Downloads codecov

Rest client to make GET, POST, PUT, DELETE, PATCH, etc calls.

Installation

To install the package we only have to add the dependency to *composer.json* file:

{
    "require": {
      "othercode/rest": "*"
    }
}

And run the following command:

composer install

Usage

To use the Rest we only have to instantiate it and configure the params we want. We can establish the configuration accessing to the ->configuration->configure_property, for example to configure the url of the call we only have to set the ->configuration->url parameter like we can see as follows:

$api = new \OtherCode\Rest\Rest();
$api->configuration->url = "http://jsonplaceholder.typicode.com/";

or

$api = new \OtherCode\Rest\Rest(new \OtherCode\Rest\Core\Configuration(array(
    'url' => 'http://jsonplaceholder.typicode.com/',
)));

After this we have to set the type of call and the parameters that we wil use, in this case we are going to perform a GET request to the "posts/1" endpoint:

$response = $api->get("posts/1");

The rest client will throw a ConnectionException if there any problem related to the connection.

NOTE: These errors are related to the session cURL, here is the complete list

Methods

The available methods to work with are:

get()

Perform a GET request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made $data | Array | Optional. Associative array of data parameters

Return: Response object

head()

Perform a HEAD request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made

Return: Response object (no body)

post()

Perform a POST request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made $data | Array | Optional. Associative array of data parameters

Return: Response object

delete()

Perform a DELETE request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made $data | Array | Optional. Associative array of data parameters

Return: Response object

put()

Perform a PUT request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made $data | Array | Optional. Associative array of data parameters

Return: Response object

patch()

Perform a PATCH request.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $url | String | Required. The URL to which the request is made $data | Array | Optional. Associative array of data parameters

Return: Response object

getMetadata()

Return the metadata of the request.

Return: Array

getError()

Return the last known error.

Return: Error object

getPayloads()

Return an array with the Response and Request objects.

Return: Array

setDecoder()

Set a new Decoder.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $name | String | Required. The unique name of the decoder. $decoder | String | Optional. The class name with namespace of the new decoder.

Return: Rest object

setEncoder()

Set a new Encoder.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $name | String | Required. The unique name of the encoder. $encoder | String | Optional. The class name with namespace of the new encoder.

Return: Rest object

setModule()

Set a new Module.

Parameters | Type | Description ----------------------------- | ------- | ------------------------------------------- $name | String | Required. The unique name of the module. $module | String | Required. The class name with namespace of the new module. $hook | String | Optional. The hook name (after/before) that will trigger the module, 'after' by default.

Return: Rest object

unsetModule()

Unregister a module.

Parameters | Type | Description ----------------------------- | ------ | ------------------------------------------- $moduleName | String | Required. The unique name of the decoder. $hook | String | Optional. The hook name (after/before) from where delete the module.

Return: Rest object

addHeader()

Add a new header.

Parameters | Type | Description ----------------------------- | ------ | ------------------------------------------- $header | String | Required. The unique name of the header. $value | String | Requires. The value of the header.

Return: Rest object

addHeaders()

Add an array of headers.

Parameters | Type | Description ----------------------------- | ------ | ------------------------------------------- $headers | String | Required. An array of headers.

Return: Rest object

NOTE: We can use the addHeader() and addHeaders() methods with the Rest instance or with the configuration object

$api->addHeader('some_header','some_value');
$api->addHeaders(array('some_header' => 'some_value','other_header' => 'other_value'));

is the same as

$api->configuration->addHeader('some_header','some_value');
$api->configuration->addHeaders(array('some_header' => 'some_value','other_header' => 'other_value'));

removeHeader()

Remove a header offset.

Parameters | Type | Description ----------------------------- | ------ | ------------------------------------------- $header | String | Required. The unique name of the header.

Return: Rest object

removeHeaders()

Remove an array of headers.

Parameters | Type | Description ----------------------------- | ------ | ------------------------------------------- $headers | String | Required. An array of headers to remove.

Return: Rest object

Modules

This package allow you to create modules to perform task before and after the request.. To create a new module we only have to use this template:

class CustomModule extends BaseModule
{
    public function run()
    {
        // do something
    }
}

IMPORTANT: Any module MUST extends BaseModule

The only method that is mandatory is ->run(), this method execute your custom code of the module.

Once we have our module we can register it with the ->setModule() method. This method needs three parameters, the first one is the name of the module, the second one is the complete namespace of the module, and the third one is the hook name for our module, it can be "before" and "after" depends when we want to launch our module.

$api->setModule('module_name','Module\Complete\Namespace','after');

For "before" modules you can use all the properties of the Request object.

  • `method`
  • `url`
  • `headers`
  • `body`

For "after" modules you can use all the properties of the Response object.

  • `code`
  • `content_type`
  • `charset`
  • `body`
  • `headers`
  • `error`
  • `metadata`

All modules are executed in the order that we register them into the Rest client, this also affect to Decoders and Encoders.

Decoders

A decoder is a kind of module that allows you to automatically decode de response in xml or json, to use them we only have to set the decoder we want with the ->setDecoder() method:

$api->setDecoder("json");

The default allowed values for this method are: *json,xmlandxmlrpc*. All the decoders are always executed in the "after" hook.

Custom Decoders

To create a new decoder we only have to use this template:

class CustomDecoder extends BaseDecoder
{
	protected $contentType = 'application/json';

	protected function decode()
	{
		// decode $this->body
	}
}

Like in modules, we have the Response object available to work. The $contentType property is the content-type that will trigger the decoder, in the example above all responses with content-type "application/json" will trigger this decoder.

Quick Calls

We can do quick calls using the \OtherCode\Rest\Payloads\Request::call() method. This static method returns a Rest instance so we can use all the methods from it.

$response = \OtherCode\Rest\Payloads\Request::call('http://jsonplaceholder.typicode.com')
    ->setDecoder('json')
    ->get('/posts/1');

Complete Example

require_once '../autoload.php';

try {

    $api = new \OtherCode\Rest\Rest(new \OtherCode\Rest\Core\Configuration(array(
        'url' => 'http://jsonplaceholder.typicode.com/',
        'httpheader' => array(
            'some_header' => 'some_value',
        )
    )));
    $api->setDecoder("json");
    
    $response = $api->get("posts/1");
    var_dump($response);
    
} catch (\Exception $e) {
    print "> " . $e->getMessage() . "\n"
}

  Files folder image Files (42)  
File Role Description
Files folder imageexamples (3 files)
Files folder imagesrc (1 file, 4 directories)
Files folder imagetests (9 files, 2 directories)
Accessible without login Plain text file LICENSE.md Lic. Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (42)  /  examples  
File Role Description
  Accessible without login Plain text file get_json_request.php Example Example script
  Accessible without login Plain text file get_xml_request.php Example Example script
  Accessible without login Plain text file post_json_request.php Example Example script

  Files folder image Files (42)  /  src  
File Role Description
Files folder imageCore (4 files)
Files folder imageExceptions (4 files)
Files folder imageModules (2 files, 2 directories)
Files folder imagePayloads (3 files)
  Plain text file Rest.php Class Class source

  Files folder image Files (42)  /  src  /  Core  
File Role Description
  Plain text file Configuration.php Class Class source
  Plain text file Core.php Class Class source
  Plain text file CurlOpts.php Class Class source
  Plain text file Error.php Class Class source

  Files folder image Files (42)  /  src  /  Exceptions  
File Role Description
  Plain text file ConfigurationException.php Class Class source
  Plain text file ConnectionException.php Class Class source
  Plain text file ModuleNotFoundException.php Class Class source
  Plain text file RestException.php Class Class source

  Files folder image Files (42)  /  src  /  Modules  
File Role Description
Files folder imageDecoders (5 files)
Files folder imageEncoders (4 files)
  Plain text file BaseModule.php Class Class source
  Plain text file ModuleInterface.php Class Class source

  Files folder image Files (42)  /  src  /  Modules  /  Decoders  
File Role Description
  Plain text file BaseDecoder.php Class Class source
  Plain text file DecoderInterface.php Class Class source
  Plain text file JSONDecoder.php Class Class source
  Plain text file XMLDecoder.php Class Class source
  Plain text file XMLRPCDecoder.php Class Class source

  Files folder image Files (42)  /  src  /  Modules  /  Encoders  
File Role Description
  Plain text file BaseEncoder.php Class Class source
  Plain text file EncoderInterface.php Class Class source
  Plain text file JSONEncoder.php Class Class source
  Plain text file XMLRPCEncoder.php Class Class source

  Files folder image Files (42)  /  src  /  Payloads  
File Role Description
  Plain text file Headers.php Class Class source
  Plain text file Request.php Class Class source
  Plain text file Response.php Class Class source

  Files folder image Files (42)  /  tests  
File Role Description
Files folder imageModules (1 file, 2 directories)
Files folder imageRest (1 file)
  Plain text file ConfigurationTest.php Class Class source
  Plain text file DecodersTest.php Class Class source
  Plain text file EncodersTest.php Class Class source
  Plain text file ErrorTest.php Class Class source
  Plain text file HeadersTest.php Class Class source
  Plain text file ModulesTest.php Class Class source
  Plain text file QuickCallsTest.php Class Class source
  Plain text file ResponseTest.php Class Class source
  Accessible without login Plain text file RestTest.php Test Unit test script

  Files folder image Files (42)  /  tests  /  Modules  
File Role Description
Files folder imageDecoders (1 file)
Files folder imageEncoders (1 file)
  Plain text file Dummy.php Class Class source

  Files folder image Files (42)  /  tests  /  Modules  /  Decoders  
File Role Description
  Plain text file DummyDecoder.php Class Class source

  Files folder image Files (42)  /  tests  /  Modules  /  Encoders  
File Role Description
  Plain text file DummyEncoder.php Class Class source

  Files folder image Files (42)  /  tests  /  Rest  
File Role Description
  Plain text file CoreTester.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:956
This week:0
All time:3,772
This week:75Up
User Ratings User Comments (1)
 All time
Utility:85%StarStarStarStarStar
Consistency:82%StarStarStarStarStar
Documentation:75%StarStarStarStar
Examples:71%StarStarStarStar
Tests:71%StarStarStarStar
Videos:-
Overall:72%StarStarStarStar
Rank:155
 
Congratulations, this is a amazing class ;-)
8 years ago (José Filipe Lopes Santos)
90%StarStarStarStarStar