#Using zig http client

1 messages · Page 1 of 1 (latest)

ebon fjord
#

Hi all, i am sending a request to the
https://uselessfacts.jsph.pl/api/v2/facts/random
using the zig http client, and following somewhat of this https://zig.news/nameless/coming-soon-to-a-zig-near-you-http-client-5b81 example.
I am just not sure how can i extract the text field, and how could i for example print it out to console.

I would say i need to use req.response.parser . but i am not sure how to exactly to "reach" the underlying value.

Thanks!

Zig NEWS

Forewarning: This post is intended to be a overview of the new features included under std.http. As...

lusty prawn
#

req.reader().readAllAlloc(allocator, std.math.maxInt(usize))

#

reader gives you a reader from which you can read your data as required

#

here it would read as much data as the server is willing to give

ebon fjord
#

Okay, but what then ?
Isnt there a way to get underlying data ? Reader has not much info on it in documentation, and other helper methods read bytes, do i need somehow to convert this stream of bytes or ?
Also response from that link is json, do i need to use some serialize / deserialize library to get underlying data easier

native tree
# ebon fjord Okay, but what then ? Isnt there a way to get underlying data ? Reader has not ...

From the json pattern on the website you can construct a struct to hold that data, parse the string you get with std.json, and then print the text:

const Data = struct {
    id: []const u8,
    text: []const u8,
    source: []const u8,
    source_url: []const u8,
    language: []const u8,
    permalink: []const u8,
};

pub fn main() !void {
  // ...
  const json_str = try req.reader().readAllAlloc(alloc, std.math.maxInt(usize));
  defer alloc.free(json_str);

  const data = try std.json.parseFromSlice(Data, alloc, json_str, .{});
  defer data.deinit();

  std.debug.print("fact! {s}\n", .{data.value.text});
}
ebon fjord
#

Okay, this does work, but i feel its quite confusing, why are all the fields of Data struct u8 ?, wouldnt it make sense for text to be a string ?
first you fetch and store to memory all the data from response, and then try to parse it to json struct representation and lastly we print out one of the struct fields to console

native tree
#

theres no "string" type in zig, []const u8 is how we represent a string of text

#

parsing it into a struct is just the easiest way to access the fields of a json string as far as i know

lusty prawn
native tree
lusty prawn
#

the new std.json does this

#

thanks whoever did that

#

std.json.parseFrom* with Value

native tree
#

oh sweet

ebon fjord
lusty prawn
#

yep