datamodel-code-generator
datamodel-code-generator copied to clipboard
Support for older V2 OpenAPI documents
Is your feature request related to a problem? Please describe.
Given a 2.0 OpenAPI document, trying to import it fails as it finds no models
Args:
--input-file-type openapi --input openapi/ProductSearch.json --output doc_insights/openapi/product_search.py --openapi-scopes schemas
Describe the solution you'd like
Auto-detection of the v2 api via the "swagger": "2.0" or "openapi": "2.0" part (or a cli flag).
Then under v2 mode, load definitions instead of components.schemas
So https://github.com/koxudaxi/datamodel-code-generator/blob/2df133c00949b6efce6f1493c6ce0e341872b955/datamodel_code_generator/parser/openapi.py#L586C13-L588 would turn into
schemas: Dict[Any, Any] = specification.get('definitions', {})
Making this change works for me, but there might be other v2/v3 incompatibilities that my use case doesn't run into.
Describe alternatives you've considered It doesn't look like there is a way to load v2 OpenAPI docs in this tool, I also don't have control over the spec so I can't update it to v3.
FWIW, I came across this SO answer about using the Swagger Converter to convert OAS 2 specs to v3.
For me, the Swagger Editor didn't work for my doc (Edit: Though their beta site did), but if the OAS file is accessible online, you could use File -> Import URL.
I was then able to use datamodel-codegen against the output to generate classes.
If you don't mind sending your API spec through a third party, you can use https://converter.swagger.io/.
Further, if your v2 spec is hosted somewhere publicly, you can use the GET /convert endpoint directly. Say your API spec is hosted at https://www.example.com/swagger-2.json, you can run something like
datamodel-codegen --input-file-type openapi \
--url 'https://converter.swagger.io/api/convert?url=https://www.example.com/swagger-2.json'
If you don't want your data going through a third party (or you intend to make a high volume of conversion requests) you can run the converter locally in docker - see https://github.com/swagger-api/swagger-converter for details.