pydantic-to-typescript

repository·master·Indexed 19 days ago

https://github.com/phillipdupuis/pydantic-to-typescript

A CLI tool and Python API that converts Pydantic models (V1 and V2) into TypeScript interfaces. It utilizes the json-schema-to-typescript (json2ts) utility to generate type definitions, allowing for a single source of truth between Python and JavaScript applications.

Tokens
1.6K
Snippets
8
Records
8
Agent score
16%

What's inside pydantic-to-typescript

  1. Use generated TypeScript interfaces

    master

    Once the conversion is complete, the resulting TypeScript file contains exported interfaces that match your Pydantic models. You can import these directly into your TypeScript/JavaScript application to ensure type safety when interacting with your Python backend.

    import { LoginCredentials, LoginResponseData } from "./apiTypes.ts";
    
    async function login(
      credentials: LoginCredentials,
      resolve: (data: LoginResponseData) => void,
      reject: (error: string) => void
    ) {
      try {
        const response: Response = await fetch("/login/", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(credentials),
        });
        const data: LoginResponseData = await response.json();
        resolve(data);
      } catch (error) {
        reject(error.message);
      }
    }
  2. Convert Pydantic models via CLI

    master

    You can convert models using either the Python module dot-notation or a direct file path to the .py file.

    # Using module notation
    $ pydantic2ts --module backend.api --output ./frontend/apiTypes.ts
    
    # Using file path
    $ pydantic2ts --module ./backend/api.py --output ./frontend/apiTypes.ts
  3. CLI Reference for pydantic2ts

    master

    The pydantic2ts command-line interface allows you to convert Pydantic models from a Python module into TypeScript interfaces. Use the following flags to configure the conversion:

    | Prop | Description |
    | :--- | :--- |
    | `--module` | name or filepath of the python module you would like to convert. All the pydantic models within it will be converted to typescript interfaces. Discoverable submodules will also be checked. |
    | `--output` | name of the file the typescript definitions should be written to. Ex: `./frontend/apiTypes.ts` |
    | `--exclude` | name of a pydantic model which should be omitted from the resulting typescript definitions. This option can be defined multiple times, ex: `--exclude Foo --exclude Bar` to exclude both the Foo and Bar models from the output. |
    | `--json2ts-cmd` | optional, the command used to invoke json2ts. The default is 'json2ts'. Specify this if you have it installed locally (ex: 'yarn json2ts') or if the exact path to the executable is required (ex: /myproject/node_modules/bin/json2ts) |
  4. Reference: pydantic2ts CLI arguments

    master

    The following flags are available for the pydantic2ts command:

    FlagRequiredDescription
    --moduleYesThe name (dotted path) or valid filepath of the Python module containing your Pydantic models. Submodules will be searched recursively.
    --outputYesThe filename where the generated TypeScript definitions will be written.
    --excludeNoThe name of a Pydantic model to omit from the output. This flag can be used multiple times to exclude multiple models.
    --json2ts-cmdNoThe command used to execute json2ts. Use this if the executable is not in your PATH or is installed locally (e.g., yarn json2ts). Defaults to json2ts.
    pydantic2ts --module my_project.schemas --output ./types/models.ts --exclude ModelA --exclude ModelB --json2ts-cmd "yarn json2ts"
  5. Use the pydantic2ts CLI to convert models to TypeScript

    master

    The pydantic2ts command-line tool converts Pydantic models (both V1 and V2) from a specified Python module into TypeScript interfaces. It works by generating a JSON schema from your models and then using the json-schema-to-typescript (json2ts) utility to produce the final TypeScript definitions.

    Prerequisites You must have the json-schema-to-typescript package installed and available in your path (e.g., via npm install -g json-schema-to-typescript).

    pydantic2ts --module my_project.schemas --output ./types/models.ts