swagger-codegen-generators icon indicating copy to clipboard operation
swagger-codegen-generators copied to clipboard

Support for both required and optional form parameters

Open vigoo opened this issue 6 years ago • 1 comments

The current code that gathers the form parameters ignores the per-field required flag on them and overrides them based on the whole request body's required flag. I can see that this is intended as there are even tests for this behavior.

This is a serious limitation and prevents us describing some APIs that were possible with Swagger2 + codegen.

Let's see a modified version of the example used in the repo, requiredFormParamTest:

openapi: 3.0.0
info:
  title: Test Api
  version: '3.0.0'

paths:
  /test_required:
    post:
      summary: Operation with form body that is required
      operationId: get_with_required_body
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/Category'
      responses:
        "200":
          description: Success

  /test_optional:
    post:
      summary: Operation with form body that is optional
      operationId: get_with_optional_body
      requestBody:
        required: false
        content:
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/Category'
      responses:
        "200":
          description: Success

components:
  schemas:
    Category:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

The difference is that I explicitly marked id as required.

With this, get_with_required_body should mean that:

  • Having a application/x-www-form-urlencoded request body is required
  • The form must have an id field
  • The form can have a name field but it is optional

The generated code can accept requests with one of two form fields, and the request handler can get an optional value for the name and a non-optional one for the id.

In the get_with_optional_body the whole request body is optional, so the request handler would have to get all the parameters as optionals.

With the current implementation all the fields are either required or optional. I'm creating a pull request with a proposed implementation that reflects my interpretation described above.

vigoo avatar May 03 '19 09:05 vigoo

Hi @HugoMario, any chance to apply this PR? In our organization, we had to keep fork and apply changes manually.

ShemTovYosef avatar Dec 14 '25 09:12 ShemTovYosef