Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I annotate an endpoint in NestJS for OpenAPI that takes Multipart Form Data

My NestJS server has an endpoint that accepts files and also additional form data For example I pass a file and a user_id of the file creator in the form.

enter image description here

NestJS Swagger needs to be told explicitly that body contains the file and that the endpoint consumes multipart/form-data this is not documented in the NestJS docs https://docs.nestjs.com/openapi/types-and-parameters#types-and-parameters.

like image 474
auerbachb Avatar asked Sep 10 '25 09:09

auerbachb


1 Answers

Luckily some bugs led to discussion about how to handle this use case

looking at these two discussions https://github.com/nestjs/swagger/issues/167 https://github.com/nestjs/swagger/issues/417 I was able to put together the following

I have added annotation using a DTO: the two critical parts are:

in the DTO add

  @ApiProperty({
    type: 'file',
    properties: {
      file: {
        type: 'string',
        format: 'binary',
      },
    },
  })
  public readonly file: any;

  @IsString()
  public readonly user_id: string;

in the controller add

@ApiConsumes('multipart/form-data')

this gets me a working endpoint

and this OpenAPI Json

{
   "/users/files":{
      "post":{
         "operationId":"UsersController_addPrivateFile",
         "summary":"...",
         "parameters":[
            
         ],
         "requestBody":{
            "required":true,
            "content":{
               "multipart/form-data":{
                  "schema":{
                     "$ref":"#/components/schemas/UploadFileDto"
                  }
               }
            }
         }
      }
   }
}

...

{
   "UploadFileDto":{
      "type":"object",
      "properties":{
         "file":{
            "type":"file",
            "properties":{
               "file":{
                  "type":"string",
                  "format":"binary"
               }
            },
            "description":"...",
            "example":"'file': <any-kind-of-binary-file>"
         },
         "user_id":{
            "type":"string",
            "description":"...",
            "example":"cus_IPqRS333voIGbS"
         }
      },
      "required":[
         "file",
         "user_id"
      ]
   }
}

enter image description here

like image 140
auerbachb Avatar answered Sep 13 '25 01:09

auerbachb