pydantic2-to-typescript


Namepydantic2-to-typescript JSON
Version 0.0.1 PyPI version JSON
download
home_pagehttps://github.com/mukul-mehta/pydantic2-to-typescript
SummaryConvert pydantic v2 models to typescript interfaces
upload_time2024-05-06 10:02:53
maintainerNone
docs_urlNone
authorMukul Mehta
requires_pythonNone
licenseMIT
keywords pydantic typescript annotations validation interface
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pydantic2-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/phillipdupuis/pydantic-to-typescript/actions/workflows/cicd.yml/badge.svg)](https://github.com/phillipdupuis/pydantic-to-typescript/actions/workflows/cicd.yml)
[![Coverage Status](https://coveralls.io/repos/github/phillipdupuis/pydantic-to-typescript/badge.svg?branch=master)](https://coveralls.io/github/phillipdupuis/pydantic-to-typescript?branch=master)

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

```bash
$ 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):

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

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mukul-mehta/pydantic2-to-typescript",
    "name": "pydantic2-to-typescript",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "pydantic typescript annotations validation interface",
    "author": "Mukul Mehta",
    "author_email": "work@mukul-mehta.in",
    "download_url": "https://files.pythonhosted.org/packages/bf/5b/08ac6a2774c47cecd4e0d9ada8496a84e0f324cb038b580d4d94ec32f279/pydantic2_to_typescript-0.0.1.tar.gz",
    "platform": null,
    "description": "# pydantic2-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/phillipdupuis/pydantic-to-typescript/actions/workflows/cicd.yml/badge.svg)](https://github.com/phillipdupuis/pydantic-to-typescript/actions/workflows/cicd.yml)\n[![Coverage Status](https://coveralls.io/repos/github/phillipdupuis/pydantic-to-typescript/badge.svg?branch=master)](https://coveralls.io/github/phillipdupuis/pydantic-to-typescript?branch=master)\n\nA fork of the tool to work with Pydantic V2\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```bash\n$ pip install pydantic2-to-typescript\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",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Convert pydantic v2 models to typescript interfaces",
    "version": "0.0.1",
    "project_urls": {
        "Homepage": "https://github.com/mukul-mehta/pydantic2-to-typescript"
    },
    "split_keywords": [
        "pydantic",
        "typescript",
        "annotations",
        "validation",
        "interface"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e61b8523589da24c2a23f36f098e6c3341160aab1534f354eb156af596d0e9ae",
                "md5": "f36b3fd1fd4209fa4c5ca876e025b3d0",
                "sha256": "ce0fef880ea66db9acbada318f0372d4c70e15ad13258463648d97c86683f292"
            },
            "downloads": -1,
            "filename": "pydantic2_to_typescript-0.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f36b3fd1fd4209fa4c5ca876e025b3d0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 8102,
            "upload_time": "2024-05-06T10:02:51",
            "upload_time_iso_8601": "2024-05-06T10:02:51.657886Z",
            "url": "https://files.pythonhosted.org/packages/e6/1b/8523589da24c2a23f36f098e6c3341160aab1534f354eb156af596d0e9ae/pydantic2_to_typescript-0.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bf5b08ac6a2774c47cecd4e0d9ada8496a84e0f324cb038b580d4d94ec32f279",
                "md5": "8c7e721e06d054ea44af3d1a0f0d5ae9",
                "sha256": "f9846adcd25db00deccd51fd5a11573a37479012ca4e056dc0502cb03a2e40c6"
            },
            "downloads": -1,
            "filename": "pydantic2_to_typescript-0.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "8c7e721e06d054ea44af3d1a0f0d5ae9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8783,
            "upload_time": "2024-05-06T10:02:53",
            "upload_time_iso_8601": "2024-05-06T10:02:53.543551Z",
            "url": "https://files.pythonhosted.org/packages/bf/5b/08ac6a2774c47cecd4e0d9ada8496a84e0f324cb038b580d4d94ec32f279/pydantic2_to_typescript-0.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-06 10:02:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mukul-mehta",
    "github_project": "pydantic2-to-typescript",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pydantic2-to-typescript"
}
        
Elapsed time: 4.59912s