Sample code for 30+ languages & platforms
Zig

OpenAI (ChatGPT) Create Image

See more OpenAI ChatGPT Examples

Show how to send a POST to create an image. Gets the JSON response with URLs and then downloads images to files.

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 example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const http = try chilkat.Http.init();
    defer http.deinit();

    // Implements the following CURL command:

    // curl https://api.openai.com/v1/images/generations \
    //   -H "Content-Type: application/json" \
    //   -H "Authorization: Bearer $OPENAI_API_KEY" \
    //   -d '{
    //     "prompt": "A cute baby sea otter",
    //     "n": 2,
    //     "size": "1024x1024"
    //   }'

    // Use the following online tool to generate HTTP code from a CURL command
    // Convert a cURL Command to HTTP Source Code

    // Use this online tool to generate code from sample JSON:
    // Generate Code to Create JSON

    // The following JSON is sent in the request body.

    // {
    //   "prompt": "A cute baby sea otter",
    //   "n": 2,
    //   "size": "1024x1024"
    // }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("prompt", "A cute baby sea otter") catch {};
    json.updateInt("n", 2) catch {};
    json.updateString("size", "1024x1024") catch {};

    // Adds the "Authorization: Bearer $OPENAI_API_KEY" header.
    // This is NOT a real key.  Change the "sk-vi...." to your own key.
    http.setAuthToken("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");

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpJson("POST", "https://api.openai.com/v1/images/generations", json, "application/json", resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    const sb_response_body = try chilkat.StringBuilder.init();
    defer sb_response_body.deinit();
    resp.getBodySb(sb_response_body) catch {};

    const j_resp = try chilkat.JsonObject.init();
    defer j_resp.deinit();
    j_resp.loadSb(sb_response_body) catch {};
    j_resp.setEmitCompact(false);

    std.debug.print("Response Body:\n", .{});
    std.debug.print("{s}\n", .{try j_resp.emit(alloc)});

    const resp_status_code = resp.getStatusCode();
    std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
    if (resp_status_code >= 400) {
        std.debug.print("Response Header:\n", .{});
        std.debug.print("{s}\n", .{try resp.getHeader(alloc)});
        std.debug.print("Failed.\n", .{});
        return;
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "created": 1589478378,
    //   "data": [
    //     {
    //       "url": "https://..."
    //     },
    //     {
    //       "url": "https://..."
    //     }
    //   ]
    // }

    // Sample code for parsing the JSON response...
    // Use the following online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    var url: [:0]const u8 = "";
    const sb_local_file_path = try chilkat.StringBuilder.init();
    defer sb_local_file_path.deinit();

    // Download each image..
    http.clearHeaders();
    http.setAuthToken("");

    _ = j_resp.intOf("created");
    var i: i32 = 0;
    const count_i = j_resp.sizeOfArray("data");
    while (i < count_i) {
        j_resp.setI(i);
        url = try j_resp.stringOf(alloc, "data[i].url");

        sb_local_file_path.setString("c:/aaworkarea/image_") catch {};
        sb_local_file_path.appendInt(i + 1) catch {};
        sb_local_file_path.append(".png") catch {};

        http.download(url, try sb_local_file_path.getAsString(alloc)) catch {
            std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
            return;
        };

        i = i + 1;
    }
}