Search code examples
swaggerfastapiopenapicode-generationopenapi-generator

Does FastAPI generate this Enum correctly and if yes, why does the openapi-generator think it is invalid?


I am not quite sure where the issue lies, but FastAPI generates an OpenAPI file which I believe to be true and the openapi-generator-cli in the latest version thinks the OpenAPI file is invalid. The error message is:

Exception in thread "main" org.openapitools.codegen.SpecValidationException: There were issues with the specification. The option can be disabled via validateSpec (Maven/Gradle) or --skip-validate-spec (CLI).
 | Error count: 1, Warning count: 2
Errors: 
        -attribute paths.'/units/{id}/charts/'(get).parameters.[group_mode].schemas.required is not of type `array`
Warnings: 
        -attribute paths.'/units/{id}/charts/'(get).parameters.[group_mode].schemas.required is not of type `array`

        at org.openapitools.codegen.config.CodegenConfigurator.toContext(CodegenConfigurator.java:701)
        at org.openapitools.codegen.config.CodegenConfigurator.toClientOptInput(CodegenConfigurator.java:728)
        at org.openapitools.codegen.cmd.Generate.execute(Generate.java:519)
        at org.openapitools.codegen.cmd.OpenApiGeneratorCommand.run(OpenApiGeneratorCommand.java:32)
        at org.openapitools.codegen.OpenAPIGenerator.main(OpenAPIGenerator.java:66)

This is how the OpenAPI parameter looks:

OpenAPI schema image

And this is how it looks in the FastAPI code:

group_mode: GroupMode = Query(
        default="1d",
        description="Group by a parameter. Options are Minute, Hour, Day, Week, Month, Year.",
        required=True,
    ),

The first question would be, where the issue lies. Is the OpenAPI correct and the settings for the code generator (client is typescript-axios, but I tried with others, same issue) are wrong? Or is the code generator actually correct and the FastAPI generated spec is wrong? Or is it a coding issue on my side?


Solution

  • Your parameter declaration is a bit incorrect. This results in an invalid OpenAPI definition being generated by FastAPI, which in turn causes codegen errors.

    In FastAPI, query parameters are required by default unless the parameter is nullable (e.g. string | None) or has a default value. So you don't need the required=True annotation.

    Also, required parameters cannot have default values. Providing a default value is a hint to FastAPI to make the parameter optional. If you want to provide an example value for documentation purposes, use the example keyword instead.

    For more information, see FastAPI documentation on Required query parameters.


    To resolve the issue, change your parameter declaration to:

    group_mode: GroupMode = Query(
            example="1d",
            description="Group by a parameter. Options are Minute, Hour, Day, Week, Month, Year.",
        ),