Sample code for 30+ languages & platforms
Zig

Send a Staged REST Request with a Binary Body

See more REST Examples

Demonstrates Rest.SendReqBd, which sends a request whose binary body is read from a BinData, then reads the response in separate steps.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

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;
    };

    // The file paths are relative to the application's current working directory.  Absolute paths
    // may also be used.  Supply the paths appropriate to your own environment.

    // Send a request whose binary body is read from a BinData.
    const bd_body = try chilkat.BinData.init();
    defer bd_body.deinit();
    bd_body.loadFile("qa_data/image.png") catch {
        std.debug.print("Failed to load the request body file.\n", .{});
        return;
    };

    rest.addHeader("Content-Type", "image/png") catch {};

    rest.sendReqBd("PUT", "/api/images/1", bd_body) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    // After sending, read the response status line and header fields.  The return value is the HTTP
    // status code, or -1 if no response was received.
    const status_code = rest.readResponseHeader();
    if (status_code < 0) {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Response status code: {d}\n", .{status_code});

    // Read the response body as text.
    const response_body = rest.readRespBodyString(alloc) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

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