OpenAPITools / OpenAPITools/openapi-generator

Spring Generator generates invalid API when response is an array of objects or primitives

Open
#11,897 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • [Y ] Have you provided a full/minimal spec to reproduce the issue?
  • [ Y] Have you validated the input using an OpenAPI validator (example)?
  • [ N] Have you tested with the latest master to confirm the issue still exists?
  • [Y ] Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

When using OpenAPI generator with language=spring and library=spring-boot with the following configuration on an OAS 3.0.3 spec which has Response object as an array of values (could be primitives or objects), the generated Java code has an error

The API has 'array' in the ResponseEntity type

   /**
     * GET /v1/groups : Get groups.
     * Get the list of groups for this example.
     *
     * @return List of groups. (status code 200)
     *         or Unauthorized (status code 401)
     *         or Forbidden (status code 403)
     *         or No groups found. (status code 404)
     *         or InternalServerError (status code 500)
     */
    @Operation(
        operationId = "getGroups",
        summary = "Get groups.",
        tags = { "metadata" },
        responses = {
            @ApiResponse(responseCode = "200", description = "List of groups.", content = @Content(mediaType = "application/json", schema = @Schema(implementation =  String.class))),
            @ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = "application/json", schema = @Schema(implementation =  HttpError.class))),
            @ApiResponse(responseCode = "403", description = "Forbidden", content = @Content(mediaType = "application/json", schema = @Schema(implementation =  HttpError.class))),
            @ApiResponse(responseCode = "404", description = "No groups found.", content = @Content(mediaType = "application/json", schema = @Schema(implementation =  HttpError.class))),
            @ApiResponse(responseCode = "500", description = "InternalServerError", content = @Content(mediaType = "application/json", schema = @Schema(implementation =  HttpError.class)))
        },
        security = {
            @SecurityRequirement(name = "bearerAuth")
        }
    )
    @RequestMapping(
        method = RequestMethod.GET,
        value = "/v1/groups",
        produces = { "application/json" }
    )
    ResponseEntity<array<java.util.List<String>>> getGroups(
        
    );
openapi-generator version

Open API Generator version - 5.4.0

OpenAPI declaration file content or url

Open API declaration file

openapi: 3.0.1
info:
  title: metadata-svc
  description: Metadata Service
  contact:
    name: Test Svc
    email: xyz@xyz.com
  version: 3.1.2
servers:
  - url: https://localhost:8080/
tags:
  - name: metadata
    description: APIs to get metadata.
paths:
  /v1/groups:
    get:
      tags:
        - metadata
      summary: Get groups.
      description: Get the list of groups for this example.
      operationId: get-groups
      responses:
        200:
          description: List of groups.
          content:
            application/json:
#              schema:
#                type: array
#                items:
#                  $ref: '#/components/schemas/TestResponse'
#              schema:
#                $ref: '#/components/schemas/Groups'
              schema:
                type: array
                items:
                  type: string
        401:
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HttpError'
        403:
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HttpError'
        404:
          description: No groups found.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HttpError'
        500:
          description: InternalServerError
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HttpError'
      deprecated: false
      security:
        - bearerAuth: []
components:
  schemas:
    Groups:
      type: array
      items:
        type: string
    HttpError:
      title: HttpError
      type: object
      properties:
        code:
          type: integer
          format: int32
        details:
          type: array
          items:
            $ref: '#/components/schemas/HttpErrorDetail'
        message:
          type: string
        traceId:
          type: string
    HttpErrorDetail:
      title: HttpErrorDetail
      type: object
      properties:
        code:
          type: string
        localizedMessage:
          type: string
        message:
          type: string
    TestResponse:
      title: TestResponse
      required:
        - enabled
      type: object
      properties:
        enabled:
          type: boolean
          description: Default value is false.
          example: false
      description: Object
  securitySchemes:
    bearerAuth:
      type: apiKey
      name: Authorization
      in: header
Generation Details

Using hidetake swagger generator the configuration is below

    service {
        inputFile = file("${project.rootDir}/schemas/test.yaml")
        code {
            language = 'spring'
            library = 'spring-boot'
            additionalProperties = [
                    invokerPackage           : "com.kv.groups",
                    basePackage              : "com.kv.groups",
                    apiPackage               : "com.kv.groupsapi",
                    modelPackage             : "com.kv.groups.api.models",
                    fullJavaUtil             : "true",
                    hideGenerationTimestamp  : "true",
                    useTags                  : "true",
                    interfaceOnly            : "true",
                    skipDefaultInterface     : "true",
                    additionalModelTypeAnnotations : "@lombok.Builder(toBuilder=true)",
                    performBeanValidation:    "true",
                    useSpringController :  "true",
                    serializationLibrary: "jackson"
            ]
        }
    }
Steps to reproduce

Using the OpenAP 3.0.1 yaml above try generating the code for spring generator either 1. using the gradle config above or using the CLI

openapi-generator generate -g spring -i test.yaml -c conf.json -o spring-boot-codegenerator

The generated MetadataApi.java has ReponseEntioty as follows

ResponseEntity<array<java.util.List<String>>> getGroups(

    );
Related issues/PRs
Suggest a fix

There should not be "array "in the generated Java code

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided OpenAPI YAML through the spring generator with the shown CLI command or configuration, then inspect the generated MetadataApi.java. Trace how the array response schema becomes the ResponseEntity type; done means the generated Java API uses a valid collection type without the literal "array" token.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
api, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.