pydantic-to-typescript2


Namepydantic-to-typescript2 JSON
Version 1.0.6 PyPI version JSON
download
home_pagehttps://github.com/dariuslabs/pydantic-to-typescript2
SummaryConvert pydantic v1 and pydantic v2 models to typescript interfaces
upload_time2024-09-12 04:20:27
maintainerNone
docs_urlNone
authorPhillip Dupuis, Darius Labs
requires_pythonNone
licenseMIT
keywords pydantic pydantic2 typescript annotations validation interface
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pydantic-to-typescript

[![PyPI version](https://badge.fury.io/py/pydantic-to-typescript.svg)](https://badge.fury.io/py/pydantic-to-typescript)
[![CI/CD](https://github.com/dariuslabs/pydantic-to-typescript2/actions/workflows/cicd.yml/badge.svg)](https://github.com/dariuslabs/pydantic-to-typescript2/actions/workflows/cicd.yml)
[![Coverage Status](https://coveralls.io/repos/github/dariuslabs/pydantic-to-typescript2/badge.svg?branch=master)](https://coveralls.io/github/dariuslabs/pydantic-to-typescript2?branch=master)

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

```shell
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):

```python
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:

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

or:

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

or:

```python
from pydantic2ts import generate_typescript_defs

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

The models are now defined in typescript...

```ts
/* 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.

```ts
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
```shell
# 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
```


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/dariuslabs/pydantic-to-typescript2",
    "name": "pydantic-to-typescript2",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "pydantic pydantic2 typescript annotations validation interface",
    "author": "Phillip Dupuis, Darius Labs",
    "author_email": "sean@dariuslabs.com",
    "download_url": "https://files.pythonhosted.org/packages/25/b1/7f4d86847084ad345ffb2bfe75365536b7640678c9cd5ae6ad64599a14ff/pydantic-to-typescript2-1.0.6.tar.gz",
    "platform": null,
    "description": "# pydantic-to-typescript\n\n[![PyPI version](https://badge.fury.io/py/pydantic-to-typescript.svg)](https://badge.fury.io/py/pydantic-to-typescript)\n[![CI/CD](https://github.com/dariuslabs/pydantic-to-typescript2/actions/workflows/cicd.yml/badge.svg)](https://github.com/dariuslabs/pydantic-to-typescript2/actions/workflows/cicd.yml)\n[![Coverage Status](https://coveralls.io/repos/github/dariuslabs/pydantic-to-typescript2/badge.svg?branch=master)](https://coveralls.io/github/dariuslabs/pydantic-to-typescript2?branch=master)\n\nA 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.\n\nThis 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\n\n### Installation\n\n```shell\npip install pydantic-to-typescript2\n```\n\n---\n\n### CLI\n\n| Prop                            | Description                                                                                                                                                                                                                             |\n| :------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| ‑‑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.                                            |\n| ‑‑output            | name of the file the typescript definitions should be written to. Ex: './frontend/apiTypes.ts'                                                                                                                                          |\n| ‑‑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.        |\n| ‑‑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) |\n\n---\n\n### Usage\n\nDefine your pydantic models (ex: /backend/api.py):\n\n```python\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom typing import List, Optional\n\napi = FastAPI()\n\nclass LoginCredentials(BaseModel):\n    username: str\n    password: str\n\nclass Profile(BaseModel):\n    username: str\n    age: Optional[int]\n    hobbies: List[str]\n\nclass LoginResponseData(BaseModel):\n    token: str\n    profile: Profile\n\n@api.post('/login/', response_model=LoginResponseData)\ndef login(body: LoginCredentials):\n    profile = Profile(**body.dict(), age=72, hobbies=['cats'])\n    return LoginResponseData(token='very-secure', profile=profile)\n```\n\nExecute the command for converting these models into typescript definitions, via:\n\n```bash\n$ pydantic2ts --module backend.api --output ./frontend/apiTypes.ts\n```\n\nor:\n\n```bash\n$ pydantic2ts --module ./backend/api.py --output ./frontend/apiTypes.ts\n```\n\nor:\n\n```python\nfrom pydantic2ts import generate_typescript_defs\n\ngenerate_typescript_defs(\"backend.api\", \"./frontend/apiTypes.ts\")\n```\n\nThe models are now defined in typescript...\n\n```ts\n/* tslint:disable */\n/**\n/* This file was automatically generated from pydantic models by running pydantic2ts.\n/* Do not modify it by hand - just update the pydantic models and then re-run the script\n*/\n\nexport interface LoginCredentials {\n  username: string;\n  password: string;\n}\nexport interface LoginResponseData {\n  token: string;\n  profile: Profile;\n}\nexport interface Profile {\n  username: string;\n  age?: number;\n  hobbies: string[];\n}\n```\n\n...and can be used in your typescript code with complete confidence.\n\n```ts\nimport { LoginCredentials, LoginResponseData } from \"./apiTypes.ts\";\n\nasync function login(\n  credentials: LoginCredentials,\n  resolve: (data: LoginResponseData) => void,\n  reject: (error: string) => void\n) {\n  try {\n    const response: Response = await fetch(\"/login/\", {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(credentials),\n    });\n    const data: LoginResponseData = await response.json();\n    resolve(data);\n  } catch (error) {\n    reject(error.message);\n  }\n}\n```\n\n### Testing\n```shell\n# Install nvm\ncurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash\n\n# Load nvm into the current shell session\nexport NVM_DIR=\"$([ -z \"${XDG_CONFIG_HOME-}\" ] && printf %s \"${HOME}/.nvm\" || printf %s \"${XDG_CONFIG_HOME}/nvm\")\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\"  # This loads nvm\n\n# Install Node.js version 18\nnvm install 18\n\n# Use Node.js version 18\nnvm use 18\n\n# Verify Node.js installation\nnode -v\nnpm -v\n\n# Install Python dependencies\npip install -U pip wheel pytest pytest-cov coverage\npip install -U .\n\n# Install json-schema-to-typescript\nnpm install -g json-schema-to-typescript\n```\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Convert pydantic v1 and pydantic v2 models to typescript interfaces",
    "version": "1.0.6",
    "project_urls": {
        "Homepage": "https://github.com/dariuslabs/pydantic-to-typescript2"
    },
    "split_keywords": [
        "pydantic",
        "pydantic2",
        "typescript",
        "annotations",
        "validation",
        "interface"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6274cf2aee6837b357f7edef46584c1754d49cb29be00b3bfea97580168dea2b",
                "md5": "e309c56eb9011c92afb1d8c32d37ff6e",
                "sha256": "89bbdd4b84b72d9f8ada33fd4d7d6605457be302dd6d4c6d48faa9310841bb69"
            },
            "downloads": -1,
            "filename": "pydantic_to_typescript2-1.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e309c56eb9011c92afb1d8c32d37ff6e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 8624,
            "upload_time": "2024-09-12T04:20:25",
            "upload_time_iso_8601": "2024-09-12T04:20:25.889306Z",
            "url": "https://files.pythonhosted.org/packages/62/74/cf2aee6837b357f7edef46584c1754d49cb29be00b3bfea97580168dea2b/pydantic_to_typescript2-1.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "25b17f4d86847084ad345ffb2bfe75365536b7640678c9cd5ae6ad64599a14ff",
                "md5": "7d7ac28f38325fd2f9df47c1cf980b65",
                "sha256": "19cc0fb03802abcb508b02fbc334f1667ff50e0853a782b58df9dd0409290163"
            },
            "downloads": -1,
            "filename": "pydantic-to-typescript2-1.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "7d7ac28f38325fd2f9df47c1cf980b65",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8007,
            "upload_time": "2024-09-12T04:20:27",
            "upload_time_iso_8601": "2024-09-12T04:20:27.233433Z",
            "url": "https://files.pythonhosted.org/packages/25/b1/7f4d86847084ad345ffb2bfe75365536b7640678c9cd5ae6ad64599a14ff/pydantic-to-typescript2-1.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-12 04:20:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "dariuslabs",
    "github_project": "pydantic-to-typescript2",
    "github_not_found": true,
    "lcname": "pydantic-to-typescript2"
}
        
Elapsed time: 0.31425s