2

I'm trying to make a request to an API sending an image and some other data, and getting the response. That's my code:

file = "assets/images/test.jpg"
conn = Faraday.new(:url => "api_url" ) do |faraday|
  faraday.request :multipart
end
payload = { :profile_pic => Faraday::UploadIO.new(file, 'image/jpeg') }
conn.post "/test", payload

My first problem is that I'm always getting the following error:

Errno::ENOENT (No such file or directory - assets/images/test.png)

I've tried all the paths I could imagine. Where should be saved the image in directories to be found by Faraday?

The second question is about the response, how can I get the response and handle it?

The third one is that, I haven't understand what's the utility of the first parameter of the last call:

conn.post "/hello", payload

I've written "/hello" but don't have any idea about what's the real usage.

And the last one. Could I send a raw image saved in a variable instead of sending a path to Faraday?

EDIT

Now it's working, this is the solution: Be aware that url must be only until .com, the rest of the path must go on conn.post like this example /v1/search. c.adapter :net_http was needed too. Message response is correctly handled in json variable.

Solution:

  url = 'http://url.com'

  file = Rails.root.to_s + "/app/assets/images/test.jpg"
  conn = Faraday.new(:url => url ) do |c|
    c.request :multipart
    c.adapter :net_http
  end
  payload = { :image => Faraday::UploadIO.new(file, 'image/jpeg'), :token => token}

  response = conn.post '/v1/search', payload
  json = JSON.parse response.body
user1573607
  • 522
  • 9
  • 23

1 Answers1

1

You should try this for your first question :

file = Rails.root.to_s + "/app/assets/images/test.jpg"

For your third question, the first parameters allows you to construct the right URL from the base "api_url". Please see the example from the Readme.

## POST ##

conn.post '/nigiri', { :name => 'Maguro' }  # POST "name=maguro" to http://sushi.com/nigiri
Pol0nium
  • 1,346
  • 4
  • 15
  • 31
  • In fact the correct answer is `file = Rails.root.to_s + "/app/assets/images/test.jpg"` But it have helped me to find it out. And about the other points? any idea? – user1573607 Nov 21 '13 at 13:43
  • @user1573607 I updated my answer. (I don't know the anwser for the second question, Perhaps you should print payload[:profile_pic] after the `conn.post` call and see what you get?) – Pol0nium Nov 21 '13 at 13:53