Sending a JSON to an API Url through Ruby on Rails - ruby

I have a json object that I'm sending to Google's QXP Express API. The idea is that I send the object with the relevant travel information. In terminal, through curl, it's very easy to send it. I just use the following curl command. Doc.json is the file name of the json.
curl -d #doc.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0
This is my code to do it in Ruby.
uri = URI('https://www.googleapis.com/qpxExpress/v1/trips/search?key=MYAPIKEY')
req = Net::HTTP::Post.new uri.path
req.body = {
"request" => {
"passengers" => {
"adultCount" => 1
},
"slice" => [
{
"origin" => "BOS",
"destination" => "LAX",
"date" => "2014-10-14"
},
{
"origin" => "LAX",
"destination" => "BOS",
"date" => "2014-11-14"
}
]
}
}.to_json
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.ssl_version = :SSLv3
http.request req
end
puts res.body
However I'm getting back the following error.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "This API does not support parsing form-encoded input."
}
],
"code": 400,
"message": "This API does not support parsing form-encoded input."
}
}
I just need to send it with the json file, but nothing I can find online covers sending json's to APIs. Please help, I'm very stuck.

It is always matter of taste what tools you prefer, but as for me i am currently using the rest-client gem for accessing REST APIs. With this library your example could be written like this:
require 'json'
require 'rest-client'
response = RestClient.post 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=AIzaSyAaLHEBBLCI4aHLNu2jHiiAQGDbCunBQX0',
{
request: {
passengers: {
adultCount: 1
},
slice: [
{
origin: "BOS",
destination: "LAX",
date: "2014-10-14"
},
{
origin: "LAX",
destination: "BOS",
date: "2014-11-14"
}
]
}
}.to_json,
:content_type => :json
puts response.body
But if you want a Net::HTTP only solution, this might not be a suitable answer for you.

Related

Send API get request from AWS Lambda in ruby

I was trying to send API request to my rails server from AWS Lambda function.
I was using httparty gem to send request.
I have tried with below code
require "httparty"
class PostManager
include HTTParty
def initialize
end
def create_post(job_id)
puts "----------------- Inside post manager ------------------"
puts "----------------- #{ENV["BASE_URI"]} ------------------"
puts "#{ENV['BASE_URI']}/call_response?job_id=#{job_id}"
response = HTTParty.get("#{ENV['BASE_URI']}")
puts "******************HTTP Response -: #{response}******************"
response
end
end
I am triggering this code from aws lambda main handler like below.
post_manager = PostManager.new
response = post_manager.create_post(job_id)
But lambda function gets timeout. Request not reaching to rails server at all.
Please guide me if i am missing something. Other alternatice to send post request to external server from aws lambda function is also invited.
Since http party is a http client, I recommend read the documentation, start experimenting with pry and a site like http://httpbin.org
So went will have all the thinks. reading your code I'm not sure of what you want to achieve, but I think that you want to connect to some en point that is on:
The domain inside this shell variable => #{ENV['BASE_URI']}
the path of the http method => call_response
and some path parameters like => job_id=#{job_id}
You allways say that this is a post but you are doing a get => HTTParty.get
So let's start with some object like the one showed in the documentation in order to attack to this method with curl will be something like this:
❯ curl -X GET "http://httpbin.org/get?job_id=4" -H "accept: application/json" ~/learn/ruby/stackoverflow
{
"args": {
"job_id": "4"
},
"headers": {
"Accept": "application/json",
"Host": "httpbin.org",
"User-Agent": "curl/7.64.1",
"X-Amzn-Trace-Id": "Root=1-613b73ef-2d00166a2ae40e704b448352"
},
"origin": "83.53.251.55",
"url": "http://httpbin.org/get?job_id=4"
}
Then for an http client object
add this to afile called httpbin_client.rb :
require 'httparty'
class HTTPbinClient
include HTTParty
base_uri ENV['BASE_URI']
def initialize
end
def ask_for_job_id(job_id)
self.class.get('/get', {query: {job_id: job_id}})
end
end
http_bin = HTTPbinClient.new
puts http_bin.ask_for_job_id(28)
call like this:
❯ BASE_URI=httpbin.org ruby httpbin_client.rb ~/learn/ruby/stackoverflow
{
"args": {
"job_id": "28"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
"Host": "httpbin.org",
"User-Agent": "Ruby",
"X-Amzn-Trace-Id": "Root=1-613b776d-47036b9b29bb1ae34b4a0e50"
},
"origin": "83.53.251.55",
"url": "http://httpbin.org/get?job_id=28"
}

laravel JSON validation rule

I'm trying to use the 'json' validation rule in a form request, but I constantly get an invalid JSON message. I havent found any examples on how to use this rule, so I'm a bit lost here.
My rules function looks like this:
public function rules()
{
return [
'userData'=>'json',
'securityChanges'=>'json'
]
}
And my JSON looks like this:
{
"userData":{
"domicilio":"nowere",
"empresa":"Burgerking",
"name":"zorgito",
"surname": "perez",
"cuit":"10101010"
},
"securityChanges":{
"email": "flasheadas#lolo.com",
"password": "777777777777",
"passwordConfirmation":"777777777777"
}
}
My headers are properly set:
Accept: application/json
Content-Type: application/json
It should work, but I get:
"The user data must be a valid JSON string."
Any idea what's wrong here?
EDIT:
as requested n one of the answers, I'm putting the output of a dd($this->all()); in my form request class
array:2 [
"userData" => array:5 [
"domicilio" => "nowere"
"empresa" => "Burgerking"
"name" => "zorgito"
"surname" => "perez"
"cuit" => "10101010"
]
"securityChanges" => array:3 [
"email" => "flasheaasddas#lolo.com"
"password" => "777777777777"
"passwordConfirmation" => "777777777777"
]
]
The whole HTTP request is:
PATCH /api/users/me HTTP/1.1
Host: DOMAIN REMOVED
Authorization: Bearer (TOKEN REMOVED.)
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 73516b63-8556-4c21-9050-7a4fa3a83cb1
{
"userData":{
"domicilio":"nowere",
"empresa":"Burgerking",
"name":"zorgito",
"surname": "perez",
"cuit":"10101010"
},
"securityChanges":{
"email": "flasheaasddas#lolo.com",
"password": "777777777777",
"passwordConfirmation":"777777777777"
}
}
Nothing clear here, please make dd($request->all()) or dd($this->all()) (if you are in request class directly) and make sure you have that fields, and then make sure that fields are valid json strings. You can check it here https://jsonlint.com/

Logstash http_poller post giving Name may not be found error

Im trying to use the http_poller to fetch the data from ElasticSearch and write them into another ES. While doing this, ES query need to done as a POST request.
In the examples provided, I could not find the parameters that shoukd be used to post the body and it referred to the manticore client from ruby. Based n that, I have used the params parameter to post the body.
The http_poller component looks like this
input {
http_poller {
urls => {
some_other_service => {
method => "POST"
url => "http://localhost:9200/index-2016-03-26/_search"
params => '"query": { "filtered": { "filter": { "bool": { "must": [ { "term": { "SERVERNAME": "SERVER1" }}, {"range": { "eventtime": { "gte": "26/Mar/2016:13:00:00" }}} ]}}} }"'
}
}
# Maximum amount of time to wait for a request to complete
request_timeout => 300
# How far apart requests should be
interval => 300
# Decode the results as JSON
codec => "json"
# Store metadata about the request in this key
metadata_target => "http_poller_metadata"
}
}
output {
stdout {
codec => json
}
}
When I execute this, the Logstash gives an error,
Error: Name may not be null {:level=>:error}
Any help is appreciated.
The guess that I have is that the params need to be really key value pairs but then the question is as to how to post a query using logstash.
I referred to this link to get the available options for the HTTP Client
https://github.com/cheald/manticore/blob/master/lib/manticore/client.rb
Since I got the answer when I tried different options, thought I would share the solution as well.
Replace params with body in the above payload.
The correct payload to do a post using HTTP Poller is
input {
http_poller {
urls => {
some_other_service => {
method => "POST"
url => "http://localhost:9200/index-2016-03-26/_search"
body=> '"query": { "filtered": { "filter": { "bool": { "must": [ { "term": { "SERVERNAME": "SERVER1" }}, {"range": { "eventtime": { "gte": "26/Mar/2016:13:00:00" }}} ]}}} }"'
}
}
# Maximum amount of time to wait for a request to complete
request_timeout => 300
# How far apart requests should be
interval => 300
# Decode the results as JSON
codec => "json"
# Store metadata about the request in this key
metadata_target => "http_poller_metadata"
}
}
output {
stdout {
codec => json
}
}

How do I print out a response from an API call Ruby

I'm looking to print out the response from an API call with Kickbox's api.
This is what I have
require "kickbox"
client = Kickbox::Client.new('XXXXXXXXXXXXXXXXXXXXXXXXXXXX')
kickbox = client.kickbox()
response = kickbox.verify("test#example.com")
puts response
I'm not getting any response when trying to run the file in my terminal.
try response.body
{
"result" =>"unknown",
"reason" =>"no_connect",
"role" =>true,
"free" =>false,
"disposable" =>false,
"accept_all" =>false,
"did_you_mean" =>nil,
"sendex" =>0.35,
"email" =>"test#example.com",
"user" =>"test",
"domain" =>"example.com",
"success" =>true,
"message" =>nil
}
You can also get the response time and balance from headers from response.headers
{
"content-type" =>"application/json",
"x-kickbox-balance" =>"99",
"x-kickbox-response-time"=>"17"
}

Use Github API with rest client to create a file

I'm trying to use the Github API to create a file in a repo.
This CURL command does exactly what I want to do:
curl -X PUT -H 'Authorization: token <TOKEN>' -d '{"path": "test.txt", "message": "Test Commit", "committer": {"name": "Kevin Clark", "email": "kevin#kevinclark.ca"}, "content": "bXkgbmV3IGZpbGUgY29udGVudHM="}' https://api.github.com/repos/vernalkick/kevinclark/contents/test.txt
I need to do the same request but using rest_client in ruby, but this returns a 404:
require 'rest_client'
params = {
:path => "test.txt",
:message => "Test Commit",
:committer => {
:name => "Kevin Clark",
:email => "kevin#kevinclark.ca"
},
:content => "bXkgbmV3IGZpbGUgY29udGVudHM=",
:access_token => <TOKEN>
}
RestClient.put "https://api.github.com/repos/vernalkick/kevinclark/contents/test.txt", :params => params
Github's documentation: https://developer.github.com/v3/repos/contents/
So I finally found the solution to my problem!
I needed to create a json string instead of just passing the hash.
RestClient.put "https://api.github.com/repos/vernalkick/kevinclark/contents/test.txt", :params => JSON.generate(params)

Resources