Code

1 endpoint for generating TypeScript type definitions from JSON.

Method Endpoint Purpose
POST /v1/convert/json-to-typescript Generate TypeScript interfaces from a JSON object

REST API Examples

Convert code / generate TypeScript

curl -X POST "https://dev.toolkitapi.io/v1/convert/json-to-typescript" \
  -H "X-API-Key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"data": {"id": 1, "name": "Widget", "active": true}, "root_name": "Product"}'
const resp = await fetch("https://dev.toolkitapi.io/v1/convert/json-to-typescript", {
  method: "POST",
  headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({ data: { id: 1, name: "Widget" }, root_name: "Product" }),
});
const data = await resp.json();
console.log(data.typescript);

Python SDK Examples

The JSON-to-TypeScript endpoint is not yet exposed as a named method on the Convert SDK class. Call it directly via the underlying HTTP client.

Simple object to TypeScript

import httpx

data = {
    "userId": 1,
    "username": "janedoe",
    "email": "[email protected]",
    "isActive": True,
}

response = httpx.post(
    "https://dev.toolkitapi.io/v1/convert/json-to-typescript",
    json={"data": data, "root_name": "User"},
    headers={"X-API-Key": "tk_..."},
)
result = response.json()
print(result["typescript"])
# interface User {
#   userId: number;
#   username: string;
#   email: string;
#   isActive: boolean;
# }
print(f"Generated {result['interface_count']} interface(s)")

Nested object with sub-interfaces

Nested objects are automatically extracted into their own named interfaces using PascalCase.

import httpx

data = {
    "orderId": "ORD-9921",
    "customer": {
        "name": "Alice Green",
        "address": {
            "street": "123 Main St",
            "city": "Springfield",
            "zipCode": "12345",
        },
    },
    "total": 149.99,
    "isPaid": False,
}

response = httpx.post(
    "https://dev.toolkitapi.io/v1/convert/json-to-typescript",
    json={"data": data, "root_name": "Order"},
    headers={"X-API-Key": "tk_..."},
)
print(response.json()["typescript"])
# interface Address {
#   street: string;
#   city: string;
#   zipCode: string;
# }
#
# interface Customer {
#   name: string;
#   address: Address;
# }
#
# interface Order {
#   orderId: string;
#   customer: Customer;
#   total: number;
#   isPaid: boolean;
# }

Array of typed objects

Arrays of objects are typed as T[] with a generated child interface.

import httpx

data = {
    "page": 1,
    "items": [
        {"id": 1, "title": "Widget", "price": 9.99},
        {"id": 2, "title": "Gadget", "price": 14.99},
    ],
}

response = httpx.post(
    "https://dev.toolkitapi.io/v1/convert/json-to-typescript",
    json={"data": data, "root_name": "ProductList"},
    headers={"X-API-Key": "tk_..."},
)
print(response.json()["typescript"])
# interface ItemsItem {
#   id: number;
#   title: string;
#   price: number;
# }
#
# interface ProductList {
#   page: number;
#   items: ItemsItem[];
# }

Write interfaces to a file

import httpx
from pathlib import Path

data = {
    "token": "abc123",
    "expiresAt": "2025-12-31T00:00:00Z",
    "user": {"id": 42, "role": "admin"},
}

response = httpx.post(
    "https://dev.toolkitapi.io/v1/convert/json-to-typescript",
    json={"data": data, "root_name": "AuthResponse"},
    headers={"X-API-Key": "tk_..."},
)

result = response.json()
Path("auth-types.ts").write_text(result["typescript"])
print(f"Wrote {result['interface_count']} interface(s) to auth-types.ts")

Request Parameters

Parameter Type Description
data object JSON object to convert
root_name string Name for the root interface (default Root, max 100 characters)

Response Fields

Field Type Description
typescript string Complete TypeScript interface declarations as a string
interface_count integer Number of interfaces generated

Tip

Interface names are derived using PascalCase. Nested objects become their own named interfaces and are referenced by name — the deeper the nesting, the more interfaces are generated. Use root_name to set a meaningful entry-point type name.


Type Mapping Reference

The generator walks the JSON value tree and emits one export interface per object it encounters. The mapping below is the exact behaviour of apis/convert/app/routers/code_convert.py — verified by round-tripping each shape through the live handler logic.

JSON value Emitted TypeScript Notes
null null Not any or optional. A null sample value becomes the literal type null.
true / false boolean
integer or float number No distinction between int and float.
string string
nested object PascalName Emits a new interface named after the key, not the value.
array of objects PascalNameItem[] Interface name is _to_pascal(key) + "Item".
array of scalars type[] Uses the first element only — [1, "a"] becomes number[].
empty array unknown[] No element to infer from.
array of arrays type[][] Nesting depth is preserved.

Key → interface name conversion

_to_pascal splits the key on _ and -, capitalises each fragment, and joins them. So:

Key Interface name
user_profile UserProfile
order-items OrderItems
userName UserName

Known Constraints and Rough Edges

These are real limitations of the current implementation. Read them before you rely on the output in a build step.

1. data must be a JSON object

data is typed as dict, so a root-level array or scalar is rejected with 422. To convert a top-level list, wrap it:

curl -X POST "https://convert.toolkitapi.io/v1/convert/json-to-typescript" \
  -H "X-API-Key: YOUR_KEY" -H "Content-Type: application/json" \
  -d '{"data": {"items": [{"id": 1}, {"id": 2}]}}'

2. Root-name collisions produce self-referencing interfaces

If root_name matches a key in data (case-insensitively, after Pascal conversion), the nested interface is suppressed by the dedup check and the field points back at the root. This output is invalid TypeScript:

{"data": {"response": {"ok": true}}, "root_name": "Response"}
export interface Response {
  response: Response;   // ⚠️ circular — has no `ok` property
}

Avoid this by choosing a root_name that does not appear as a key — e.g. prefix it (ApiResponse, RootPayload).

3. Keys are emitted unquoted

Property names are written verbatim with no quoting or escaping. Keys that are not valid TypeScript identifiers therefore produce a syntax error:

{"data": {"200": {"status": "ok"}, "user-profile": 1}}
export interface Root {
  200: 200;             // ⚠️ invalid — numeric literal
  user-profile: number; // ⚠️ invalid — unquoted hyphen
}

Keys that are valid identifiers but TypeScript reserved words (class, function, new) work fine as interface properties, so only non-identifier syntax is a problem.

4. Number-like keys collide

Because the type reference for an object value is derived from the key, a key of 200 produces export interface 200 { ... } — an illegal interface name. Numeric HTTP-status-shaped maps are the common trigger; rename them (status_200) or convert them one at a time.

5. interface_count counts emitted interfaces

interface_count is the length of the emitted interface list, including the root. Nested objects that would dedupe to an existing name are not counted twice.

Response Fields

Field Type Description
typescript string The generated .ts source, interfaces separated by blank lines.
interface_count number Number of interfaces emitted.

Safe Usage Pattern

Since the output is verbatim type text, treat it as a starting point rather than a build artifact:

import re
import httpx

resp = httpx.post(
    "https://convert.toolkitapi.io/v1/convert/json-to-typescript",
    headers={"X-API-Key": "YOUR_KEY"},
    json={"data": sample_payload, "root_name": "RootPayload"},
    timeout=30,
)
ts = resp.json()["typescript"]

# Sanity-check for the circular-interface footgun before writing to disk.
for m in re.finditer(r"export interface (\w+) \{\s*\1\b", ts):
    raise SystemExit(f"circular interface detected: {m.group(1)}")

Pick a root_name that cannot collide (RootPayload, ApiResponse), and validate the generated file with tsc --noEmit in CI.