Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

CLI Tool for converting pydantic models into typescript definitions

License

NotificationsYou must be signed in to change notification settings

phillipdupuis/pydantic-to-typescript

Use this GitHub action with your project
Add this Action to an existing workflow or create a new one
View on Marketplace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

67 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PyPI versionCI/CDCoverage Status

A simple CLI tool for converting pydantic models into typescript interfaces.It supports all versions of pydantic, with polyfills for older versions to ensure that the resulting typescript definitions are stable and accurate.

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

Pydantic V2 support

If you are encountering issues withpydantic>2, it is most likely because you're using an old version ofpydantic-to-typescript.Runpip install 'pydantic-to-typescript>2' and/or addpydantic-to-typescript>=2 to your project requirements.

CI/CD

You can now usepydantic-to-typescript to automatically validate and/or update typescript definitions as part of your CI/CD pipeline.

The github action can be found here:https://github.com/marketplace/actions/pydantic-to-typescript.The available inputs are documented here:https://github.com/phillipdupuis/pydantic-to-typescript/blob/master/action.yml.

CLI

PropDescription
‑‑modulename 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.
‑‑outputname of the file the typescript definitions should be written to. Ex: './frontend/apiTypes.ts'
‑‑excludename 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‑cmdoptional, 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):

fromfastapiimportFastAPIfrompydanticimportBaseModelfromtypingimportList,Optionalapi=FastAPI()classLoginCredentials(BaseModel):username:strpassword:strclassProfile(BaseModel):username:strage:Optional[int]hobbies:List[str]classLoginResponseData(BaseModel):token:strprofile:Profile@api.post('/login/',response_model=LoginResponseData)deflogin(body:LoginCredentials):profile=Profile(**body.dict(),age=72,hobbies=['cats'])returnLoginResponseData(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:

frompydantic2tsimportgenerate_typescript_defsgenerate_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*/exportinterfaceLoginCredentials{username:string;password:string;}exportinterfaceLoginResponseData{token:string;profile:Profile;}exportinterfaceProfile{username:string;age?:number;hobbies:string[];}

...and can be used in your typescript code with complete confidence.

import{LoginCredentials,LoginResponseData}from"./apiTypes.ts";asyncfunctionlogin(credentials:LoginCredentials,resolve:(data:LoginResponseData)=>void,reject:(error:string)=>void){try{constresponse:Response=awaitfetch("/login/",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(credentials),});constdata:LoginResponseData=awaitresponse.json();resolve(data);}catch(error){reject(error.message);}}

About

CLI Tool for converting pydantic models into typescript definitions

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors5


[8]ページ先頭

©2009-2025 Movatter.jp