Jae
Jae

Reputation: 1157

How to check if HTTP request status is 200 OK in Rails

I want to do something like this post but in the actual Rails app, not the testing.

I want to see if the HTTP request was successful or not. If it's not successful (aka 404 Not Found), then I want to render a different HTML. But I can't figure out the syntax to compare.

Currently, I have:

  def videos
    # get current_user's wistia_project_id & authorization token
    @current_user = current_user
    project_id = @current_user.wistia_project_id
    auth_token = "blah"
    request = "https://api.wistia.com/v1/projects/#{project_id}.json?api_password=#{auth_token}"

    @response = HTTP.get(request).body

    puts HTTP.get(request).status

    # handle errors: not 200 OK
    if !HTTP.get(request).status:
      render "/errors.html.erb/"
    end

    # get embed code for each video using the hashed_id, put in list
    @video_iframe_urls = JSON.parse(@response)['medias'].map do |p|
      "https://fast.wistia.com/embed/iframe/#{p["hashed_id"]}?version=v1&controlsVisibleOnLoad=true&playerColor=aae3d8"
    end
  end

Upvotes: 0

Views: 2900

Answers (1)

7urkm3n
7urkm3n

Reputation: 6311

require 'net/http'

uri = URI("https://api.wistia.com/v1/projects/#{project_id}.json?api_password=#{auth_token}")
res = Net::HTTP.get_response(uri)

# Status
puts res.code       # => '200'
puts res.message    # => 'OK'
puts res.class.name # => 'HTTPOK'

# Body
puts res.body if res.response_body_permitted?

Upvotes: 1

Related Questions