Skip to main content

Convert pydantic v2 models to typescript interfaces

Project description

pydantic2-to-typescript

PyPI version CI/CD Coverage Status

A fork of the tool to work with Pydantic V2

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 pydantic2-to-typescript

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic2_to_typescript-0.0.1.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic2_to_typescript-0.0.1-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file pydantic2_to_typescript-0.0.1.tar.gz.

File metadata

  • Download URL: pydantic2_to_typescript-0.0.1.tar.gz
  • Upload date:
  • Size: 8.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.10.8

File hashes

Hashes for pydantic2_to_typescript-0.0.1.tar.gz
Algorithm Hash digest
SHA256 f9846adcd25db00deccd51fd5a11573a37479012ca4e056dc0502cb03a2e40c6
MD5 8c7e721e06d054ea44af3d1a0f0d5ae9
BLAKE2b-256 bf5b08ac6a2774c47cecd4e0d9ada8496a84e0f324cb038b580d4d94ec32f279

See more details on using hashes here.

File details

Details for the file pydantic2_to_typescript-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic2_to_typescript-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ce0fef880ea66db9acbada318f0372d4c70e15ad13258463648d97c86683f292
MD5 f36b3fd1fd4209fa4c5ca876e025b3d0
BLAKE2b-256 e61b8523589da24c2a23f36f098e6c3341160aab1534f354eb156af596d0e9ae

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page