Reputation: 3585
I am learning how to write a restful API using RoR and have a question related to it. So, I will explain what I did along with the code.
This is how my controller looks like:
class EmployeesController < ApplicationController
require 'rest_client'
def index
uri = "localhost:3000/employees"
rest_resource = RestClient::Resource.new(uri)
users = rest_resource.get # will get back you all the detail in json format, but it will we wraped as string, so we will parse it in the next step.
@users = JSON.parse(users, :symbolize_names => true) # convert the return data into array
@users.each do |u|
logger.info(u.id)
end
# return based on the format type
respond_to do |format|
format.json {render json: @users}
format.xml {render xml: @users}
format.html
end
end
end
In my Gemfile, I have included rest-client as well.
gem 'rest-client'
My routes are : root 'employees#index' resources 'employees'
Hope everything is fine till now.
Now, when I send:
-> Curl request to 'http://localhost:3000/employees', it gets stuck.
-> Get request(by typing in the browser) to 'http://localhost:3000/', it get stuck here as well.
What is that which I am missing?
Upvotes: 0
Views: 165
Reputation: 46509
You don't need RestClient as you're writing a server here, not a client. The browser acts as the client. Remove the call to localhost as it's creating a loop.
The URL for this should already be set in your routes.rb, maybe using:
resources :users
Assuming this is a typical app, the show function should be reading from the database using ActiveRecord.
class EmployeesController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.json {render json: @users}
format.xml {render xml: @users}
format.html
end
end
end
Upvotes: 1
Reputation: 2421
You actually can do this without any additional gem. You just need to declare your routes according to what you want to expose to your API users and return the type (xml, json, ...) accordingly.
Upvotes: 0
Reputation: 433
Do you have some other application running on localhost:3000? Because if not, then what your server does is calling himself again and again, causing a loop.
If you do have some other application, which fetches users from database, then be sure its running on some other port, other than this your rails app.
If you have only 1 app, then you don't need rest client.
Upvotes: 0