Fork me on GitHub

HTTPFUL

Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client. Httpful includes...

Here's a quick snippet to whet your appetite. Search the Twitter API.

                $url = "http://search.twitter.com/search.json?q=" . urlencode('#PHP');
                $response = Request::get($url)
                    ->withXTrivialHeader('Just as a demo')
                    ->send();

                foreach ($response->body->results as $tweet) {
                    echo "@{$tweet->from_user} tweets \"{$tweet->text}\"\n";
                }
            

Note the chaining, the albeit trivial custom header (for the sake of demoing), and the automatic parsing based on Content-Type of response.

Install Option 1: Phar

IDEAL FOR: Quick hacking or small projects

Httpful provides a PHP Archive file that includes the entire library. Simply download this file and include it in your code.

                    <?php
                    // Point to where you downloaded the phar
                    include('./httpful.phar');

                    // And you're ready to go!
                    $response = \Httpful\Request::get('http://example.com')->send();
                    ...
                

Install Option 2: Composer

IDEAL FOR: Projects that already support Composer, the sane alternative to PEAR.

Composer is starting to emerge as the true people's package manager for PHP. If you aren't already using it, you should give it a shot. Simply add nategood/httpful to require in your composer.json file like below. After doing so, you're all set to start using Httpful! The autoloader provided by composer takes care of the rest!

                    {
                        "require": {
                            "nategood/httpful": "*"
                        }
                    }
                

Lastly, Httpful supports the PSR-0 standard, therefore, if your project already includes a PSR-0 compliant autoloader, just drop Httpful in your vendor library. If you don't have an autoloader, Httpful comes with a very simple one. You can use this autoloader by simply including the "bootstrap.php" file (located in the base directory of Httpful).

Get & Parse JSON

Send off a GET request. Get automatically parsed JSON response.

The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.

                    $uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
                    $response = Request::get($uri)->send();

                    echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
                

Get & Parse XML

Get XML. Parse an XML response.

Although the library does "smart parsing" based off Content-Type, we can also explicitly state how to parse a response. We've done so here with the `expectsXml` method. Other common Mime types are supported this way as well (expectsJson, expectsHtml, etc.).

                    // Get GitHub Profile for nategood as XML
                    $uri = 'https://github.com/api/v2/xml/user/show/nategood';

                    $response = Request::get($uri)  // Will parse based on Content-Type
                        ->expectsXml()              // from the response, but can specify
                        ->send();                   // how to parse via expectsXml too.

                    echo "{$request->body->name} joined GitHub on " .
                        date('M jS', strtotime($request->body->{'created-at'})) ."\n";
                

Post XML

Post XML. Parse an XML response.

We're using a string as the "body" so the library sends it as is. If an associative array is provided, the library will serialize it to an XML string.

                    $response = Request::post($uri)
                        ->body('Value')
                        ->sendsXml()
                        ->send();
                

Put JSON w/ Basic Auth

Send off a PUT request. Send a JSON body. Use basic auth. Expect a JSON response. Send it off. Parse the response accordingly.

The library automatically serializes our body (associative hash) into valid JSON (if we specified a specific JSON string, it would skip this serialization step).

                    $response = Request::put($uri)                  // Build a PUT request...
                        ->sendsJson()                               // tell it we're sending (Content-Type) JSON...
                        ->authenticateWith('username', 'password')  // authenticate with basic auth...
                        ->body('{"json":"is awesome"}')             // attach a body/payload...
                        ->send();                                   // and finally, fire that thing off!
                

Delete w/ Client Side Cert Auth

Send off a DELETE request. Authenticate with a client side certificate.

                    $key        = '/path/to/client/key.pem';
                    $crt        = '/path/to/client/crt.pem';
                    $passphrase = 'for-your-key-if-needed';

                    $response = Request::get($uri)
                        ->authenticateWithCert($cert, $key, $passphrase)
                        ->send();
                

Custom Headers

Send GET request with some custom headers.

Httpful supports a clean, readable syntax for specifying custom request headers. The preferred syntax is to just add the header as an instance method call (e.g. xExampleHeader() or withXExampleHeader()). Httpful also supports adding headers via addHeader method, or multiple headers at once via the addHeaders method.

                    $response = Request::get($uri)
                        ->xExampleHeader("My Value")                // Add in a custom header X-Example-Header
                        ->withXAnotherHeader("Another Value")       // Sugar: You can also prefix the method with "with"
                        ->addHeader('X-Or-This', 'Header Value')    // Or use the addHeader method
                        ->addHeaders(array(
                            'X-Header-1' => 'Value 1',              // Or add multiple headers at once
                            'X-Header-2' => 'Value 2',              // in the form of an assoc array
                        ))
                        ->send();
                

Get CSV w/ custom response parser

Get CSV. Use a custom response parser to parse the CSV.

While the library supports several built in parsing options, Httpful also allows for specifying custom headers via Closures.

                    // Attach our own handler that could naively parse comma
                    // separated values into an array
                    $response = Request::get($uri)
                        ->parseWith(function($body) {
                            return explode(",", $body);
                        })
                        ->send();

                    echo "This response had " . count($response) . " values separated via commas";
                

Templates

Keep it DRY. Create a template request to model your other requests off of

Often, if we are working with an API, a lot of the headers we send to that API remain the same (e.g. the expected mime type, authentication headers, etc.). Usually it ends up in writing boiler plate code to get around this. Httpful solves this problem by letting you create "template" requests. Subsequent requests will, by default, use the headers and settings of that template request.

                    // Create the template
                    $template = Request::init()
                        ->method(Http::POST)        // Alternative to Request::post
                        ->withoutStrictSsl()        // Ease up on some of the SSL checks
                        ->expectsHtml()             // Expect HTML responses
                        ->sendsType(Mime::FORM);    // Send application/x-www-form-urlencoded

                    // Set it as a template
                    Request::ini($template);

                    // This new request will have all the settings
                    // of our template by default.  We can override
                    // any of these settings by settings them on this
                    // new instance as we've done with expected type.
                    $r = Request::get($uri)->expectsJson();