Sample code for 30+ languages & platforms
Zig

Read the REST Response Body into a StringBuilder

See more REST Examples

Demonstrates Rest.ReadRespSb, which reads the response body as text into a StringBuilder, replacing its previous contents.

Background. The staged request model separates sending from reading: a SendReq method transmits the request, ReadResponseHeader reads the status line and headers, and a ReadResp method reads the body. This gives fine control over large or streamed messages compared with the single-call full-request methods.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    const rest = try chilkat.Rest.init();
    defer rest.deinit();
    const b_tls = true;
    const b_auto_reconnect = true;
    rest.connect("example.com", 443, b_tls, b_auto_reconnect) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    rest.sendReqNoBody("GET", "/api/items/123") catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const status_code = rest.readResponseHeader();
    if (status_code < 0) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    // Read the response body as text into a StringBuilder, replacing its previous contents.
    const sb_response = try chilkat.StringBuilder.init();
    defer sb_response.deinit();
    rest.readRespSb(sb_response) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    const response_body = sb_response.getAsString(alloc) catch {
        std.debug.print("{s}\n", .{try sb_response.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{response_body});
}