Search code examples
ruby-on-railsjrubyckan

Create CKAN resource in RoR, providing file content as string


How does one create a CKAN resource in RoR, providing a string with file content?

This seems to be a working command line solution (if I save the file to filesystem):

curl -H 'Authorization: <api_key>' 'https://demo.ckan.org/api/action/resource_create' --form upload=@file.csv --form package_id=<pck_id>

Given that I have CSV file content as a string, how could I upload it to CKAN site?

Here is the code I have right now, resource is created but its content appears to be blank.

    http_client = HTTPClient.new

    temp_file = Tempfile.open('csv_export_tmp_file')
    temp_file.write(resource_content)

    body = {
      name: <filename>,
      title: <filetitle>,
      package_id: <package_id_here>,
      description: <description>,
      created: <created_at_time>,
      upload: temp_file,
      mimetype: 'text/csv',
      resource_type: 'file',
      format: 'csv'
    }
    response = http_client.post(resource_create_url, body, [['Authorization', api_key], ['Content-Type', 'multipart/form-data']])

    temp_file.close
    temp_file.unlink

Solution

  • This it the solution that I ended up using

        resource_create_url = 'ckan_site_url.com/api/action/resource_create'
    
        http_client = HTTPClient.new
    
        extended_string_io = Class.new(StringIO) do
          def path
            'data.csv'
          end
        end
    
        virtual_file = extended_string_io.new("my, csv, file, content\n1,2,3,4")
    
        body = {
          name: <filename>,
          title: <filetitle>,
          package_id: <package_id_here>,
          description: <description>,
          created: <created_at_time>,
          upload: virtual_file,
          resource_type: 'file',
          format: 'csv'
        }
        response = http_client.post(resource_create_url, body, [['Authorization', api_key]])