13

How do you make HTTP requests with Raku? I'm looking for the equivalent of this Python code:

import requests

headers = {"User-Agent": "python"}
url = "http://example.com/"
payload = {"hello": "world"}

res = requests.get(url, headers=headers)
res = requests.post(url, headers=headers, json=payload)
Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
R891
  • 2,550
  • 4
  • 18
  • 30

3 Answers3

16

You may want to try out the recent HTTP::Tiny module.

use HTTP::Tiny;
my $response = HTTP::Tiny.new.get( 'https://example.com/' );
say $response<content>.decode
Scimon Proctor
  • 4,558
  • 23
  • 22
  • 1
    Thanks, that seem better than what I was doing. That page also led me to `HTTP::UserAgent`. I added another related question here, because the responses from them are producing unexpected results when I convert the responses from JSON. https://stackoverflow.com/questions/65014105/extracting-json-from-a-raku-http-client-request-perl-6 – R891 Nov 25 '20 at 23:27
11

After searching around a bit, I found an answer in the Cro docs.

use Cro::HTTP::Client;

my $resp = await Cro::HTTP::Client.get('https://api.github.com/');
my $body = await $resp.body;

# `$body` is a hash
say $body;

There's more information on headers and POST requests in the link.

R891
  • 2,550
  • 4
  • 18
  • 30
5

I want to contribute a little more. There is a fantastic module named WWW. It's very convenient to make 'gets' that receive json because it can be parsed automagically.

In their example:

use WWW;
my $response = jget('https://httpbin.org/get?foo=42&bar=x');

You can examine the objects using the basic functionalities of arrays and hashes, for example to extract the values of my response you can use:

$response<object_you_want_of_json><other_nested_object>[1]<the_last_level>

Here the number [1] are a nested list inside a hash, and the properties are the same. Welcome to the raku community !!!

metagib
  • 223
  • 1
  • 5
  • Thanks, that looks good, but when I do `zef install WWW` it asks for my Github username and password in the terminal, which makes me a little nervous. Should it be doing that when I install packages with zef? – R891 Dec 12 '20 at 04:36
  • 1
    I too am having issues with ```zef install WWW``` and have raised an [issue][1] [1]: https://github.com/raku-community-modules/WWW/issues/19 – librasteve Dec 13 '20 at 21:58
  • Looks okay now: `Installing: WWW:ver<1.005006>:auth` – jubilatious1 Jul 17 '22 at 15:00