How to response with JSON format using Ruby Rack middleware - ruby-on-rails

How to reply a simple ruby rack server with JSON object , lets assume mt server is something like :
app = Proc.new do |env|
[200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end
Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)
and lets assume instead of some body text I want a JSON object with something like :
{
"root": [
{
"function": null
}
]
}
Thanks

Include the "json" gem in your project, and then call #to_json on the Hash:
app = Proc.new do |env|
[200, { 'Content-Type' => 'application/json' }, [ { :x => 42 }.to_json ]]
end
Note that nil is translated to null in the JSON, if you need null.

Related

Error SENDING POST in rails and HTTPPARTY semantic error my request

this is my error when I lanunched my method {"errors"=>{"users"=>["Missing data for required field."]}, "msg"=>"The request was well-formed but was unable to be followed due to semantic errors."}
class BookingNotifier
include HTTParty
def initialize(booking_id)
#booking = Booking.find booking_id
#venue = #booking.event.service.venue
#body = { "users" => [] }
#headers = {
"Accept" => "application/json",
"Authorization" => "ENV_KEY",
"Content-Type" => "application/json"
}
end
def send_venue_notification
venues_objects = []
if #venue.notifications_enabled
venues_objects << { "cellphone" => #booking.event.service.venue.phone,
"country_code" => "+57",
"user_session_keys" => [{ "key" => "Nombre", "value" => #booking.profile.name },
{ "key" => "Centro", "value" => #booking.event.service.venue.name },
{ "key" => "Cupos", "value" => #booking.quantity },
{ "key" => "Horarios", "value" => #booking.time.strftime("%I:%M %p el %d/%m/%Y") }] }.to_json
#body["users"] = venues_objects
make_request_venue
end
end
def make_request_venue
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #header, body: #body)
end
The problem is caused by to_json called in the wrong place.
The whole request body should be sent as a JSON. In your code, you call to_json for a hash that is later pushed into #body["users"] array.
Please remove to_json from send_venue_notification and call it for the #body when sending the request:
HTTParty.post("http://api.treble.ai/api/poll/49/deploy", headers: #headers, body: #body.to_json)

How can I increase timeout for HTTParty post method in rails?

I have a method in rails to send post requests to a third party API. The code looks similar to the following:
data = HTTParty.post("url",
:headers=> {'Content-Type' => 'application/json'},
:body=> { update => true, first_name => "name" }
)
With this, after exactly one minute, the process is terminated with the following error.
<Net::HTTPGatewayTimeOut 504 GATEWAY_TIMEOUT readbody=true>
Set the default by:
module HTTParty
default_timeout your_preferred_timeout
end
or set it individually by:
data = HTTParty.post("url",
headers: {"Content-Type" => "application/json"},
body: {update => true, first_name => "name"},
timeout: your_preferred_timeout
)
you can try
data = HTTParty.post("url",
headers: {"Content-Type" => "application/json"},
body: {update => true, first_name => "name"},
open_timeout: 0.5,
write_timeout:1,
read_timeout:3
)
also you can reference
https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#attribute-i-write_timeout

Making POST Request to GCM server for notification key fails from Rails Controller

I have try to making a POST request to google cloud messaging server as follow from my Rails controller using httparty gem
#response = HTTParty.post("https://android.googleapis.com/gcm/notification",
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
)
#json = JSON.parse(#response.body)
render :json => #json
The response I got it not a notification key. It is
{
"error": "BadJsonFormat"
}
What's wrong in my code?
My Rails controller request format is
POST /api/fcm HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: cfd40d1e-81f4-5402-a3cd-f6749f868291
{
"user_id" : "42"
}
I guess httparty gem expects json data
So replace
:body => {
:text => '{
"operation" : "remove",
"notification_key_name": "43",
"registration_ids": [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}'.to_json
},
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
with
:body => {
:text => {
:operation => "remove",
:notification_key_name => "43",
:registration_ids => [
"dmfbvTrqeSo:APA91bFmk_zTryZi-2-BrjZK-zxN3nmQxl8tIUJriTl7EwRZsnHq3UAMNQ2O_mxLVes7WLHnW6INx21UdKwm64ReUpd5bKTE0uinrPau2WVrAUkfUyRKxlIGLD2xLKbNiSGjAeNIDAhe"
]
}
}.to_json,
:headers => {
'Content-Type' => 'application/json',
'Authorization' => 'key=AIzaSyDQiBiYk433JhWKWFZZGAU3c08tWjCzU5o',
'project_id' => '857642310184'
}
Try removing to to_json on post. This would work if you were calling it for a Hash, but what it's doing here is double-escaping your string (which is already valid JSON).
If you want to send a minimal JSON request (i.e. without the extra spaces and carriage returns), you can also use
JSON.parse('{
"operation" : "remove",
...
}').to_json

Change in value of JSON data at receiver end

I am sending post request to facebook graph api using Httparty gem.
My code is
message_data ={
"recipient" => {
"id" => recipient_id
},
"message" => {
"attachment" => {
"type" => "template",
"payload" => {
"template_type" => "generic",
"elements" => [
{
"title" => "Titilize",
"subtitle" => "Subtitle"
}
]
}
}
}
}
options ={
"query": {access_token: #page_access_token},
"body": message_data
}
HTTParty.post("https://graph.facebook.com/v2.6/me/messages",options)
Httparty will send data by converting hash into json.
Problem is at the end point data is receiving differently not as i expected (maybe httparty is not parsing properly).
Someone help me with this.
Thanks
Seems like you have to set the Content-Type header. There may be issues with the Hash syntax depending on your version of Ruby, so check out this open ticket: https://github.com/jnunemaker/httparty/issues/472
str = "{\"recipient\":{\"id\":\"1291831200828847\"},\"message\":{\"attachment\":{\"typ‌​e\":\"template\",\"payload\":{\"template_type\":\"generic\",\"elements\":[{\"titl‌​e\":\"Titilize\",\"subtitle\":\"Subtitle\"}]}}}}"
options {
:headers => {"Content-Type" => "application/json"},
:query => {access_token: #page_access_token},
:body => str
}
HTTParty.post("https://graph.facebook.com/v2.6/me/messages", options)

NoMethodError in ChatRoomMessagesController

I am doing an AJAX call as the following and trying to parse the JSON recieved in Rails as bellow
AJAX
local_data = {chat:{room_name: chatRoomName ,message: message}}
$.ajax({
type: "POST",
url: '/chat_notify',
dataType: 'json',
async : false,
data: local_data,
success: function(data) {
alert("working");
}
});
Ruby
def notify
#data = ActiveSupport::JSON.decode(params)
#chat_room = ChatRoom.where(:slug => data.chat.name)
#puts #chat_room
puts params.chat
RestClient.post 'https://api.pushbots.com/push/all',
{ "platform" => [0,1] ,
"msg" => "Harsha sent a message." ,
"sound" => "pulse",
"alias" => "harsha#mink7.com",
"badge" => "1",
"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json,
headers = { "x-pushbots-appid" => APP_CONFIG['PUSHBOTS_APPID'],
"x-pushbots-secret" => APP_CONFIG['PUSHBOTS_SECRET'],
:content_type => :json }
render json: true
end
Error
You need to paste your error trace
But I think the problem might in below
puts params.chat
there is no chat method for params , just remove it
or
…………"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json
you need require 'json' to make .to_json available

Resources