4

I have to migrate old eshop to new, made on Spree. It has good API to do it.

But i am stuck with uploading images from remote server. Here is what I am doing on making new product:

require 'nokogiri'
require 'open-uri'
require 'curb'
require 'uri'

http = Curl.post("http://DOMAIN/api/products?product[name]=Test\
  &product[price]=123\
  &product[shipping_category_id]=1\
  &product[taxon_ids]=52\
  &product[sku]=020323232\
  &product[image]=http://www.computercloset.org/Altair_8800_and_Santa.jpg") do |http|
    http.headers['X-Spree-Token'] = 'd60ff5896cef2920d83f18c11b95ee1dff8d9c82d1480cbc'
end

The product is saving with all parameters, except the image.

I think I have wrong syntax, but I am unable to find example or something about uploading images on http://guides.spreecommerce.com/api/

Evgeny
  • 61
  • 1
  • 2

3 Answers3

4

You likely won't be able to create an image that way.

Your best bet will be to create the images directly using this undocumented API call:

https://github.com/spree/spree/blob/v2.2.0/api/app/controllers/spree/api/images_controller.rb

As of 2.2.0, you can specify the following parameters: :alt, :attachment, :position, :viewable_type, :viewable_id

I expect that you may find this insufficient for doing what you're looking for. In particular, you'll need to upload the files separately from this process. This will just create the image record showing where it is stored (which goes through Paperclip). Specifying a full URL like you have listed is not likely to work. It will need to be a filename for a file stored in the place that Paperclip stores images.

This isn't an ideal experience, which is probably why this API call is undocumented. If you're able to modify it to make it work a bit better you should send a pull request to the Spree team. I'm sure they'd be happy to receive it.

gmacdougall
  • 4,901
  • 1
  • 16
  • 21
0

Yes you can upload images to the product, but with separate API call to POST: /api/v1/products/123/images

curl -i -X POST -H "X-Spree-Token: secrettoken123" /
-H "Content-Type: multipart/form-data" /
-F "image[attachment]=@/home/user/asd.jpg" /
-F "type=image/jpeg" http://localhost:3000/api/v1/products/123/images 
Vladimir Dimitrov
  • 1,008
  • 7
  • 21
0

There is an example of adding an image with the api here https://github.com/spree-contrib/spree_api_examples/blob/master/examples/images/product_image_creation.rb

You need to import their custom spree api client to use it but once you have that its as simple as

    image = File.dirname(__FILE__) + '/filename.jpg'
    attachment = Faraday::UploadIO.new(image, 'image/jpeg')

    # Adding an image to a product's master variant
    response = client.post('/api/products/#{product_id}/images',
      {
        image: {
          attachment: attachment
        }
      }
    )
Qwertie
  • 5,784
  • 12
  • 45
  • 89