Use Github API with rest client to create a file - ruby

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)

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"
}

How can I get the logo for an "Item" from the Plaid api?

I looked over the API documentation and I didn't see anything about how to get logos, but plaid clearly has them as they appear in the link app. Is there any way that I can also get access to those logo as part of the API or through another mechanism using an "Item" id?
While not documented at the time of this writing, it apparently can be done by adding an options parameter to a institution request with the value of {"include_display_data": true}. With the node API using the getInstitutionById method and Vangaurd it looks like this.
client.getInstitutionById('ins_108768', {include_display_data: true} (err, result) => {
// Handle err
const logo = result.institution.logo;
});
The value of logo will either be null or a base64 encoded string containing the binary data of the logo.
The current version of a plaid ruby gem(6.1.0) doesn't retrieve a logo but you can extend a plaid library and use include_display_data parameter to get a logo.
module Plaid
class Institutions < BaseProduct
def get_by_id_with_logo(institution_id)
post_with_public_key 'institutions/get_by_id',
SingleInstitutionResponse,
institution_id: institution_id,
options: { include_display_data: true }
end
end
end
Usage:
ins = client.institutions.get_by_id_with_logo(YOUR_INSTITUTION_ID)
puts ins.institution[:logo]
To get a list of all institutions from Plaid API one needs to hit /institutions/get with a POST request. To get logos and other institution attributes such as home page URL and brand color one needs to add options attribute in the body of the request with a key=>value pair of "include_optional_metadata" => true. The count parameter indicates the number of institutions you want returned (perPage) while offset is the number of institutions to skip.
curl -X POST \
https://sandbox.plaid.com/sandbox/institutions/get \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"client_id": "clientIdFromPlaidDashboard",
"secret": "secretFromPlaidDashboard",
"count": 500,
"offset": 0,
"options" => [
"include_optional_metadata" => true
]
}'
Expected response from Plaid doc:
http code 200
{
"institutions": [
{
"country_codes": ["US"],
"credentials": [{
"label": "User ID",
"name": "username",
"type": "text"
}, {
"label": "Password",
"name": "password",
"type": "password"
}],
"has_mfa": true,
"institution_id": "ins_109508",
"mfa": [
"code",
"list",
"questions",
"selections"
],
"name": "First Platypus Bank",
// the following are included when
// options.include_optional_metadata is true
"primary_color": "#1f1f1f",
"url": "https://plaid.com",
"logo": null,
]
}
],
"request_id": "m8MDnv9okwxFNBV",
"total": 1
}

RethinkDB subquery sample error

Sample on http://www.rethinkdb.com/docs/table-joins/, titled "Using subqueries" does not work as expected. Apart from the typo on the word lambda can you suggest the fix ?
The example posted in http://www.rethinkdb.com/docs/table-joins/ is a Python example. If you want to try out the example in Ruby, try the entering the following query into irb:
r.table("companies").get(id).merge{ |company| {
:employees => r.table('employees')
.get_all(company['id'], :index => 'company_id')
.coerce_to('array') }
}.run(Conn)
The result of that query should look something like this:
irb(main):254:0> r.table("companies").get(id).merge{ |company| {
irb(main):255:2* :employees => r.table('employees')
irb(main):256:2> .get_all(company['id'], :index => 'company_id')
irb(main):257:2> .coerce_to('array') }
irb(main):258:1> }.run(Conn)
=> {"company"=>"Starfleet", "company_id"=>"064058b6-cea9-4117-b92d-c911027a725a", "employees"=>[], "id"=>"064058b6-cea9-4117-b92d-c911027a725a", "name"=>"Jean-Luc Picard", "rank"=>"captain", "type"=>"paramilitary"}
Make sure that all the appropriate tables and indexes have been created before you run the query:
// Create the tables
r.table_create("companies").run(Conn)
r.table_create("employees").run(Conn)
// Create the index
r.table("employees").index_create("company_id").run(Conn)
// Insert a document
r.table("companies").insert({
"id": "064058b6-cea9-4117-b92d-c911027a725a",
"name": "Jean-Luc Picard",
"company_id": "064058b6-cea9-4117-b92d-c911027a725a",
"rank": "captain",
"company": "Starfleet",
"type": "paramilitary"
}).run(Conn)

Sending a JSON to an API Url through Ruby on Rails

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.

from curl -d to HTTParty get response

I need to convert from curl -d "params" "url"
To HTTParty.get request
so here's my curl:
curl -d 'email=myadmin#mycompany.com.au&password=mypassword' 'http://localhost:8080/locomotive/api/tokens.json'
So what is equivalent in httparty?
The answer is:
HTTParty.post("#{my_host}/locomotive/api/tokens.json", body: {:email => "myadmin#mycompany.com.au", :password => "mypassword"})

Resources