HTTP requests, simply

It's long been common to use the LWP::Simple module for quick HTTP requests where you only need to retrieve the contents of a website and put them somewhere. Nowadays I would highly recommend the very neat ojo module from the Mojolicious framework for oneliners, but I have created another alternative using just core modules.

HTTP::Simple implements similar functions to LWP::Simple using the core HTTP::Tiny. One other important difference is that it will throw exceptions whenever there is an error, rather than sometimes returning undef which the user can't do anything with. For oneliners, exceptions are very useful as they will print out what went wrong and cause the script to exit with a failure code; for scripts, they can be easily handled with modules like Syntax::Keyword::Try to perform the appropriate action.

Like in LWP::Simple, the getprint and getstore functions are optimized to stream data as it is received rather than collecting it all in memory (the mirror function also does this, as implemented in HTTP::Tiny). I also added in a few more convenience functions: getjson, which is like get but decodes the response from JSON; and three POST functions: postform, postjson, and postfile, which will each send a POST request with the appropriate type of content. postfile will also stream the file contents rather than reading it all into memory.

While I still prefer the flexibility of using HTTP::Tiny directly, I hope that this can be a useful alternative to LWP::Simple for those who want just a little more conciseness.


LWP::Protocol::PSGI converted me back from HTTP::Tiny

For all HTTP::Tiny's joys, LWP::Protocol::PSGI makes testing delightful

Leave a comment

About Grinnz

user-pic I blog about Perl.