Wilson
Wilson

Reputation: 181

Accessing a 3rd party API JSON object in ruby

Been messing around with Kickbox's api for email verification. I'm trying to have the program only display the result object in the returned JSON.

Here's the code:

require "kickbox"
require 'httparty'
require 'json'


client   = Kickbox::Client.new('ac748asdfwef2fbf0e8177786233a6906cd3dcaa')
kickbox  = client.kickbox()
response = kickbox.verify("[email protected]")

file = File.read(response)

json = JSON.parse(file)

json['result'] 

I'm getting an error verify.rb:10:in read': no implicit conversion of Kickbox::HttpClient::Response into String (TypeError) from verify.rb:10:in'

Here's a sample response:

{
  "result":"undeliverable",
  "reason":"rejected_email",
  "role":false,
  "free":false,
  "disposable":false,
  "accept_all":false,
  "did_you_mean":"[email protected]",
  "sendex":0,
  "email":"[email protected]",
  "user":"bill.lumbergh",
  "domain":"gamil.com",
  "success":true,
  "message":null
}

Upvotes: 2

Views: 69

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

You are getting this error:

read': no implicit conversion of Kickbox::HttpClient::Response into String (TypeError)

Because, in this line:

file = File.read(response)

Your response is a Kickbox::HttpClient::Response type object, but the File.read is expecting a String object instead (possibly a file name with path).

I'm not sure what you are trying to do, but this: file = File.read(response) is wrong. You can't do this and that's why you are getting the mentioned error.

If you really want to use file, then you can write the response to a file and then read the response back from the file and use that:

f = File.new('response.txt', 'w+') # creating a file in read/write mode
f.write(response) # writing the response into that file
file_content = File.read('response.txt') # reading the response back from the file

So, the issue is not about Accessing a 3rd party API JSON object in ruby, but you are trying to use File.read in a wrong way.

You can get the response from the API by doing this:

client   = Kickbox::Client.new('YOUR_API_KEY')
kickbox  = client.kickbox()
response = kickbox.verify("[email protected]")

Then, you can play with the response e.g. can do a puts response.inspect or puts response.body.inspect and see what's inside that object. And, from there you can extract your required outputs only.

Upvotes: 1

Related Questions