Automatically generate Pydantic models from API responses
Project description
API-to-Pydantic
🚀 Automatically generate Pydantic models from API responses, JSON files, or curl commands.
Features
✨ Smart Type Inference - Automatically detects correct Python types from sample data
🔍 Pattern Recognition - Identifies emails, URLs, UUIDs, datetimes, and more
📦 Nested Structures - Handles complex nested objects and arrays
✅ Validators - Generates Field validators based on data patterns
🎯 Optional Detection - Identifies optional fields from null values
🔄 Enum Recognition - Detects limited value sets and creates enums
📝 Documentation - Adds helpful docstrings to generated models
Installation
pip install api2pydantic
Or install from source:
git clone https://github.com/codedev1992/api2pydantic.git
cd api2pydantic
pip install -e .
Quick Start
From a URL
api2pydantic https://api.example.com/users
using Piple
curl https://api.example.com/users | api2pydantic
From curl command
api2pydantic curl https://api.example.com/users -H "Authorization: Bearer token"
From JSON file
api2pydantic file data.json
From stdin
echo '{"name": "John", "age": 30}' | api2pydantic
Save to file
api2pydantic https://api.example.com/users --output models.py
Custom model name
api2pydantic https://api.example.com/users --model-name UserResponse
Examples
Input JSON:
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"email": "user@example.com",
"name": "John Doe",
"age": 30,
"is_active": true,
"created_at": "2024-01-15T10:30:00Z",
"tags": ["python", "pydantic"],
"profile": {
"bio": "Software Developer",
"website": "https://example.com"
}
}
Generated Pydantic Model:
from pydantic import BaseModel, Field, EmailStr, HttpUrl
from typing import Optional, List
from datetime import datetime
from uuid import UUID
class Profile(BaseModel):
"""Profile model"""
bio: str = Field(..., description="Software Developer")
website: HttpUrl = Field(..., description="https://example.com")
class RootModel(BaseModel):
"""RootModel model"""
id: UUID = Field(..., description="123e4567-e89b-12d3-a456-426614174000")
email: EmailStr = Field(..., description="user@example.com")
name: str = Field(..., min_length=1, description="John Doe")
age: int = Field(..., ge=0, description="30")
is_active: bool = Field(..., description="True")
created_at: datetime = Field(..., description="2024-01-15T10:30:00Z")
tags: List[str] = Field(..., description="['python', 'pydantic']")
profile: Profile = Field(..., description="Profile model")
Advanced Usage
Multiple samples for better inference
# Analyze multiple API responses to improve type detection
api2pydantic https://api.example.com/users/1 \
https://api.example.com/users/2 \
https://api.example.com/users/3
Options
api2pydantic --help
Options:
--output, -o Output file path
--model-name, -m Custom model name (default: RootModel)
--array-item-name Name for array item models
--no-validators Skip generating validators
--no-descriptions Skip adding descriptions
--force-optional Make all fields optional
How It Works
- Fetch - Retrieves JSON data from URL, file, or curl command
- Analyze - Examines values to infer types and detect patterns
- Generate - Creates Pydantic model with proper type hints
- Validate - Adds field validators based on data constraints
- Format - Outputs clean, formatted Python code
Type Detection
The tool intelligently detects:
- Primitives: str, int, float, bool, None
- Collections: List, Dict, Set
- Special Types: UUID, datetime, date, time
- Validated Types: EmailStr, HttpUrl
- Patterns: Enum detection from limited value sets
- Optionals: Fields with null values
- Unions: Mixed types in arrays
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/your_feature_name) - Commit your changes (
git commit -m 'Add some your_feature_name') - Push to the branch (
git push origin feature/your_feature_name) - Open a Pull Request
Development Setup
# Clone the repo
git clone https://github.com/codedev1992/api2pydantic.git
cd api2pydantic
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install in development mode
pip install -e ".[dev]"
# Run tests
pytest
# Run linter
flake8 api2pydantic tests
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Inspired by the amazing Pydantic library
- Built to solve the tedious task of manually writing models
Roadmap
- Support for JSON Schema output
- GraphQL schema support
- OpenAPI spec generation
- VS Code extension
- Web UI for online conversion
- Support for more validation patterns
Support
⭐ Star this repo if you find it helpful!
🐛 Report bugs
💡 Request features
Made with ❤️
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
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file api2pydantic-0.1.0.tar.gz.
File metadata
- Download URL: api2pydantic-0.1.0.tar.gz
- Upload date:
- Size: 20.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
083fdf03e95920f3c2eab034b31a1a68aa6a6d4cef064a4724e423b68fe833d4
|
|
| MD5 |
67fceb1a8f357a57f3a81bbaa7ed6c32
|
|
| BLAKE2b-256 |
aa2fecd6129f09d8d416850e3b359a0590c0a71c27e82b88d3114dd739aa12c9
|
File details
Details for the file api2pydantic-0.1.0-py3-none-any.whl.
File metadata
- Download URL: api2pydantic-0.1.0-py3-none-any.whl
- Upload date:
- Size: 15.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d8ab5e572a542cd3a2570cebb92b76be83daf8b1321b14f41659be4e9093a3aa
|
|
| MD5 |
ac4d34ee22fb05aec581c25ccc1e7171
|
|
| BLAKE2b-256 |
e1e994352b7f460c2f130ca09d16cc20cd3a8f4f169acf1ec6d7a4ae2694b9dd
|