pydantic-to-typescript2


Namepydantic-to-typescript2 JSON
Version 1.0.4 PyPI version JSON
download
home_pagehttps://github.com/dariuslabs/pydantic-to-typescript2
SummaryConvert pydantic v1 and pydantic v2 models to typescript interfaces
upload_time2024-06-17 23:31:24
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/ca/12/f47b66df46f7617a6a7c54990030ff9d370c25bd1bf94ae9a06c7a5e3ebb/pydantic-to-typescript2-1.0.4.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.4",
    "project_urls": {
        "Homepage": "https://github.com/dariuslabs/pydantic-to-typescript2"
    },
    "split_keywords": [
        "pydantic",
        "pydantic2",
        "typescript",
        "annotations",
        "validation",
        "interface"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0dc8d6779d49876e1459f4d31814be207ef7c35dc3aeba985d2b5464164ed60d",
                "md5": "cad3b2412240692718db6dae137b9a69",
                "sha256": "597f1848e918d0b95879c9a371ff664c8f300894d43aafb0b7f693f6c84f3657"
            },
            "downloads": -1,
            "filename": "pydantic_to_typescript2-1.0.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "cad3b2412240692718db6dae137b9a69",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 8652,
            "upload_time": "2024-06-17T23:31:20",
            "upload_time_iso_8601": "2024-06-17T23:31:20.450296Z",
            "url": "https://files.pythonhosted.org/packages/0d/c8/d6779d49876e1459f4d31814be207ef7c35dc3aeba985d2b5464164ed60d/pydantic_to_typescript2-1.0.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ca12f47b66df46f7617a6a7c54990030ff9d370c25bd1bf94ae9a06c7a5e3ebb",
                "md5": "612871740c4f6fdfac63768ca4683ff1",
                "sha256": "1bd25dea0e1ce4220c495ad408d028ddd905376cbed1a856b2caa6f31c344371"
            },
            "downloads": -1,
            "filename": "pydantic-to-typescript2-1.0.4.tar.gz",
            "has_sig": false,
            "md5_digest": "612871740c4f6fdfac63768ca4683ff1",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8031,
            "upload_time": "2024-06-17T23:31:24",
            "upload_time_iso_8601": "2024-06-17T23:31:24.224695Z",
            "url": "https://files.pythonhosted.org/packages/ca/12/f47b66df46f7617a6a7c54990030ff9d370c25bd1bf94ae9a06c7a5e3ebb/pydantic-to-typescript2-1.0.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-17 23:31:24",
    "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.38064s