Skip to main content

pydantic-to-typescript

PyPI version CI/CD Coverage Status

A simple CLI tool for converting pydantic models into typescript interfaces. Useful for any scenario in which python and javascript applications are interacting, since it allows you to have a single source of truth for type definitions.

This tool requires that you have the lovely json2ts CLI utility installed. Instructions can be found here: https://www.npmjs.com/package/json-schema-to-typescript

Installation

pip install pydantic-to-typescript2

CLI

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)

Usage

Define your pydantic models (ex: /backend/api.py):

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional

api = FastAPI()

class LoginCredentials(BaseModel):
    username: str
    password: str

class Profile(BaseModel):
    username: str
    age: Optional[int]
    hobbies: List[str]

class LoginResponseData(BaseModel):
    token: str
    profile: Profile

@api.post('/login/', response_model=LoginResponseData)
def login(body: LoginCredentials):
    profile = Profile(**body.dict(), age=72, hobbies=['cats'])
    return LoginResponseData(token='very-secure', profile=profile)

Execute the command for converting these models into typescript definitions, via:

$ pydantic2ts --module backend.api --output ./frontend/apiTypes.ts

or:

$ pydantic2ts --module ./backend/api.py --output ./frontend/apiTypes.ts

or:

from pydantic2ts import generate_typescript_defs

generate_typescript_defs("backend.api", "./frontend/apiTypes.ts")

The models are now defined in typescript...

/* tslint:disable */
/**
/* This file was automatically generated from pydantic models by running pydantic2ts.
/* Do not modify it by hand - just update the pydantic models and then re-run the script
*/

export interface LoginCredentials {
  username: string;
  password: string;
}
export interface LoginResponseData {
  token: string;
  profile: Profile;
}
export interface Profile {
  username: string;
  age?: number;
  hobbies: string[];
}

...and can be used in your typescript code with complete confidence.

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);
  }
}

Testing

# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

# Load nvm into the current shell session
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm

# Install Node.js version 18
nvm install 18

# Use Node.js version 18
nvm use 18

# Verify Node.js installation
node -v
npm -v

# Install Python dependencies
pip install -U pip wheel pytest pytest-cov coverage
pip install -U .

# Install json-schema-to-typescript
npm install -g json-schema-to-typescript

Release files for pydantic-to-typescript2 1.0.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pydantic-to-typescript2 1.0.6
File Size Uploaded
pydantic-to-typescript2-1.0.6.tar.gz 8.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pydantic-to-typescript2 1.0.6
File Interpreter ABI Platform
pydantic_to_typescript2-1.0.6-py3-none-any.whl Python 3 none any Details

Total release size: 16.6 kB

Release files / pydantic-to-typescript2-1.0.6.tar.gz

Download URL pydantic-to-typescript2-1.0.6.tar.gz
Size 8.0 kB
Tags Source
SHA-256 checksum
How to use checksums
19cc0fb03802abcb508b02fbc334f1667ff50e0853a782b58df9dd0409290163
BLAKE2b-256 checksum
How to use checksums
25b17f4d86847084ad345ffb2bfe75365536b7640678c9cd5ae6ad64599a14ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.9.20

Release files / pydantic_to_typescript2-1.0.6-py3-none-any.whl

Download URL pydantic_to_typescript2-1.0.6-py3-none-any.whl
Size 8.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
89bbdd4b84b72d9f8ada33fd4d7d6605457be302dd6d4c6d48faa9310841bb69
BLAKE2b-256 checksum
How to use checksums
6274cf2aee6837b357f7edef46584c1754d49cb29be00b3bfea97580168dea2b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.9.20

Release history Release notifications | RSS feed

This release

1.0.6 This release

2 release files

1.0.4

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page