How to upload product images using the Spree Commerce REST API

I need to transfer the old eshop to a new one made on Spree. It has a good API to do this.

But I am stuck in downloading images from a remote server. Here is what I do when creating a 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 saves all parameters except the image.

I think I have the wrong syntax, but I cannot find an example or something about uploading images to http://guides.spreecommerce.com/api/

+4
source share
3 answers

You probably won't be able to create an image this way.

It is best to create images directly using this undocumented API call:

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

2.2.0 : : alt,: attachment,: position,: viewable_type,: viewable_id

, , , . , . , , ( Paperclip). URL-, , . , , Paperclip .

, , , API . , , Spree. , .

+3

, , API 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 
0

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

You need to import your custom api spi client in order to use it, but once you have it it is as simple as

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

    # Adding an image to a product master variant
    response = client.post('/api/products/#{product_id}/images',
      {
        image: {
          attachment: attachment
        }
      }
    )
0
source

Source: https://habr.com/ru/post/1531052/


All Articles