Defjs

Send a typed JSON body and decode a declared 201.

POST JSON

Hand the typed body to the builder. Logical field names stay in TypeScript; wire aliases on the struct become JSON keys. An object body is application/json.

See HTTP and Client for details.

import { createClient, defineRequest, struct, withEndpoint } from "@defjs/core";

const client = createClient(withEndpoint("https://api.example.com/v1"));

const User = struct.object({
  id: struct.number(),
  name: struct.string(),
  email: struct.string(),
});

const ApiError = struct.object({
  code: struct.string(),
  message: struct.string(),
});

const NewUser = struct.object({
  name: struct.string(),
  email: struct.string(),
});

const createUser = defineRequest({
  method: "POST",
  path: "/users",
  input: NewUser,
  builder: (input) => ({ body: input }),
  output: User,
  error: ApiError,
});

async function main() {
  const [error, user, response] = await createUser(client, {
    name: "Ada",
    email: "ada@example.com",
  });
  if (error?.code === "HTTP_STATUS") {
    console.error(error.status, error.data.message);
    return;
  }
  if (error) {
    console.error(error.code);
    return;
  }
  console.log(`Created ${user.name} → ${response.status}`);
}

void main();

api.example.com is a placeholder. With a server that answers 201 and { "id": 1, "name": "Ada", "email": "ada@example.com" }, the snippet prints:

Created Ada → 201
Edit this page on GitHub
Released under the MIT License. · Copyright © 2026 MunMunMiao

On this page