Giter Site home page Giter Site logo

httpful's Introduction

Httpful

Httpful is a simple Http Client library for PHP 8.0+. There is an emphasis of readability, simplicity, and flexibility – basically provide the features and flexibility to get the job done and make those features really easy to use.

Features

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, PATCH and OPTIONS)
  • Custom Headers
  • Automatic "Smart" Parsing
  • Automatic Payload Serialization
  • Basic Auth
  • Client Side Certificate Auth
  • Request "Templates"

Sneak Peak

Here's something to whet your appetite. Search the twitter API for tweets containing "#PHP". Include a trivial header for the heck of it. Notice that the library automatically interprets the response as JSON (can override this if desired) and parses it as an array of objects.

// Make a request to the GitHub API with a custom
// header of "X-Trvial-Header: Just as a demo".
$url = "https://api.github.com/users/nategood";
$response = \Httpful\Request::get($url)
    ->expectsJson()
    ->withXTrivialHeader('Just as a demo')
    ->send();

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

Installation

Composer

Httpful is PSR-0 compliant and can be installed using composer. Simply add nategood/httpful to your composer.json file. Composer is the sane alternative to PEAR. It is excellent for managing dependencies in larger projects.

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

Install from Source

Because Httpful is PSR-0 compliant, you can also just clone the Httpful repository and use a PSR-0 compatible autoloader to load the library, like Symfony's. Alternatively you can use the PSR-0 compliant autoloader included with the Httpful (simply require("bootstrap.php")).

Build your Phar

If you want the build your own Phar Archive you can use the build script included. Make sure that your php.ini has the Off or 0 value for the phar.readonly setting. Also you need to create an empty downloads directory in the project root.

Contributing

Httpful highly encourages sending in pull requests. When submitting a pull request please:

  • All pull requests should target the dev branch (not master)
  • Make sure your code follows the coding conventions
  • Please use soft tabs (four spaces) instead of hard tabs
  • Make sure you add appropriate test coverage for your changes
  • Run all unit tests in the test directory via phpunit ./tests
  • Include commenting where appropriate and add a descriptive pull request message

Changelog

1.0.0

  • SECURITY Make certificate validation the default. This is a potentially breaking change and as a result, bumping major version number in line with semver. Validation can still be skipped but must be explicitly skipped via withoutStrictSSL.
  • REFACTOR PR #305 Remove deprecated functionality pre PHP 8.1
  • REFACTOR Partially from PR #282 Add CI support for running tests now that Travis is gone.

0.3.2

  • REFACTOR PR #276 Add properly subclassed, more descriptive Exceptions for JSON parse errors

0.3.1

  • FIX PR #286 Fixed header case sensitivity

0.3.0

  • REFACTOR Dropped support for dead versions of PHP. Updated the PHPUnit tests.

0.2.20

  • MINOR Move Response building logic into separate function PR #193

0.2.19

  • FEATURE Before send hook PR #164
  • MINOR More descriptive connection exceptions PR #166

0.2.18

0.2.17

  • FEATURE PR #144 Adds additional parameter to the Response class to specify additional meta data about the request/response (e.g. number of redirect).

0.2.16

  • FEATURE Added support for whenError to define a custom callback to be fired upon error. Useful for logging or overriding the default error_log behavior.

0.2.15

  • FEATURE I #131 Support for SOCKS proxy

0.2.14

  • FEATURE I #138 Added alternative option for XML request construction. In the next major release this will likely supplant the older version.

0.2.13

  • REFACTOR I #121 Throw more descriptive exception on curl errors
  • REFACTOR I #122 Better proxy scrubbing in Request
  • REFACTOR I #119 Better document the mimeType param on Request::body
  • Misc code and test cleanup

0.2.12

  • REFACTOR I #123 Support new curl file upload method
  • FEATURE I #118 5.4 HTTP Test Server
  • FIX I #109 Typo
  • FIX I #103 Handle also CURLOPT_SSL_VERIFYHOST for strictSsl mode

0.2.11

  • FIX I #99 Prevent hanging on HEAD requests

0.2.10

  • FIX I #93 Fixes edge case where content-length would be set incorrectly

0.2.9

  • FEATURE I #89 multipart/form-data support (a.k.a. file uploads)! Thanks @dtelaroli!

0.2.8

  • FIX Notice fix for Pull Request 86

0.2.7

  • FIX I #86 Remove Connection Established header when using a proxy

0.2.6

  • FIX I #85 Empty Content Length issue resolved

0.2.5

  • FEATURE I #80 I #81 Proxy support added with useProxy method.

0.2.4

  • FEATURE I #77 Convenience method for setting a timeout (seconds) $req->timeoutIn(10);
  • FIX I #75 I #78 Bug with checking if digest auth is being used.

0.2.3

  • FIX Overriding default Mime Handlers
  • FIX PR #73 Parsing http status codes

0.2.2

  • FEATURE Add support for parsing JSON responses as associative arrays instead of objects
  • FEATURE Better support for setting constructor arguments on Mime Handlers

0.2.1

  • FEATURE PR #72 Allow support for custom Accept header

0.2.0

  • REFACTOR PR #49 Broke headers out into their own class
  • REFACTOR PR #54 Added more specific Exceptions
  • FIX PR #58 Fixes throwing an error on an empty xml response
  • FEATURE PR #57 Adds support for digest authentication

0.1.6

  • Ability to set the number of max redirects via overloading followRedirects(int max_redirects)
  • Standards Compliant fix to Accepts header
  • Bug fix for bootstrap process when installed via Composer

0.1.5

  • Use DIRECTORY_SEPARATOR constant PR #33
  • PR #35
  • Added the raw_headers property reference to response.
  • Compose request header and added raw_header to Request object.
  • Fixed response has errors and added more comments for clarity.
  • Fixed header parsing to allow the minimum (status line only) and also cater for the actual CRLF ended headers as per RFC2616.
  • Added the perfect test Accept: header for all Acceptable scenarios see @b78e9e82cd9614fbe137c01bde9439c4e16ca323 for details.
  • Added default User-Agent header
  • User-Agent: Httpful/0.1.5 + curl version + server software + PHP version
  • To bypass this "default" operation simply add a User-Agent to the request headers even a blank User-Agent is sufficient and more than simple enough to produce me thinks.
  • Completed test units for additions.
  • Added phpunit coverage reporting and helped phpunit auto locate the tests a bit easier.

0.1.4

  • Add support for CSV Handling PR #32

0.1.3

  • Handle empty responses in JsonParser and XmlParser

0.1.2

  • Added support for setting XMLHandler configuration options
  • Added examples for overriding XmlHandler and registering a custom parser
  • Removed the httpful.php download (deprecated in favor of httpful.phar)

0.1.1

  • Bug fix serialization default case and phpunit tests

0.1.0

  • Added Support for Registering Mime Handlers
  • Created AbstractMimeHandler type that all Mime Handlers must extend
  • Pulled out the parsing/serializing logic from the Request/Response classes into their own MimeHandler classes
  • Added ability to register new mime handlers for mime types

httpful's People

Contributors

andrzejd-pl avatar aonic avatar artistan avatar atymic avatar bitdeli-chef avatar bpedro avatar bradstinson avatar chris114782 avatar cviebrock avatar dtelaroli avatar edueo avatar felixkiss avatar fzipi avatar gelolabs avatar grachov avatar griffy avatar hello-josh avatar joaomachado avatar josch1710 avatar judev avatar leviticusmb avatar luads avatar mishak87 avatar nategood avatar nickl- avatar quafzi avatar racingdeveloper avatar ramiel avatar stewsnooze avatar zdouglas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

httpful's Issues

Namespace Backslash

Hi all,
I've been having problems to run the phar file in my server.
Locally I tested using xampp with PHP 5.4 and it works like a dream.
The problem is, the online server uses PHP 5.2 and as far as we know it doesn't accept Namespace Backslash.

Is there some alternative for this case? Maybe a .phar's file version written without backslash...

Thanks in advance

Better Exception Handling

Hi,

i have worked with httpful for a few weeks - good job. But i think the error handling needs some additions.

Take a closer look on following code lines:

Request::get($this->apiUrl)
    ->authenticateWith($this->apiUsername, $this->apiPassword)
    ->withoutStrictSSL()
    ->expectsJson()
    ->send();

If you use wrong connection information or the endpoint is still not reachable, httpful will always continue with auto parsing the response because of the following code lines

if ($result === false) {
    $this->_error(curl_error($this->_ch));
    throw new ConnectionErrorException('Unable to connect.');
}

and setting the curl option CURLOPT_RETURNTRANSFER. If this option is configured, curl never return false (look here for further details).

For this reason my application gets only a generic exception Unable to parse response as JSON

You should fix this and return the detailed cURL error information as an exception. You can find the complete cURL error codes here . So other users can catch it and handle their favourite cURL error code.

Greetings,
Patrick

PATCH Support

RFC

Include examples that use If-Match and If-Unmodified-Since precondition headers.

Content-Length wrong with multibyte body (UTF-8)

If installed extension mbstring and overloaded function strlen then length of content calculates incorrect.
So, solutions is use mb_strlen($payload, '8bit'). Or don't overload 'strlen', but if it already did...

Undefined offset: 10004

Hi!

after the last update i've this notice:

Notice: Undefined offset: 10004 in /Users/tondi/Documents/projects/Innobit.PrestaShopPlugIn/trunk/application/wwwRoot/modules/mxSync/vendor/nategood/httpful/src/Httpful/Request.php on line 440

I'm trying to figure out why!

Gabriele

Arbitrary 'Unable to parse response code from HTTP response due to malformed response' Exception is raised

Demo code:

<?php

include('include/httpful.phar');

function send($uri, $body) {
    $response = \Httpful\Request::post($uri)
                ->sendsXml()
                ->body($body)   
                ->expectsXml()
                ->send();
    return $response;
}

$uri = "http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/?input=xml&output=xml&key=";
$key = "Aor625SZAtBjek2AZV08BvD0x-vZ0CgjNYWkbIyE1uGmylsFRNzcPprIkFaFOZJI";

$xmlBody1 = "<GeocodeFeed >
<GeocodeEntity Id='1' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='1501 NE Davis St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='2' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='350 W Burnside St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='3' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='1005 W Burnside St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='4' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='911 NW 14th Ave, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>
</GeocodeFeed>";

$xmlBody2 = "<GeocodeFeed >
<GeocodeEntity Id='1' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='1501 NE Davis St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='2' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='350 W Burnside St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='3' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='1005 W Burnside St, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='4' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='911 NW 14th Ave, Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>

<GeocodeEntity Id='5' xmlns='http://schemas.microsoft.com/search/local/2010/5/geocode'>
    <GeocodeRequest Culture='en-us' Query='12000 SW 49th Ave  Portland, OR'>
    </GeocodeRequest>
</GeocodeEntity>
</GeocodeFeed>";

echo '<h1>Request #1:</h1>';
$r = send($uri . $key, $xmlBody1);
print_r($r);

echo '<h1>Request #2:</h1>';
$r = send($uri . $key, $xmlBody2);
print_r($r);

?>

Demo output:

Request #1:

Httpful\Response Object ( [body] => SimpleXMLElement Object ( [Copyright] => Copyright © 2013 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation. [BrandLogoUri] => http://spatial.virtualearth.net/Branding/logo_powered_by.png [StatusCode] => 201 [StatusDescription] => Created [AuthenticationResultCode] => ValidCredentials [TraceId] => 7b3cbdd74b644ec39a655a28f883c8b3|BAYM001576|02.00.117.2900| [ResourceSets] => SimpleXMLElement Object ( [ResourceSet] => SimpleXMLElement Object ( [EstimatedTotal] => 1 [Resources] => SimpleXMLElement Object ( [DataflowJob] => SimpleXMLElement Object ( [Id] => edf0d066d6604a898ae9e10630eb6fdf [Link] => https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/edf0d066d6604a898ae9e10630eb6fdf [Description] => Geocode [Status] => Pending [CreatedDate] => 2013-05-21T04:10:25.0189272-07:00 [CompletedDate] => SimpleXMLElement Object ( ) [TotalEntityCount] => 4 [ProcessedEntityCount] => 0 [FailedEntityCount] => 0 ) ) ) ) ) [raw_body] => Copyright © 2013 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.http://spatial.virtualearth.net/Branding/logo_powered_by.png201CreatedValidCredentials7b3cbdd74b644ec39a655a28f883c8b3|BAYM001576|02.00.117.2900|1edf0d066d6604a898ae9e10630eb6fdfhttps://spatial.virtualearth.net/REST/v1/dataflows/Geocode/edf0d066d6604a898ae9e10630eb6fdfGeocodePending2013-05-21T04:10:25.0189272-07:00400 [headers] => Httpful\Response\Headers Object ( [headers:Httpful\Response\Headers:private] => Array ( [cache-control] => no-cache [transfer-encoding] => chunked [content-type] => application/xml; charset=utf-8 [location] => https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/edf0d066d6604a898ae9e10630eb6fdf [server] => Microsoft-IIS/8.0 [x-ms-bm-ws-sn] => BAYM001576 [x-ms-bm-ws-info] => 0 [x-sds-elapsed] => 989 [x-aspnet-version] => 4.0.30319 [x-powered-by] => ASP.NET [date] => Tue, 21 May 2013 11:10:24 GMT ) ) [raw_headers] => HTTP/1.1 201 Created Cache-Control: no-cache Transfer-Encoding: chunked Content-Type: application/xml; charset=utf-8 Location: https://spatial.virtualearth.net/REST/v1/dataflows/Geocode/edf0d066d6604a898ae9e10630eb6fdf Server: Microsoft-IIS/8.0 X-MS-BM-WS-SN: BAYM001576 X-MS-BM-WS-INFO: 0 X-SDS-Elapsed: 989 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Tue, 21 May 2013 11:10:24 GMT [request] => Httpful\Request Object ( [uri] => http://spatial.virtualearth.net/REST/v1/Dataflows/Geocode/?input=xml&output=xml&key=Aor625SZAtBjek2AZV08BvD0x-vZ0CgjNYWkbIyE1uGmylsFRNzcPprIkFaFOZJI [method] => POST [headers] => Array ( ) [raw_headers] => POST /REST/v1/Dataflows/Geocode/?input=xml&output=xml&key=Aor625SZAtBjek2AZV08BvD0x-vZ0CgjNYWkbIyE1uGmylsFRNzcPprIkFaFOZJI HTTP/1.1 Host: spatial.virtualearth.net User-Agent: Httpful/0.1.7 (cURL/7.24.0 PHP/5.4.7 (WINNT) Apache/2.4.3 (Win32) OpenSSL/1.0.1c .4.7 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31) Content-Type: application/xml Accept: /; q=0.5, text/plain; q=0.8, text/html;level=3;q=0.9, application/xml [strict_ssl] => [content_type] => application/xml [expected_type] => application/xml [additional_curl_opts] => Array ( ) [auto_parse] => 1 [serialize_payload_method] => 2 [username] => [password] => [serialized_payload] => [payload] => [parse_callback] => [error_callback] => [follow_redirects] => [max_redirects] => 25 [payload_serializers] => Array ( ) [_ch] => Resource id #23 [_debug] => ) [code] => 201 [content_type] => application/xml [parent_type] => application/xml [charset] => utf-8 [is_mime_vendor_specific] => [is_mime_personal] => [parsers:Httpful\Response:private] => )

Request #2:

Fatal error: Uncaught exception 'Exception' with message 'Unable to parse response code from HTTP response due to malformed response' in phar://C:/xampp/www/geocode-2/include/httpful.phar/Httpful/Response.php:138 Stack trace: #0 phar://C:/xampp/www/geocode-2/include/httpful.phar/Httpful/Response.php(37): Httpful\Response->parseCode('HTTP/1.1 100 Co...') #1 phar://C:/xampp/www/geocode-2/include/httpful.phar/Httpful/Request.php(189): Httpful\Response->_construct('HTTP/1.1 201 Cr...', 'HTTP/1.1 100 Co...', Object(Httpful\Request)) #2 C:\xampp\www\geocode-2\test.php(10): Httpful\Request->send() #3 C:\xampp\www\geocode-2\test.php(50): send('http://spatial....', '?...') #4 {main} thrown in phar://C:/xampp/www/geocode-2/include/httpful.phar/Httpful/Response.php on line 138

The first request goes through fine, but when a little more xml data is added to the POST body, suddenly the response becomes "malformed".

Verbose\Debug Mode

  • Ability to get time it took to download
  • Ability to get size of download in bytes
  • Ability to see SSL handshake, etc.

Empty body

Hi!

I've noted this bug after commit ef6a59c

If you set 'Content-Length' to 0 some webserver/library won't see the body...

I've reverted to previous commit and everything works fine.

Proxy support

Would be nice to have basic proxy support. Nothing fancy no NTLM or auth needed, just a standard basic proxy

Download link on website is broken

The download link for the phar file on http://phphttpclient.com/ is broken.
Tis is the particular line
"Httpful provides a PHP Archive file that includes the entire library. Simply download this file and include it in your code."
Seems like the link was updated.

Allow passing parameters to simplexml_load_string

When executing Request::get($url)->send() to a third party API I get the following XML:

<ns1:DbInstanceInfos xmlns:ns1="http://api.xeround.com"><ns1:DbInstanceInfo xmlns:ns1="http://api.xeround.com"><ns1:creationDate>2011-11-27T11:11:54+02:00</ns1:creationDate><ns1:dataCenter>Rackspace-US-ORD1</ns1:dataCenter><ns1:dbInstanceId>2940</ns1:dbInstanceId><ns1:description></ns1:description><ns1:name>AAA</ns1:name><ns1:plan>Free</ns1:plan><ns1:remainingPlanDays>0</ns1:remainingPlanDays><ns1:size>0.244141</ns1:size><ns1:status>DROPPED</ns1:status><ns1:edition>BASIC</ns1:edition></ns1:DbInstanceInfo></ns1:DbInstanceInfos>

The httpful throws 'Unable to parse response as XML'.
The correct way to parse this XML is by providing simplexml_load_string with the namespace:

simplexml_load_string($xmlString, null, null, "http://api.xeround.com")

Please allow passing parameters to the simplexml_load_string method.

Thanks.

Add Ability to Register Custom Payload Parsers for Mime Types

Extend the parseWith behavior so that I can register a callback. To build off of the (native) CSV example...

Register:

\Httpful\Request::register('csv', function() {
    return explode(",", $body);
});

Now that I've registered the csv mime type, I can now use it like I use other mime types directly supported by the library
'expectsCsv' will now use my registered callback

\Httpful\Request::get("http://example.com/report.csv")->expectsCsv()->send();

This may be a nice way to handle the hypermedia stuff mentioned in issue #16.

Add ability for custom serialize payload hook

Right now by default the library will take a data structure that is to be used for the payload of a request and do it's best to turn it into a well structured serialized string. (e.g. calling json_encode on the payload when the Content-Type of the request is application/json).

A user may want to define their own serialization method in certain use cases (e.g. the user was using XML-RPC and didn't want to have to build long winded associative arrays for every request).

Content-type is required

When a document with no content type is parsed Httpful throws an exception:

"Undefined offset: 1" in response.php on line 158

Move tests to PHPUnit

Right now the tests were sort of whipped up in a very basic style, only leveraging PHP's native assert. Should move this to a more standard testing library.

Issue with httpful.phar include

I am using the latest version(httpful-0.2.0.phar) of HTTPFul phar. On the hosted setup I get following problem:
I have included phar as
include "./httpful.phar";
..........................
PHP Warning: include(): Failed opening 'phar://httpful.phar/Httpful/Bootstrap.php' for inclusion (include_path='.:') in /var/www/tut/soapsync/httpful.phar on line 4
PHP Fatal error: Class 'Httpful\Bootstrap' not found in /var/www/tut/soapsync/httpful.phar on line 5

while on my local(dev) setup it works fine.

Fatal error: Class 'Request' not found

Hello

Maybe I'm just new at this but I get this error no matter if I use the .phar or install using Composer (successfully). Monolog works so I don't think it's a problem with Composer. I've tried downgrading but to no avail, still the same error:

Fatal error: Class 'Request' not found in

I've tried both the Twitter and Google samples but it seems to be some kind of include problem?

Pre PHP 5.3 support

I've been using and loving httpful. However, I have been having to jump through hoops to get it to work on my hosting accounts that support PHP 5.2 by default.

Is there some way to use the library with PHP versions before 5.3?

Handle 204 and zero length content gracefully

I'm working with an REST API that responds to a successful DELETE with a 204 and no body (it clearly states this in the response headers with Content-Length: 0)

I found that httpful still tried to parse the response as JSON and falls over in a heap:

Fatal error: Uncaught exception 'Exception' with message 'Unable to parse response as JSON' in phar://C:/Users/colemanb/Documents/Cloud/hpcloud/PHP/lib/httpful.phar/Httpful/Handlers/JsonHandler.php:19
Stack trace:
#0 phar://C:/Users/colemanb/Documents/Cloud/hpcloud/PHP/lib/httpful.phar/Httpful/Response.php(92): Httpful\Handlers\JsonHandler->parse('')
#1 phar://C:/Users/colemanb/Documents/Cloud/hpcloud/PHP/lib/httpful.phar/Httpful/Response.php(41): Httpful\Response->_parse('')
#2 phar://C:/Users/colemanb/Documents/Cloud/hpcloud/PHP/lib/httpful.phar/Httpful/Request.php(174): Httpful\Response->__construct('', 'HTTP/1.1 204 No...', Object(Httpful\Request))
#3 C:\Users\colemanb\Documents\Cloud\hpcloud\PHP\hpcloud-api.php(107): Httpful\Request->send()
#4 C:\Users\colemanb\Documents\Cloud\hpcloud\PHP\demo.php(82): api_call_delete('HPAuth_4fb362aa...', 'https://az-2.re...', '41792484084457', 'servers/123657')
#5 {main}  thrown in phar://C:/Users/colemanb/Documents/Cloud/hpcloud/PHP/lib/httpful.phar/Httpful/Handlers/JsonHandler.php on line 19

I got round this by calling autoParse(false) however should the API call error in some way there might be content in the response body that I want to handle. Shouldn't the Response be checked to ensure it's not zero length before invoking the parser? This would make sense to me!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.