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' |
‑‑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.6.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | eedc8ee88fa87509aeb39414b1386ace7181c58c1d6f6bbe4cf5f6cb6206333e |
|
MD5 | 94cb11744fb91ab27864666b69ffdfb9 |
|
BLAKE2b-256 | 7bb670c7601518519611e27e96b1ae6533fff180dc9fce252ee33b8f4d988efe |
Hashes for pydantic_to_typescript-1.0.6-py3.8.egg
Algorithm | Hash digest | |
---|---|---|
SHA256 | b111a15a1e42a3d69dd458cad5cf47102615d4078299907c024eba5d0b412698 |
|
MD5 | 3a4730481ff205878a7626b4a3e53e78 |
|
BLAKE2b-256 | 73a2e5f19cf6c3be713613551cc3d6368f74f14125f4c5c6b9f97a898dfda9bd |
Hashes for pydantic_to_typescript-1.0.6-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3d6288982d380a969a390527ed215fc44af5401fe777acb97704f81cb0652d28 |
|
MD5 | 5d68f1528371859ce06d428df2615c14 |
|
BLAKE2b-256 | 54476977d147c4dc55d3c95cdd11c2d2fd5f87b51bd260c76c907b7d8c9dc3bb |