Search code examples
ruby-on-railscarrierwaveruby-grapegrape-api

Grape - File Upload - Parameter declaration


I am writing my first API using Grape and am quite excited and it sounds and feels grate. Running through the notes I couldn't find a way to declare parameters for a file.

Below is a work-in-progress class for providing profile details, updating profile details and uploading a profile image. I got this params do; end block to define required fields and would like to do so for the file upload as well. But what is the type going to be?

Tried to find an example online and the few that I came across didn't use it. Probably trivial and a silly question, but I am finding difficulty finding it.

Update: The file upload it self uses Carrier-wave and an uploader called ProfilePictureUploader but I doubt it is the case.

class AccountApi < Grape::API

  resource :account do

    desc 'View the current user profile'
    get :profile do
      present current_user, with: Presenters::UserPresenter
    end

    desc 'Update the current user profile'
    params do
      requires :email,      type: String,   desc: 'User email'
      requires :first_name, type: String,   desc: 'First name'
      requires :last_name,  type: String,   desc: 'Last name'
      requires :phone,      type: String,   desc: 'Phone number'
      requires :school_id,  type: Integer,  desc: 'School ID'
    end
    put :profile do
    end

    desc 'Upload profile picture'
    # params do
    #   requires :user, type: Hash do
    #     requires :profile_picture, type: <<??????>>, desc: 'User profile picture'
    #   end
    # end
    post :profile_picture do
      profile_picture = params[:user][:profile_picture]

      status = current_user.update(profile_picture: profile_picture)

      {
        status: status,
        size: profile_picture[:tempfile].size,
      }
    end

  end

end

Thanks in advance for your support. You have a nice day there.


Solution

  • I think the type you're looking for is Rack::Multipart::UploadedFile or just File:

    params do
       requires :user, type: Hash do
         requires :profile_picture, type: Rack::Multipart::UploadedFile, desc: 'User profile picture'
       end
     end
    

    It's one grape supported types as here.