Convert pydantic models to typescript interfaces
Project description
pydantic-to-typescript
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-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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file pydantic_to_typescript-2.0.0.tar.gz
.
File metadata
- Download URL: pydantic_to_typescript-2.0.0.tar.gz
- Upload date:
- Size: 35.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 06e92e8d10759ffebe3abdd4de14015bbf80809fa9960273be6041d8509662be |
|
MD5 | e97a0d4107fcf81d9279e997ed2fa367 |
|
BLAKE2b-256 | 59ac8dc13be6720267b5edffb3b0d8c1abdcccc5743d7bda4257ab0a5dccc7b9 |
Provenance
The following attestation bundles were made for pydantic_to_typescript-2.0.0.tar.gz
:
Publisher:
cicd.yml
on phillipdupuis/pydantic-to-typescript
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pydantic_to_typescript-2.0.0.tar.gz
- Subject digest:
06e92e8d10759ffebe3abdd4de14015bbf80809fa9960273be6041d8509662be
- Sigstore transparency entry: 150691539
- Sigstore integration time:
- Predicate type:
File details
Details for the file pydantic_to_typescript-2.0.0-py3-none-any.whl
.
File metadata
- Download URL: pydantic_to_typescript-2.0.0-py3-none-any.whl
- Upload date:
- Size: 9.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5bc5e1a940c1a39e4e3a6124bd3bda1b0fc6df85c673a4781b94a1f4150cae15 |
|
MD5 | a6eff61a33bd20326f513477b816bf59 |
|
BLAKE2b-256 | c39cf51312f3063a8b6e1e09e6527a81d3b1828ad5fc8a65c14376f85cf65502 |
Provenance
The following attestation bundles were made for pydantic_to_typescript-2.0.0-py3-none-any.whl
:
Publisher:
cicd.yml
on phillipdupuis/pydantic-to-typescript
-
Statement type:
https://in-toto.io/Statement/v1
- Predicate type:
https://docs.pypi.org/attestations/publish/v1
- Subject name:
pydantic_to_typescript-2.0.0-py3-none-any.whl
- Subject digest:
5bc5e1a940c1a39e4e3a6124bd3bda1b0fc6df85c673a4781b94a1f4150cae15
- Sigstore transparency entry: 150691541
- Sigstore integration time:
- Predicate type: