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 in a strange location and need to provide the exact path (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 Distributions
Hashes for pydantic-to-typescript-1.0.7.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | dccf668e97626e616d20f2b1b99a568b5ac16344f3b2c850ebc463118b21a3d7 |
|
MD5 | 910015e8bd17a8c6d16f99af816176ac |
|
BLAKE2b-256 | 323b8a3bb30b3a608501e6dcd580989aa53204445138bb4f04edae2aefe40094 |
Hashes for pydantic_to_typescript-1.0.7-py3.8.egg
Algorithm | Hash digest | |
---|---|---|
SHA256 | b4917453d74df1b401259b881117ae164bf1bac2cac849a88466badb43825e6d |
|
MD5 | 11344e88c08a7b59e52fa4ff2fd54878 |
|
BLAKE2b-256 | 750234de4c0a2dea18d96a1e9b6a06146f027e237c995b7211753f26a6d9b47d |
Hashes for pydantic_to_typescript-1.0.7-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b3d093cbd15fd938faa09d1128621f27a9a93bef275eea5eb0912987d5d9d843 |
|
MD5 | 48e1a465d10133577cfa2eb79a14968c |
|
BLAKE2b-256 | ff3d44c29e1a8a12620a83c5a50bed1d34db3208a40da833a6dd8ae6b97b7996 |