Carapacik / swagger_parser

Dart package that takes an OpenApi definition file and generates REST clients based on retrofit and data classes for your project.
https://pub.dev/packages/swagger_parser
MIT License
88 stars 33 forks source link

multipart/form-data Files Type #169

Closed simonmoser-bluesource closed 4 months ago

simonmoser-bluesource commented 4 months ago

In the current generated code the dart:io File type is used. This is also used in the retrofit documentation.

I'm no expert in dart but a File is always a real File in the file system: https://api.dart.dev/stable/3.3.0/dart-io/File-class.html

When i.e. I want to upload a file that is only available as byte array (i.e. an in memory image) to a server. I would have to save the byte array in a temp file and upload it.

A far simpler approach is to use dio:Multipartfile https://pub.dev/documentation/dio/latest/dio/MultipartFile-class.html

A Multipartfile can also be loaded from a path. With this a File can easily converted to Multipartfile.

I manually changed the generated code to use MultipartFile instead of File, but this would maybe a welcome change by others, since it makes it far easier to handle file uploads.

The generated Code with MultipartFile:

@RestApi()
abstract class ClientClient {
  factory ClientClient(Dio dio, {String? baseUrl}) = _ClientClient;

  /// create  item
  @MultiPart()
  @POST('/api/item')
  Future<String> postApiItem({
    @Part(name: 'images') List<MultipartFile>? images,
  });
}

Example Yaml:

openapi: 3.0.2
info:
  title: API
  version: 1.0.0
paths:
  /api/item:
    post:
      summary: create  item
      requestBody:
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/Item'
      responses:
        '200':
          description: dummy
          content:
            text/plain:
              schema:
                type: string
components:
  schemas:
    Item:
      type: object
      properties:
        images:
          type: array
          items:
            description: Binary image
            format: binary
            type: string
StarProxima commented 4 months ago

Unfortunately, Retrofit does not support single MultipartFile https://github.com/trevorwang/retrofit.dart/issues/529

simonmoser-bluesource commented 4 months ago

@StarProxima oh thanks for your answer! I used it with an array, which works. but was not aware that this is not possible with a single file with retrofit. 🙏