Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making JSON API calls within Rails app

We have deployed an instance of Wordpress and have installed a JSON API plug in

Using this plug-in you can make simple HTTP GET request like:

http://www.example.org/?json=get_recent_posts
http://www.example.org/?json=get_post&post_id=47
http://www.example.org/?json=get_tag_posts&tag_slug=banana

And a response comes back in JSON:

{
"status": "ok",
"count": 1,
"count_total": 1,
"pages": 1,
"posts": [
{...}}

My question is how should I go about making these types of requests (and then parsing the returned JSON) in my Rails app. I was about to get started just writing something from scratch but I imagine there's some good existing tools out there to manage something like this. Basically I've never attempted connecting to an API when a Ruby-wrapper wasn't already available. Can you help a noob with how to get started?

like image 272
pejmanjohn Avatar asked Oct 10 '12 22:10

pejmanjohn


People also ask

Can you use JSON with REST API?

REST APIs should accept JSON for request payload and also send responses to JSON. JSON is the standard for transferring data. Almost every networked technology can use it: JavaScript has built-in methods to encode and decode JSON either through the Fetch API or another HTTP client.


1 Answers

It looks like HTTParty is probably your best case for something like this. I think it'll be an easy way for you to get started and handles the JSON for you easily.

Add 'httparty' to your Gemfile and bundle.

recent_posts = HTTParty.get "http://www.example.org/?json=get_recent_posts"
puts recent_posts.status, recent_posts.count

recent_posts.posts.each do |post|
  puts post.title #guessing
end
like image 150
Jesse Wolgamott Avatar answered Sep 20 '22 13:09

Jesse Wolgamott