datamodel-code-generator
datamodel-code-generator copied to clipboard
Missing support for "const" keyword
Describe the bug
OpenAPI 3 references JSONSchema 2019-09 (since https://github.com/OAI/OpenAPI-Specification/pull/1977), which includes support for the const keyword. The const keyword is for defining constant value properties in schemas.
To Reproduce
Example schema (this is part of an OpenAPI specification):
{
"components": {
"schemas": {
"Namespace": {
"type": "object",
"required": [
"apiVersion",
"kind"
],
"properties": {
"apiVersion": {
"const": "v1"
},
"kind": {
"const": "Namespace"
},
"metadata": {
"$ref": "#/compoments/schemas/ObjectMeta"
}
}
}
}
}
}
Used commandline:
$ datamodel-codegen --input openapi.json --input-file-type openapi --output models.py
Expected behavior
I expected the generated model to look something like this:
class Namespace
apiVersion: str = "v1"
kind: str = "Namespace"
metadata: ObjectMeta
But what the cli currently generates is:
class Namespace:
apiVersion: Any
kind: Any
metadata: ObjectMeta
Version:
- OS: Fedora 35
- Python version: 3.10.0
- datamodel-code-generator version: 0.11.15
Or I guess more correctly:
class Namespace
apiVersion: str = Field("v1", cont=True)
kind: str = Field("Namespace", const=True)
metadata: ObjectMeta
@larsks I'm sorry for my late reply. Thank you for sharing the feature. I will add the feature to the cli.
The generated model file should use Literal Instead of const. Refer : https://github.com/samuelcolvin/pydantic/issues/561
@koxudaxi Hi! Are there any updates on adding this feature to datamodel-codegen?
Is there any progress for the implementation of the "const" keyword?
@larsks @bharathimohan11 @Sergei-Volkov @sjohnen
I'm sorry for my too-late reply.
I have released the PR as 0.15.0
Thank you very much!!