Search code examples
rubyruby-on-rails-2rest-client

How to test if RestClient is returning a file or a JSON?


I'm calling a URL that either returns a file or a JSON with an error message. So, for example

resp = RestClient.get "my_url"
=> "\037\213\b\b\n\206XR\002\3....."

and

resp = RestClient.get "my_url"
=> "{\"status\": 1}"

I need to define if the output is a JSON or a file. So I could do something like this:

begin 
  JSON.parse(resp)
  # is a json
rescue ExceptionThatIDontRecallTheNameRightNow => e
  # it is a file
end

But this actually don't work because we would have a malformed json as a file.

So the question is, how can I verify if this answer is a file or a JSON?


Solution

  • This seems to do it:

    resp = RestClient.post(full_url, params, HTTP_HEADERS)
    if resp.headers[:content_type] == 'application/octet-stream'
      resp
    else
      resp = JSON.parse(resp)
      ...
    end