Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NestJS with Swagger report all my DTO properties as required?

Tags:

swagger

nestjs

I have this DTO class defined.

import { ApiProperty } from "@nestjs/swagger"

export class FormDTO {
    @ApiProperty()
    id: string

    @ApiProperty()
    type: string

    @ApiProperty()
    fieldValues?: Record<string, unknown>

    @ApiProperty()
    parentFormId?: string
}

I expected that the generated OpenAPI spec would indicate that fieldValues and parentFormId would be optional, but they are required.

enter image description here

According to the example in the docs here they should be optional. What am I missing?

The only method using that DTO looks like this, but I didn't think it would matter:

@Post(":id")
createForm(@Body() createFormDto: FormDTO) {
    if (this.formService.hasForm(createFormDto.id)) {
        throw new ConflictException(
            undefined,
            `A form with the id ${createFormDto.id} already exists.`
        )
    }
    return this.formService.createOrUpdateForm(createFormDto)
}

If it matters, here is the code for the DocumentBuilder

const config = new DocumentBuilder()
    .setTitle("API")
    .setDescription(
        "description."
    )
    .setVersion("1.0")
    .addBearerAuth(
        {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
            description: "Paste a valid access token here."
        },
        JWTGuard.name
    )
    .build()
like image 883
Thomas Avatar asked Oct 11 '25 18:10

Thomas


1 Answers

because that's what @ApiProperty() does

Instead, use @ApiPropertyOptional() for optional fields.