Course of Raku / Functional, concurrent, reactive, and web programming / Web programming / A simple HTTP client

Using a client module

Writing HTTP by hand is instructive, but for real work you use a client module that handles the protocol, redirects, headers, and parsing for you. The modern choice in the Raku ecosystem is Cro, whose client makes a request in one line:

use Cro::HTTP::Client;

my $response = await Cro::HTTP::Client.get('http://example.com/');
say $response.status; # 200

Cro::HTTP::Client.get returns a promise — fitting, since a network request is work that finishes later — so you await it. The resulting response object knows its status, headers, and body, without you parsing any text yourself.

This example needs the Cro module installed (zef install cro) and a network connection.

To read the body, you await it too:

my $response = await Cro::HTTP::Client.get('http://example.com/');
my $body = await $response.body-text;
say $body.chars, ' characters';

Compared with the raw socket version, the module is shorter, safer, and far more capable. The lesson of this section is the layering: a high-level client is convenient and is what you should normally use, but underneath it is exactly the send-and-receive over a socket that you saw first.

Course navigation

Quiz — HTTP requests   |   A GET request


💪 Or jump directly to the exercises in this section.