Examples

Copy a small example and start building

These examples use API calls that already exist in the repository.

Routing

Health endpoint

Create an app, register a GET route and run the server.

basic.c
#include <libchttpx.h>

static void health(chttpx_request_t* req, chttpx_response_t* res)
{
    (void)req;
    *res = cHTTPX_ResMessage(cHTTPX_StatusOK, "healthy");
}

int main(void)
{
    chttpx_app_t app;
    if (cHTTPX_AppInit(&app) != CHTTPX_OK)
        return 1;

    chttpx_config_t config = cHTTPX_DefaultConfig();
    config.port = 8080;

    chttpx_serv_t* server = cHTTPX_AppServer(&app, "main", &config);
    chttpx_router_t router = cHTTPX_RoutePathPrefix(server, "");
    cHTTPX_Get(&router, "/health", health);

    int result = cHTTPX_AppRun(&app);
    cHTTPX_AppShutdown(&app);
    return result == CHTTPX_OK ? 0 : 1;
}
Open source example ↗
Middleware

Bearer authentication

Protect a route group with a small middleware function.

middleware.c
static chttpx_middleware_result_t authenticate(
    chttpx_request_t* req,
    chttpx_response_t* res)
{
    if (!cHTTPX_BearerToken(req))
    {
        *res = cHTTPX_ResError(
            cHTTPX_StatusUnauthorized,
            "bearer token required"
        );
        return out;
    }

    return next;
}

chttpx_router_t api = cHTTPX_RoutePathPrefix(server, "/api");
chttpx_router_t private_api = cHTTPX_RouteGroup(&api, "");
cHTTPX_RouterUse(&private_api, authenticate);
Open source example ↗
JSON

Bind and validate JSON

Describe fields once, validate the request and build a JSON response.

json.c
create_user_t payload = {0};

chttpx_validation_t fields[] = {
    cHTTPX_StringField(
        "email",
        &payload.email,
        true,
        3,
        254,
        CHTTPX_TRIM | CHTTPX_LOWERCASE,
        NULL
    )
};

if (!cHTTPX_BindJSON(req, res, fields, CHTTPX_ARRAY_LEN(fields)))
    return;

chttpx_json_t* json = cHTTPX_JsonObject(req);
cHTTPX_JsonString(json, "email", payload.email);
*res = cHTTPX_ResJsonObject(cHTTPX_StatusCreated, json);
Open source example ↗
See all examples on GitHub ↗