Hey all, I've got a client that is integrating a Rails 1.2.6 site with another site that exposes services RESTfully. Upgrading to Rails 2.x is not an option at this time. Does anyone have recommendations for methods other than direct Net::HTTP calls to communicate with the REST service? Techniques or Gem recommendations are welcome, but most of the gems I've seen seem to have a dependency on ActiveSupport 2.x, which I understand to be incompatible with Rails 1.x.
Thanks in advance for any input you can provide.
Try HTTParty. It's very light on the dependencies, and makes it braindead-easy to add consumption of JSON or XML resources to an application.
Thanks Chris Heald for your response. I did end up using Net::HTTP because it was more straightforward than I thought it was in the end. HTTParty looks like it could make this easier still, but for the benefit of future people with this problem, here's what I did.
# Assume #user_name and #password were previously declared to be the
# appropriate basic auth values and that the connection is open as #connection
def put(path, body, header={})
request = Net::HTTP::Put.new(path, header.merge({'Accept' => 'application/xml,application/json', 'Content-type'=>'application/json'}))
request.basic_auth(#user_name, #password)
#connection.request(request, body).body
end
def post(path, body, header={})
request = Net::HTTP::Post.new(path, header.merge({'Accept' => 'application/xml,application/json', 'Content-type'=>'application/json'}))
request.basic_auth(#user_name, #password)
#connection.request(request, body).body
end
def get(path, header={})
request = Net::HTTP::Get.new(path)
request.basic_auth(#user_name, #password)
#connection.request(request).body
end
I then called JSON::parse() on the output of these methods and got a hash representing the JSON that I could use as I saw fit.
Related
My app controller accepts requests from third party API (webhooks), but when it becomes 400 RPM my site goes down (too many clients). What can I do with it?
class CallbacksController < ApplicationController
def acceptor
if params['type'] == 'confirmation' # this type is rare. only when client switches on callback
group_setting = GroupSetting.find_by_callback_token(params[:callback_token])
if group_setting
group_setting.update_attribute(:use_callback, true)
GroupSetting.new.callback_start(group_setting.group, group_setting.user)
render text: group_setting.response_string
else
render text:'ok'
end
else
CallbackWorker.perform_async(params[:callback_token], params['type'],
params['group_id'], params['object'],
params['secret'])
render text:'ok'
end
end
end
It seems to me that you have a web server thread bottleneck. Could you specify which server are you using? Can you make an Apache Benchmark and post the results? Maybe a little more information on your setup could help.
If you are using WEBrick, I would advise trying with PUMA.
I would also suggest that you check out Passenger that integrates easily with NGINX or Unicorn, that can help you with load balancing your requests.
I need to use an external API in my app in order to have companies informations. Beginning and having never used API in ruby, I don't know where to start. Maybe there is a gem for it but I have found 2 API that returns me JSON : https://datainfogreffe.fr/api/v1/documentation and https://firmapi.com/ (they're in french sorry about that).
Does someone have a good tutorial or hints to help me begin ?
The final need is to retrieve companies datas just by giving the company ID.
You can use Net::HTTP to call APIs in Ruby on Rails.
uri = URI(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = {} # SOME JSON DATA e.g {msg: 'Why'}.to_json
response = http.request(request)
body = JSON.parse(response.body) # e.g {answer: 'because it was there'}
http://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTP.html
You can use gem for calling REST APIs in ruby.
Also, if you want to find any ruby gem for any purpose you can have a look at this.
You can have a look at this to get company details.
You need to use HTTP client library. There are a few popular libraries:
HTTParty
Faraday
Built-in Net::HTTP
Rest-Client
HTTPClient
You can take a look and compare them on Ruby Toolbox:
https://www.ruby-toolbox.com/categories/http_clients
Faraday is the most popular one. But it is the heaviest also because it covers most cases. So check documentation for each and depending on your task pick one that works the best.
I have a typical Rails REST Api written for a http consumers. However, it turns out they need web socket API because of the integration POS Machines.
The typical API looks like this;
class Api::Pos::V1::TransactionsController < ApplicationController
before_action :authenticate
def index
#transactions = #current_business.business_account.business_deposits.last(5)
render json: {
status: 200,
number: #transactions.count,
transactions: #transactions.as_json(only: [:created_at, :amount, :status, :client_card_number, :client_phone_number])
}
end
private
def request_params
params.permit(:account_number, :api_key)
end
def authenticate
render status: 401, json: {
status: 401,
error: "Authentication Failed."
} unless current_business
end
def current_business
account_number = request_params[:account_number].to_s
api_key = request_params[:api_key].to_s
if account_number and api_key
account = BusinessAccount.find_by(account_number: account_number)
if account && Business.find(account.business_id).business_api_key.token =~ /^(#{api_key})/
#current_business = account.business
else
false
end
end
end
end
How can i serve the same responses using web-sockets?
P.S: Never worked with sockets before
Thank you
ActionCable
I would second Dimitris's reference to ActionCable, as it's expected to become part of Rails 5 and should (hopefully) integrate with Rails quite well.
Since Dimitris suggested SSE, I would recommend against doing so.
SSE (Server Sent Events) use long polling and I would avoid this technology for many reasons which include the issue of SSE connection interruptions and extensibility (websockets allow you to add features that SSE won't support).
I am almost tempted to go into a rant about SSE implementation performance issues, but... even though websocket implementations should be more performant, many of them suffer from similar issues and the performance increase is often only in thanks to the websocket connection's longer lifetime...
Plezi
Plezi* is a real-time web application framework for Ruby. You can either use it on it's own (which is not relevant for you) or together with Rails.
With only minimal changes to your code, you should be able to use websockets to return results from your RESTful API. Plezi's Getting Started Guide has a section about unifying the backend's RESTful and Websocket API's. Implementing it in Rails should be similar.
Here's a bit of Demo code. You can put it in a file called plezi.rb and place it in your application's config/initializers folder...
Just make sure you're not using any specific Servers (thin, puma, etc'), allowing Plezi to override the server and use the Iodine server, and remember to add Plezi to your Gemfile.
class WebsocketDemo
# authenticate
def on_open
return close unless current_business
end
def on_message data
data = JSON.parse(data) rescue nil
return close unless data
case data['msg']
when /\Aget_transactions\z/i
# call the RESTful API method here, if it's accessible. OR:
transactions = #current_business.business_account.business_deposits.last(5)
write {
status: 200,
number: transactions.count,
# the next line has what I think is an design flaw, but I left it in
transactions: transactions.as_json(only: [:created_at, :amount, :status, :client_card_number, :client_phone_number])
# # Consider, instead, to avoid nesting JSON streams:
# transactions: transactions.select(:created_at, :amount, :status, :client_card_number, :client_phone_number)
}.to_json
end
end
# don't disclose inner methods to the router
protected
# better make the original method a class method, letting you reuse it.
def current_business
account_number = params[:account_number].to_s
api_key = params[:api_key].to_s
if account_number && api_key
account = BusinessAccount.find_by(account_number: account_number)
if account && Business.find(account.business_id).business_api_key.token =~ /^(#{api_key})/
return (#current_business = account.business)
end
false
end
end
end
Plezi.route '/(:api_key)/(:account_number)', WebsocketDemo
Now we have a route that looks something like: wss://my.server.com/app_key/account_number
This route can be used to send and receive data in JSON format.
To get the transaction list, the client side application can send:
JSON.stringify({msg: "get_transactions"})
This will result in data being send to the client's websocket.onmessage callback with the last five transactions.
Of course, this is just a short demo, but I think it's a reasonable proof of concept.
* I should point out that I'm biased, as I'm Plezi's author.
P.S.
I would consider moving the authentication into a websocket "authenticate" message, allowing the application key to be sent in a less conspicuous manner.
EDIT
These are answers to the questions in the comments.
Capistrano
I don't use Capistrano, so I'm not sure... but, I think it would work if you add the following line to your Capistrano tasks:
Iodine.protocol = false
This will prevent the server from auto-starting, so your Capistrano tasks flow without interruption.
For example, at the beginning of the config/deploy.rb you can add the line:
Iodine.protocol = false
# than the rest of the file, i.e.:
set :deploy_to, '/var/www/my_app_name'
#...
You should also edit your rakefile and add the same line at the beginning of the rakefile, so your rakefile includes the line:
Iodine.protocol = false
Let me know how this works. Like I said, I don't use Capistrano and I haven't tested it out.
Keeping Passenger using a second app
The Plezi documentation states that:
If you really feel attached to your thin, unicorn, puma or passanger server, you can still integrate Plezi with your existing application, but they won't be able to share the same process and you will need to utilize the Placebo API (a guide is coming soon).
But the guide isn't written yet...
There's some information in the GitHub Readme, but it will be removed after the guide is written.
Basically you include the Plezi application with the Redis URL inside your Rails application (remember to make sure to copy all the gems used in the gemfile). than you add this line:
Plezi.start_placebo
That should be it.
Plezi will ignore the Plezi.start_placebo command if there is no other server defined, so you can put the comment in a file shared with the Rails application as long as Plezi's gem file doesn't have a different server.
You can include some or all of the Rails application code inside the Plezi application. As long as Plezi (Iodine, actually) is the only server in the Plezi GEMFILE, it should work.
The applications will synchronize using Redis and you can use your Plezi code to broadcast websocket events inside your Rails application.
You may want to have a look at https://github.com/rails/actioncable which is the Rails way to deal with WebSockets, but currently in Alpha.
Judging from your code snippet, the client seems to only consume data from your backend. I'm skeptical whether you really need WebSockets. Ιf the client won't push data back to the server, Server Sent Events seem more appropriate.
See relevant walk-through and documentation.
I have a very simple number crunching Ruby function that I want to make available via a web API. The API is essentially a single endpoint, e.g. http://example.com/crunch/<number> and it returns JSON output.
I can obviously install Rails and implement this quickly. I require no more help from a 'framework' other than to handle HTTP for me. No ORM, MVC and other frills.
On the far end, I can write some Ruby code to listen on a port and accept GET request and parse HTTP headers etc. etc. I don't want to re-invent that wheel either.
What can I use to expose a minimal API to the web using something with the least footprint/dependencies. I read about Sinatra, Ramaze, etc., but I believe there can be a way to do something even simpler. Can I just hack some code on top of Rack to do what I am trying to do?
Or in other words, what will be the simplest Ruby equivalent of the following code in nodejs:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var ans = crunch(number);
res.end(ans);
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
You seem like you want to use Rack directly. "Rack from the Beginning" is a decent tutorial that should get you started.
It'll probably look something like this:
class CrunchApp
def self.crunch(crunchable)
# top-secret crunching
end
def self.call(env)
crunchy_stuff = input(env)
[200, {}, crunch(crunchy_stuff)]
end
private
def self.input(env)
request = Rack::Request.new(env)
request.params['my_input']
end
end
Rack::Server.start app: CrunchApp
But I must say, using that instead of something like Sinatra seems silly unless this is just a fun project to play with things. See their 'Hello World':
require 'sinatra'
get '/hi' do
"Hello World!"
end
Ruby-Grape is a good option for your use case. It has a minimal implementation over Rack that allow the creation of simple REST-API endpoints.
Cuba is another good option with a thin layer over Rack itself.sample post
If you are familiar with Rails you can use the Rails API gem which is very well documented with minor overhead. Remember also that Rails-API will be part of Rails 5.
Last, but not last you can implement it on Rack directly.
We have a very unique use case where we want a Rails controller to access a route within the Rails app using Net::HTTP. Can this be done? I'm currently receiving a timeout when attempting to do so. The current code works when the uri is a separate Rails app, but not when the uri belongs to the app itself. Here's the gist of the current controller action:
def export_data
uri = URI("http://localhost:3000")
#data = JSON.parse( Net::HTTP.get(uri) )
respond_to do |format|
...
end
end
Forget why we want to do this. Why doesn't this work? Is there a modification that can be made to get it to work? Thanks in advance!
It doesn't work because you are not using a multi-threaded server. Your request is coming in and blocking the server until it's complete. During that time, you're making a request to your localhost that isn't being handled.
Easy solution? Try puma. Other easy solution, spin up two rails instances, connect to the 2nd instance.