or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdgeneration.mdindex.mdtypes-config.mdutilities.md

cli.mddocs/

0

# CLI Interface

1

2

Command-line interface for generating Python data models from various schema formats. The `datamodel-codegen` command provides access to all generation features through command-line arguments.

3

4

## Capabilities

5

6

### Main CLI Entry Point

7

8

Primary command-line interface accessed through the `datamodel-codegen` console script.

9

10

```python { .api }

11

def main(args: Sequence[str] | None = None) -> Exit:

12

"""

13

Main CLI entry point for datamodel-codegen command.

14

15

Parses command-line arguments and calls generate() function with

16

appropriate parameters. Handles user input validation, error reporting,

17

and output formatting.

18

19

Args:

20

args: Command-line arguments (uses sys.argv[1:] if None)

21

22

Returns:

23

Exit enum indicating success or failure status

24

25

Exit codes:

26

Exit.OK (0): Successful completion

27

Exit.ERROR (1): General error (invalid arguments, processing failure, etc.)

28

Exit.KeyboardInterrupt (2): User interrupted operation

29

"""

30

```

31

32

## Types

33

34

```python { .api }

35

class Exit(IntEnum):

36

"""Exit status codes for CLI operations."""

37

38

OK = 0 # Successful completion

39

ERROR = 1 # General error

40

KeyboardInterrupt = 2 # User interrupted operation

41

```

42

43

### Command-Line Usage

44

45

#### Basic Syntax

46

```bash

47

datamodel-codegen [OPTIONS]

48

```

49

50

#### Required Options

51

```bash

52

--input INPUT_FILE # Input file path or URL

53

--output OUTPUT_FILE # Output file path

54

```

55

56

#### Common Options

57

```bash

58

# Input/Output Control

59

--input-file-type TYPE # Input format (auto|openapi|jsonschema|json|yaml|csv|graphql)

60

--output-model-type TYPE # Output model type (pydantic.BaseModel|pydantic_v2.BaseModel|dataclasses.dataclass|typing.TypedDict|msgspec.Struct)

61

--encoding ENCODING # File encoding (default: utf-8)

62

63

# Code Generation Options

64

--target-python-version VER # Target Python version (3.9|3.10|3.11|3.12|3.13)

65

--base-class CLASS # Custom base class

66

--class-name NAME # Root class name

67

--field-constraints # Include field validation constraints

68

--validation # Enable Pydantic validation features

69

--use-annotated # Use typing.Annotated for annotations

70

71

# Field Naming Options

72

--snake-case-field # Convert field names to snake_case

73

--original-field-name-delimiter DELIM # Delimiter for original field names

74

--aliases MAPPING # Custom field name aliases

75

--capitalise-enum-members # Capitalize enum member names

76

77

# Output Formatting

78

--disable-timestamp # Skip timestamp in file header

79

--enable-version-header # Include package version in header

80

--custom-file-header PATH # Path to custom file header

81

--formatters LIST # Code formatters (black,isort,ruff-check,ruff-format)

82

--use-double-quotes # Use double quotes in generated code

83

84

# Model Behavior

85

--strip-default-none # Remove None default values

86

--allow-extra-fields # Allow extra fields in models

87

--force-optional-for-required-fields # Make all fields optional

88

--reuse-model # Reuse models with same structure

89

--use-schema-description # Use schema descriptions in docstrings

90

--use-field-description # Use field descriptions in field definitions

91

92

# Advanced Options

93

--custom-template-dir DIR # Directory with custom Jinja2 templates

94

--http-headers HEADERS # Headers for HTTP requests (format: "key:value")

95

--http-ignore-tls # Ignore TLS verification

96

--openapi-scopes SCOPES # OpenAPI parsing scopes (schemas,paths,tags,parameters)

97

--enum-field-as-literal TYPE # Convert enums to literals (all|one)

98

--strict-types TYPES # Enable strict typing for types (str,bytes,int,float,bool)

99

```

100

101

## Usage Examples

102

103

### Basic Model Generation

104

```bash

105

# Generate Pydantic models from OpenAPI spec

106

datamodel-codegen --input api.yaml --output models.py

107

108

# Generate from JSON Schema

109

datamodel-codegen --input schema.json --output models.py --input-file-type jsonschema

110

```

111

112

### Different Output Model Types

113

```bash

114

# Generate Pydantic v2 models

115

datamodel-codegen --input schema.yaml --output models.py --output-model-type pydantic_v2.BaseModel

116

117

# Generate dataclasses

118

datamodel-codegen --input data.json --output models.py --output-model-type dataclasses.dataclass

119

120

# Generate TypedDict

121

datamodel-codegen --input schema.json --output types.py --output-model-type typing.TypedDict

122

```

123

124

### Advanced Configuration

125

```bash

126

# With field constraints and validation

127

datamodel-codegen \

128

--input openapi.yaml \

129

--output models.py \

130

--field-constraints \

131

--validation \

132

--use-schema-description \

133

--snake-case-field

134

135

# With custom formatting and Python version

136

datamodel-codegen \

137

--input schema.json \

138

--output models.py \

139

--target-python-version 3.11 \

140

--formatters black,isort,ruff-format \

141

--use-double-quotes \

142

--use-annotated

143

```

144

145

### Remote Schema Fetching

146

```bash

147

# Fetch from URL with authentication

148

datamodel-codegen \

149

--input https://api.example.com/schema.yaml \

150

--output api_models.py \

151

--http-headers "Authorization:Bearer token123" \

152

--http-headers "User-Agent:datamodel-codegen"

153

154

# With custom query parameters

155

datamodel-codegen \

156

--input "https://api.example.com/schema?version=v2" \

157

--output models.py \

158

--http-ignore-tls

159

```

160

161

### OpenAPI-Specific Options

162

```bash

163

# Generate from OpenAPI with path parameters

164

datamodel-codegen \

165

--input openapi.yaml \

166

--output models.py \

167

--input-file-type openapi \

168

--openapi-scopes schemas,paths \

169

--include-path-parameters \

170

--use-operation-id-as-name

171

```

172

173

### GraphQL Schema Generation

174

```bash

175

# Generate from GraphQL schema (requires graphql extra)

176

datamodel-codegen \

177

--input schema.graphql \

178

--output models.py \

179

--input-file-type graphql

180

```

181

182

### Custom Templates and Headers

183

```bash

184

# Use custom templates and file header

185

datamodel-codegen \

186

--input schema.json \

187

--output models.py \

188

--custom-template-dir ./templates \

189

--custom-file-header ./header.txt \

190

--disable-timestamp

191

```

192

193

### Enum and Literal Handling

194

```bash

195

# Convert enums to literals

196

datamodel-codegen \

197

--input schema.json \

198

--output models.py \

199

--enum-field-as-literal all \

200

--capitalise-enum-members \

201

--use-one-literal-as-default

202

```

203

204

## Error Handling

205

206

The CLI provides clear error messages for common issues:

207

208

```bash

209

# Invalid input file

210

$ datamodel-codegen --input nonexistent.yaml --output models.py

211

Error: File not found

212

213

# Unsupported input format

214

$ datamodel-codegen --input invalid.txt --output models.py

215

Error: Invalid file format

216

217

# Missing required arguments

218

$ datamodel-codegen --input schema.json

219

Error: --output is required

220

```

221

222

## Environment Variables

223

224

Some CLI behavior can be controlled via environment variables:

225

226

```bash

227

# Set default encoding

228

export DATAMODEL_CODEGEN_ENCODING=utf-8

229

230

# Enable debug mode (requires debug extra)

231

export DATAMODEL_CODEGEN_DEBUG=1

232

```

233

234

## Integration Examples

235

236

### Makefile Integration

237

```makefile

238

generate-models:

239

datamodel-codegen \

240

--input schemas/api.yaml \

241

--output src/models.py \

242

--output-model-type pydantic_v2.BaseModel \

243

--field-constraints \

244

--formatters black,isort

245

```

246

247

### CI/CD Pipeline

248

```yaml

249

# GitHub Actions example

250

- name: Generate Models

251

run: |

252

pip install datamodel-code-generator

253

datamodel-codegen \

254

--input ${{ github.workspace }}/schemas/openapi.yaml \

255

--output ${{ github.workspace }}/src/generated_models.py \

256

--validation \

257

--use-schema-description

258

```

259

260

### Pre-commit Hook

261

```yaml

262

# .pre-commit-config.yaml

263

repos:

264

- repo: local

265

hooks:

266

- id: generate-models

267

name: Generate data models

268

entry: datamodel-codegen

269

args: [--input, schemas/api.yaml, --output, src/models.py]

270

files: ^schemas/.*\.(yaml|json)$

271

language: system

272

```