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 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. Ex: 'pydantic2ts.examples.pydantic_models' |
‑‑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:
$ pydantic2ts --module backend.api --output ./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
Hashes for pydantic-to-typescript-1.0.5.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 79fa51b73e28db6ec39e9b3dfcc9ca8426e3f46c001109a6928b6ee60dd6ada2 |
|
MD5 | 204ae7d4c25ecddd35d9711bd76b5004 |
|
BLAKE2b-256 | a0281df4eafe004c1709d4e160f976f9d6d223408a3e53dd8ac0b43265ab4704 |
Hashes for pydantic_to_typescript-1.0.5-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0590bc0221e3aae1f6d55c5f1c353e086f9d2eea6537d28d7f8777458df4c244 |
|
MD5 | caa1273da5ae9319982fb4b508e2a117 |
|
BLAKE2b-256 | 98ed1f04113d89e186d16f58949723f1e20cbda6fcccee9f6bf81641851032e5 |