JSON to OpenAPI Generator
A Python CLI tool that analyzes JSON data files and automatically generates valid OpenAPI 3.0 specification files. It infers data types, detects nested structures, and produces specs ready for Swagger UI, ReDoc, and code generators.
Features
- Automatic Type Inference: Infers OpenAPI schema types (string, number, integer, boolean, null, array, object) from JSON data
- Nested Object Detection: Recursively detects nested objects and arrays to build complete schema trees
- Format Detection: Automatically detects date, datetime, email, URI, UUID, and byte formats
- Batch Processing: Process multiple JSON files in a single command with parallel processing support
- Interactive Customization: Interactive CLI prompts to customize endpoint names, paths, HTTP methods, and descriptions
- OpenAPI 3.0 Output: Generates valid OpenAPI 3.0 YAML/JSON output compatible with Swagger UI, ReDoc, and code generators
- Validation: Built-in validation of generated OpenAPI specs
Installation
From Source
pip install -e .
Using pip
pip install json-to-openapi
Development Installation
pip install -e ".[dev]"
Usage
Basic Conversion
Convert a single JSON file to OpenAPI specification:
json-to-openapi convert input.json -o output.yaml
With Custom Options
json-to-openapi convert input.json \
-o output.yaml \
-t "My API" \
-v "1.0.0" \
-d "API description" \
-f yaml
Interactive Mode
Interactive mode for customizing the OpenAPI specification:
json-to-openapi interactive
Batch Processing
Process multiple JSON files:
json-to-openapi batch "*.json" -o ./openapi_specs/
Generate a combined OpenAPI spec:
json-to-openapi batch "*.json" -c -o combined.yaml
Validation
Validate an existing OpenAPI specification:
json-to-openapi validate openapi.yaml
Options
Global Options
| Option | Description |
|---|---|
-v, --verbose |
Enable verbose output |
-q, --quiet |
Suppress all output except errors |
Convert Command
| Option | Description |
|---|---|
input_file |
Path to input JSON file |
-o, --output |
Output file path |
-f, --format |
Output format (yaml or json, default: yaml) |
-t, --title |
API title (default: "My API") |
-v, --version |
API version (default: "1.0.0") |
-d, --description |
API description |
Batch Command
| Option | Description |
|---|---|
input_pattern |
File glob pattern (e.g., ".json" or "data/**/.json") |
-o, --output-dir |
Output directory |
-f, --format |
Output format (yaml or json, default: yaml) |
-t, --title |
API title (default: "My API") |
-v, --version |
API version (default: "1.0.0") |
-c, --combined |
Generate combined OpenAPI spec |
-p, --parallel |
Process files in parallel |
Examples
Simple Object
Input JSON:
{
"name": "John",
"age": 30,
"active": true
}
Generated OpenAPI:
openapi: 3.0.3
info:
title: My API
version: 1.0.0
paths:
/:
get:
summary: Get My API
operationId: getMyAPI
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
name:
type: string
age:
type: integer
active:
type: boolean
Nested Structure
Input JSON:
{
"user": {
"id": 1,
"profile": {
"name": "Alice",
"email": "alice@example.com"
}
}
}
The tool automatically detects nested objects and creates the appropriate schema with properties.
Array with Objects
Input JSON:
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
The tool merges array object properties and generates comprehensive array item schemas.
API Reference
Python API
from json_to_openapi.schema_generator import OpenAPIGenerator, EndpointInfo
# Create generator
generator = OpenAPIGenerator(title="My API", version="1.0.0")
# Generate spec from JSON data
data = {"name": "Test", "value": 42}
spec = generator.generate(data)
# Generate spec with custom endpoint
endpoint = EndpointInfo(
path="/items",
method="get",
summary="Get Items",
description="Retrieve all items",
tags=["items"]
)
spec = generator.generate(data, endpoint=endpoint)
# Save to file
generator.save_spec(spec, "output.yaml", format="yaml")
Type Inference
The analyzer automatically detects:
- Basic Types: string, number, integer, boolean, null
- String Formats: date, date-time, email, uri, uuid, byte
- Complex Types: objects with properties, arrays with items
- Required Fields: All object properties are marked as required
- Integer Formats: int32 for standard integers, int64 for large integers
- Number Formats: double for floating-point numbers
Error Handling
The tool handles common errors gracefully:
- Invalid JSON: Provides helpful error messages with line numbers
- Empty JSON: Validates input has valid structure
- Invalid Output Path: Checks path permissions and parent directory existence
- Batch Processing: Continues processing remaining files and reports summary at end
Development
Running Tests
pytest tests/ -v
Test Coverage
pytest tests/ --cov=json_to_openapi --cov-report=html
Code Quality
ruff check .
mypy .
Project Structure
json-to-openapi/
├── json_to_openapi/
│ ├── __init__.py # Package initialization
│ ├── analyzer.py # JSON type inference and analysis
│ ├── cli.py # CLI interface
│ └── schema_generator.py # OpenAPI schema generation
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Pytest fixtures
│ ├── test_analyzer.py # Type inference tests
│ ├── test_schema_generator.py # Schema generation tests
│ ├── test_cli.py # CLI tests
│ └── test_integration.py # Integration tests
├── examples/
│ ├── users.json # Example user data
│ └── products.json # Example product data
├── .python-version
├── requirements.txt
├── setup.py
├── setup.cfg
├── pyproject.toml
└── README.md
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.