koxudaxi / datamodel-code-generator

Pydantic model and dataclasses.dataclass generator for easy conversion of JSON, OpenAPI, JSON Schema, and YAML data sources.
https://koxudaxi.github.io/datamodel-code-generator/
MIT License
2.69k stars 296 forks source link

Support for older V2 OpenAPI documents #2115

Open hydrogen602 opened 2 hours ago

hydrogen602 commented 2 hours ago

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.

DefiDebauchery commented 2 hours ago

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.