rubyapihttparty

How to get api data using api keys in httparty ruby


i have been trying to get the api data using httparty and been doing it like this

require 'httparty'

doc = HTTParty.get('http://ip-api.com/php/105.49.23.183')

puts doc['status']

The api response is

a:14:{s:6:"status";s:7:"success";s:7:"country";s:5:"Kenya";s:11:"countryCode";s:2:"KE";s:6:"region";s:2:"30";s:10:"regionName";s:16:"Nairobi Province";s:4:"city";s:7:"Nairobi";s:3:"zip";s:5:"09831";s:3:"lat";d:-1.25909;s:3:"lon";d:36.7858;s:8:"timezone";s:14:"Africa/Nairobi";s:3:"isp";s:17:"Safaricom Limited";s:3:"org";s:3:"SFC";s:2:"as";s:25:"AS33771 Safaricom Limited";s:5:"query";s:13:"105.49.23.183";}

but the output when i run my script is just status but i need it to return the data responding to the status key which is success. I can't figure it out how to do this. Initially in python this method works but ruby is different


Solution

  • Just use the JSON formatted API endpoint:

    require 'httparty'
    doc = HTTParty.get('http://ip-api.com/json/105.49.23.183')
    puts doc['status']
    #=> "success"
    

    Notice the json instead of the php in the URL path. The serialized PHP endpoint is deprecated anyway.