Zig Requires Chilkat v11.4.0+
Zig
Finnhub API - Get Stock Quote
See more AI Examples
Demonstrates how to get a stock quote from the Finnhub API.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// Replace with your actual Finnhub API key.
const api_key = "YOUR_FINNHUB_API_KEY";
const symbol = "AAPL";
const http = try chilkat.Http.init();
defer http.deinit();
// This is the URL without params.
const url_without_params = "https://finnhub.io/api/v1/quote";
const req = try chilkat.HttpRequest.init();
defer req.deinit();
// Add params that will be sent in the URL.
req.addParam("symbol", symbol);
req.addParam("token", api_key);
req.setHttpVerb("GET");
// Send the request to get the JSON response.
const resp = try chilkat.HttpResponse.init();
defer resp.deinit();
http.httpReq(url_without_params, req, resp) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
const json = try chilkat.JsonObject.init();
defer json.deinit();
resp.getBodyJson(json) catch {};
const status_code = resp.getStatusCode();
std.debug.print("response status code: {d}\n", .{status_code});
json.setEmitCompact(false);
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Sample result:
// {
// "c": 248.8,
// "d": -4.09,
// "dp": -1.6173,
// "h": 255.493,
// "l": 248.07,
// "o": 253.9,
// "pc": 252.89,
// "t": 1774641600
// }
if (status_code == 200) {
// Add the symbol to the top of the result.
json.addStringAt(0, "symbol", symbol) catch {};
// Rename members for clarification.
json.rename("c", "currentPrice") catch {};
json.rename("d", "change") catch {};
json.rename("dp", "percentChange") catch {};
json.rename("h", "high") catch {};
json.rename("l", "low") catch {};
json.rename("o", "open") catch {};
json.rename("pc", "prevClose") catch {};
json.rename("t", "unixTime") catch {};
std.debug.print("{s}\n", .{try json.emit(alloc)});
} else {
std.debug.print("Failed\n", .{});
}
}