Skip to content

Examples

This section contains complete, runnable examples demonstrating api.zig features.

Available Examples

REST API

ExampleDescriptionKey Features
REST APIComplete CRUD APIMulti-threading, Path params, Status codes
HTML PagesServer-rendered pagesHTML templates, CSS styling, Mixed content
Path ParametersDynamic URL segmentsSingle/multiple params, Type conversion
Static File ServerServe directoriesDirectory serving, MIME types, Security

GraphQL

ExampleDescriptionKey Features
Basic GraphQLComplete GraphQL APISchema, Queries, Mutations, 5 UI providers
GraphQL SubscriptionsReal-time updatesWebSocket, Live data, Chat example

Real-time

ExampleDescriptionKey Features
WebSocket ChatReal-time chatWebSocket, Rooms, Broadcasting
Live DashboardMetrics dashboardServer-Sent Events, Auto-refresh

Running Examples

Build and run the main example:

bash
zig build run

Output:

[OK] http://127.0.0.1:8000
[INFO]   /docs   - Interactive API Documentation
[INFO]   /redoc  - API Reference

Source Files

Example files in examples/ directory:

  • hello_world.zig - Minimal example
  • static_file_server.zig - Directory serving
  • graphql_server.zig - GraphQL API

The main example demonstrates:

  • HTML pages with modern CSS templates
  • JSON API endpoints with proper status codes
  • Path parameters ({id}) and query parameters
  • Multi-threading with configurable thread count
  • Access logging with request details

Quick Start

The simplest api.zig application:

zig
const std = @import("std");
const api = @import("api");

fn hello() api.Response {
    return api.Response.text("Hello, World!");
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    var app = try api.App.init(allocator, .{});
    defer app.deinit();

    try app.get("/", hello);
    try app.run(.{ .port = 8000 });
}

Output:

[OK] http://127.0.0.1:8000
[INFO]   /docs   - Interactive API Documentation
[INFO]   /redoc  - API Reference

Handler Types

api.zig supports multiple handler signatures:

zig
// Simple handler (no context needed)
fn simple() api.Response {
    return api.Response.text("Hello");
}

// Context handler (access params, headers, body)
fn withContext(ctx: *api.Context) api.Response {
    const id = ctx.param("id") orelse "0";
    _ = id;
    return api.Response.jsonRaw(\\{"id":1});
}

HTTP Methods

Register handlers for all standard HTTP methods:

zig
try app.get("/resource", getHandler);
try app.post("/resource", postHandler);
try app.put("/resource/{id}", putHandler);
try app.patch("/resource/{id}", patchHandler);
try app.delete("/resource/{id}", deleteHandler);
try app.options("/resource", optionsHandler);
try app.head("/resource", headHandler);
try app.trace("/resource", traceHandler);

Configuration Tables

App Init Options

OptionTypeDescription
title[]const u8OpenAPI title
version[]const u8API version
description[]const u8API description

Server Run Options

OptionTypeDefaultDescription
portu168000Listen port
address[]const u8"127.0.0.1"Bind address
num_threads?u32CPU countWorker threads
enable_access_logbooltrueRequest logging
max_body_sizeusize10MBMax body size

Released under the MIT License.