'OpenAPI-generated Spring Boot server doesn't validate required properties

I am using OpenAPI Generator to generate Spring code based on the YAML file as below. But I noticed that Spring Boot validation doesn't work for required properties.

OpenAPI Generator CLI version: 5.2.1

OpenAPI spec file:

openapi: "3.0.3"
info:
  title: Example API
  version: "0.1.0"

paths:
  # AUTH
  /auth/login:
    post:
      operationId: authLogin
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AuthLoginRequest"
        required: true
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AuthLoginResponse"
          description: Session created successfully
      security: []
      summary: Creates a new session
      tags:
        - AUTH - Session management

components:
  schemas:
    AuthLoginRequest:
      type: object
      properties:
        username:
          type: string
        password:
          type: string
      required:
        - username
        - password

    AuthLoginResponse:
      type: object
      properties:
        token:
          type: string


Solution 1:[1]

Do you have validation dependencies on your classpath? If Spring Boot sees any validation mechanism on your classpath, it will use it. Otherwise, it will launch the server with no validation.

If you're using Maven, you can specify Spring validation with this dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

Or you can use Hibernate validation with this.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.2.Final</version>
</dependency>

(Be flexible on the version here.)

I doubt this is an exhaustive list. These are just the ones I've tried. They both work.

Solution 2:[2]

I've retrieved the fields with:

print([elem.name for elem in attr.fields(type(testb))]) # ['a_val', 'b_val']

alternatively to just see inherited fields:

print([elem.name for elem in attr.fields(type(testb)) if elem.inherited])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DharmanBot
Solution 2 rob