Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.5.0+

curl with Variable Substitution in the Request Body

See more CURL Examples

This example demonstrates using variables located in the request body with the {{variable_name}} syntax.

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

    // Variables can also be used within the HTTP request body.
    // Variable names are enclosed between {{ and }}

    // Here is a curl command with two variables {{name}} and {{age}} located in the data.

    // curl -X POST https://api.example.com/data \
    //   -H "Content-Type: application/json" \
    //   -d '{"name":"{{name}}","age":{{age}}}'

    const sb_curl = try chilkat.StringBuilder.init();
    defer sb_curl.deinit();
    sb_curl.appendLn("curl -X POST https://api.example.com/data \\") catch {};
    sb_curl.appendLn("  -H \"Content-Type: application/json\" \\") catch {};
    sb_curl.appendLn("  -d '{\"name\":\"{{name}}\",\"age\":{{age}}}'") catch {};

    const curl = try chilkat.HttpCurl.init();
    defer curl.deinit();

    // Provide values for variables.
    curl.setVar("name", "Alice");
    curl.setVar("age", "30");

    // To demonstrate how the variables are replaced, this example does not execute the curl command.
    // Instead, it generates the raw HTTP request that would be sent if the curl command were run.
    const sb_raw_request = try chilkat.StringBuilder.init();
    defer sb_raw_request.deinit();
    curl.toRawRequest(try sb_curl.getAsString(alloc), sb_raw_request) catch {
        std.debug.print("{s}\n", .{try curl.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try sb_raw_request.getAsString(alloc)});

    // Output:

    // POST /data HTTP/1.1
    // Host: api.example.com
    // Content-Type: application/json
    // Content-Length: 25
    //
    // {"name":"Alice","age":30}

    // --------------------------------------------------------------------------------------------------
    // Note: Variable substitution in the request body can be turned off by
    // setting the EnableBodyVars property equal to false

    curl.setEnableBodyVars(false);

    curl.toRawRequest(try sb_curl.getAsString(alloc), sb_raw_request) catch {
        std.debug.print("{s}\n", .{try curl.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try sb_raw_request.getAsString(alloc)});

    // The raw request with body variable substitution disable:

    // Host: api.example.com
    // Content-Type: application/json
    // Content-Length: 33
    //
    // {"name":"{{name}}","age":{{age}}}
}