Sample code for 30+ languages & platforms
Zig

REST POST JSON using Gzip Content Encoding

See more REST Examples

Demonstrates how to send a JSON POST using the gzip Content-Encoding.

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();

    // This requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // Use the online tool at https://tools.chilkat.io/Default.cshtml
    // to generate the JSON code that creates this JSON:

    // {
    //     "lists": [
    //         {
    //             "id": "1511199999"
    //         }
    //     ],
    //     "confirmed": false,
    //     "email_addresses": [
    //         {
    //             "email_address": "support@chilkatsoft.com"
    //         }
    //     ],
    //     "first_name": "Matt",
    //     "last_name": "Smith"
    // }
    //

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("lists[0].id", "1511199999") catch {};
    json.updateBool("confirmed", false) catch {};
    json.updateString("email_addresses[0].email_address", "support@chilkatsoft.com") catch {};
    json.updateString("first_name", "Matt") catch {};
    json.updateString("last_name", "Smith") catch {};

    const rest = try chilkat.Rest.init();
    defer rest.deinit();

    rest.connect("api.constantcontact.com", 443, true, true) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    rest.addHeader("Content-Type", "application/json") catch {};
    rest.addHeader("Authorization", "Bearer xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx") catch {};

    // Tell the server you'll accept only an application/json response.
    rest.addHeader("Accept", "application/json") catch {};

    // Indicate that we'll be sending the request body gzipped.
    rest.addHeader("Content-Encoding", "gzip") catch {};

    const sb_req = try chilkat.StringBuilder.init();
    defer sb_req.deinit();
    json.emitSb(sb_req) catch {};

    // Send the POST.
    const sb_resp = try chilkat.StringBuilder.init();
    defer sb_resp.deinit();
    rest.fullRequestSb("POST", "/v2/contacts?action_by=ACTION_BY_VISITOR&api_key=xxxxxxx", sb_req, sb_resp) catch {
        std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Response body:\n", .{});
    std.debug.print("{s}\n", .{try sb_resp.getAsString(alloc)});

    if (rest.getResponseStatusCode() != 200) {
        std.debug.print("Received error response code: {d}\n", .{rest.getResponseStatusCode()});
        return;
    }

    const json_resp = try chilkat.JsonObject.init();
    defer json_resp.deinit();
    json_resp.loadSb(sb_resp) catch {};

    // Use the online tool at https://tools.chilkat.io/jsonParse.cshtml
    // to generate the JSON code that parses the JSON response..
}