Writing general notes for API docs using swagger-docs - ruby-on-rails

I am using swagger to document my Rails REST API using swagger-docs. I am able to document every method but the problem is that I want to write general guidelines() for using API. I cannot find any method that allows me to do so. Any help will be appreciated.
Something as shown in the image below:

You just need to set the "Description" attribute to some appropriate text when you initially configure Swagger.
Have a look at the first example from https://github.com/richhollis/swagger-docs:
Swagger::Docs::Config.register_apis({
"1.0" => {
# the extension used for the API
:api_extension_type => :json,
# the output location where your .json files are written to
:api_file_path => "public/api/v1/",
# the URL base path to your API
:base_path => "http://api.somedomain.com",
# if you want to delete all .json files at each generation
:clean_directory => false,
# add custom attributes to api-docs
:attributes => {
:info => {
"title" => "Swagger Sample App",
"description" => "This is a sample description.",
"termsOfServiceUrl" => "http://helloreverb.com/terms/",
"contact" => "apiteam#wordnik.com",
"license" => "Apache 2.0",
"licenseUrl" => "http://www.apache.org/licenses/LICENSE-2.0.html"
}
}
}
})
The example app at petstore.swagger.io shows you the general output and layout you'll get.

Related

updating a column Parse Rest API

i am trying to update a Users information for ex. Phone, email etc.
i looked at this: https://parse.com/docs/rest/guide#users-updating-users
so i wrote this in my controller:
#response = HTTParty.put('https://api.parse.com/1/users/',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
I return #response in a view and get back this:
{"error"=>"requested resource was not found"}
I was thinking maybe its because im not passing the user's objectid in the url?
Well, now that you have played with creating HTTP requests to API manually, it's time to switch to some library/gem for interactions with Parse. Hopefully, people who built the library that you will find, already have dealt with many routine tasks (like formatting your JSON properly – the error you are investigating right now), and have good documentation for many cases.
I suggest parse-ruby-client.
Add gem 'parse-ruby-client', github: 'adelevie/parse-ruby-client' to Gemfile (it's better to use master version, not the current Rubygems version, because they are saying that there are some useful changes which are not yet pushed to Rubygems), then run bundle install as usual, and you are good to go.
Object saving is as easy as
game_score = client.object("GameScore")
game_score["score"] = 1337
game_score["playerName"] = "Sean Plott"
game_score["cheatMode"] = false
result = game_score.save
puts result
according to their documentation.
UPD. Answering original question. You can use a function to provide object id dynamically:
def update_user(object_id)
#response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token],
"Content-Type" => "application/json"},
:data => {"phoneNumber" => "9994432"})
end
My solution is force the variables to int and string
response = HTTParty.put("https://api.parse.com/1/users/#{object_id}",
:headers => {
"X-Parse-Application-Id" => ENV['PARSE_APP_ID'].to_s,
"X-Parse-REST-API-Key" => ENV['PARSE_API_KEY'].to_s,
"X-Parse-Session-Token" => token.to_s,
"Content-Type" => "application/json"},
:body => {"h_optimum" => optimum.to_i,
"h_moderate" => moderate.to_i,
"h_appalling" => appalling.to_i}
)

How to track API calls on my ruby on rails app using google analytics?

I created an API for external applications to log in or make specific web calls using OAuth. What I'm looking for is a way to track the number of times these API calls are being used.
Is there an option for me?
You could send the events with the measurement protocol.
require "net/http"
require "uri"
uri = URI.parse("http://www.google-analytics.com/collect")
Net::HTTP.post_form(uri, {"v" => "1",
"tid" => "UA-XXXX-1",
"cid" => "555",
"t" => "event",
"ec" => "API",
"ea" => "request",
"el" => "data/get",
"ev" => "5"})
I believe you can do this with Google Events:
https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide
There are various Ruby libraries for interacting with GA.

Upload compressed data to Google BigQuery using API

For the past couple of days i've been working to improve the logstash google_bigquery connector.
Currently i was able to add features such as error handling (bad lines), better connection management and couple of other stuff.
the last but most important feature that i'm been working on is uploading compressed data to BigQuery and well the documentation of the API is horrible.
for now i'm able to uploading CSV files directly to BQ using the Jobs.insert method
and i've noted that its clearly written that data can be uploaded compressed.
the only question left is there a way i can do so without using Google Cloud Storage, as the compressed option is there to reduce the network bandwidth and its cost, and adding another route (that cost money) such as GCS is pointless
the error code i'm getting is:
BQ: job failed, please enable debug and check full response (probably
the issue is an incompatible schema). NOT deleting local file.
{:job_id=>"job_OvWTWOXGv9yGnLKfrTfGfukLytM",
:filename=>"/Users/dave.e/Logstash/tmp/bq-logstash_daves-mpb.local_2014-08-26.part000.log.gz",
:job_status=>{"state"=>"DONE",
"errorResult"=>{"reason"=>"internalError", "location"=>"File: 0",
"message"=>"Unexpected. Please try again."},
"errors"=>[{"reason"=>"internalError", "location"=>"File: 0",
"message"=>"Unexpected. Please try again."}]}, :level=>:error}
I'll cut to the main case with the code and be grateful for your help
# Uploads a local file to the configured bucket.
def upload_object(filename)
#logger.debug("entering upload_object")
begin
#logger.debug("1")
require 'json'
#logger.debug("2")
table_id = #table_prefix + "_" + get_date_pattern(filename)
#logger.debug("3")
# BQ does not accept anything other than alphanumeric and _
# Ref: https://developers.google.com/bigquery/browser-tool-quickstart?hl=en
table_id = table_id.gsub(':','_').gsub('-', '_')
#logger.debug("table bane has been modified")
#logger.debug("BQ: upload object.",
:filename => filename,
:table_id => table_id)
media = Google::APIClient::UploadIO.new(filename, "application/octet-stream")
body = {
"configuration" => {
"load" => {
"sourceFormat" => "NEWLINE_DELIMITED_JSON",
"schema" => #json_schema,
"destinationTable" => {
"projectId" => #project_id,
"datasetId" => #dataset,
"tableId" => table_id
},
'createDisposition' => 'CREATE_IF_NEEDED',
'writeDisposition' => 'WRITE_APPEND',
'maxBadRecords' => 99
}
}
}
#logger.debug("Execution details: ",
:body_object => body,
:parameters => {
'uploadType' => 'multipart',
'projectId' => #project_id
},
:media => media)
datasetId = #project_id+":"+#dataset
verify_dataset = #client.execute(:api_method => #bq.datasets.get,
:parameters => {
'projectId' => #project_id,
'datasetId' => datasetId })
status = JSON.parse(verify_dataset.response.body)["id"]
if status != dataset
#logger.info("BQ: dataset doesnt exist, creating it instead")
create_dataset = #client.execute(:api_method => #bq.datasets.insert,
:parameters => { 'projectId' => #project_id },
:body_object => { 'id' => datasetId })
sleep 10
end
insert_result = #client.execute(:api_method => #bq.jobs.insert,
:body_object => body,
:parameters => {
'uploadType' => 'multipart',
'projectId' => #project_id
},
:media => media)
job_id = JSON.parse(insert_result.response.body)["jobReference"]["jobId"]
#logger.debug("BQ: multipart insert",
:job_id => job_id)
return job_id
rescue => e
#logger.error("BQ: failed to upload file", :exception => e)
# TODO(rdc): limit retries?
sleep 1
if File.exist?(filename)
retry
end
end
end
The error on our side was that the file did not appear to be a valid gzip file, and the gzip library was unable to open it.
This could be a problem with how the file was generated or with how it was uploaded. If you still have access to the file, can you verify that you're able to unzip it?

How to use LinkedIn's Share API with the Rails Gem

I'm running Rails 3, with the LinkedIn API gem: here
I've been unable to get the Share API working as described here
This works fine:
response = client.add_share(:comment => 'new share API')
This Fails with:
response = client.add_share(:comment => 'new share API', :title => 'Linkedin Share API', :url => 'http://developer.linkedin.com/docs/DOC-1212', :image_url => 'http://images.bizjournals.com/travel/cityscapes/thumbs/sm_sanfrancisco.jpg')
Error:
LinkedIn::Errors::GeneralError ((400): Invalid xml {Expected elements 'post-network-update#http://api.linkedin.com/v1 id#http://api.linkedin.com/v1 visibility#http://api.linkedin.com/v1 comment#http://api.linkedin.com/v1 attribution#http://api.linkedin.com/v1 content#http://api.linkedin.com/v1 private-message#http://api.linkedin.com/v1 share-target-reach#http://api.linkedin.com/v1' instead of 'image-url#http://api.linkedin.com/v1' here in element share#http://api.linkedin.com/v1, Expected elements 'post-network-update#http://api.linkedin.com/v1 id#http://api.linkedin.com/v1 attribution#http://api.linkedin.com/v1 content#http://api.linkedin.com/v1 private-message#http://api.linkedin.com/v1 share-target-reach#http://api.linkedin.com/v1' instead of 'url#http://api.linkedin.com/v1' here in element share#http://api.linkedin.com/v1}):
Any ideas? Thanks
You're doing it wrong. This is the XML in of sample request in https://developer.linkedin.com/documents/share-api#toggleview:id=xml
<share>
<comment>Check out the LinkedIn Share API!</comment>
<content>
<title>LinkedIn Developers Documentation On Using the Share API</title>
<description>Leverage the Share API to maximize engagement on user-generated content on LinkedIn</description>
<submitted-url>https://developer.linkedin.com/documents/share-api</submitted-url>
<submitted-image-url>http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png</submitted-image-url>
</content>
<visibility>
<code>anyone</code>
</visibility>
</share>
So the request should look something like this based in the sample request:
response = client.add_share(:comment => 'Sample Job',
:content => { :title => 'LinkedIn Developers Documentation On Using the Share API', :description => 'Leverage the Share API to maximize engagement on user-generated content on LinkedIn', :'submitted-url' => 'https://developer.linkedin.com/documents/share-api', :'submitted-image-url' => 'http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png' } )

Ruby add_item for eBay

I am attempting to write a ruby on rails app that posts an item to eBay. Cody Fauser/Garry Tan have a gem called ebayApi which is built on top of the ebay gem. When I attempt to post an item, I am getting an error back from ebay that says the condition ID is required for this category. I have found a category that does not require the condition, and I can post to that category. Searching through the eBay API documentation, I have found a tag conditionID under the "item" class. However, in the documentation for ebayAPI, there is no such tag. Looking back at the ebay API documentation, there is an older way to specify condition, using lookup_attributes. I have noted that the return xml is coming in API version 745, and Garry Gan's updated of the ruby interface is running version 609. I have tried using the lookup, and seem to get the same error (condition required). I am using the following code to specify the item:
#ebay = Ebay::Api.new :auth_token => #seller.ebay_token
item = Ebay::Types::Item.new( :primary_category => Ebay::Types::Category.new(:category_id => #ebayTemplate.categoryID),
:title => #ebayTemplate.name,
:description => #ebayTemplate.description,
:location => #ebayTemplate.location,
:start_price => Money.new((#ebayTemplate.startPrice*100).to_d, #ebayTemplate.currency),
:quantity => 1,
:listing_duration => #ebayTemplate.listingDuration,
:country => #ebayTemplate.country,
:currency => #ebayTemplate.currency,
:payment_methods => ['VisaMC', 'PayPal'],
:paypal_email_address => '********#gmail.com',
:dispatch_time_max => 3,
:lookup_attributes => [Ebay::Types::LookupAttribute.new( :name => "Condition", :value => "New")],
# :attribute_sets => [
# Ebay::Types::AttributeSet.new(
# :attribute_set_id => 2919,
# :attributes => [
# Ebay::Types::Attribute.new(
# :attribute_id => 10244,
# :values => [ Ebay::Types::Val.new(:value_id => 10425) ]
# )
# ]
# )
# ],
:shipping_details => Ebay::Types::ShippingDetails.new(
:shipping_service_options => [
# ShippingServiceOptions.new(
# :shipping_service_priority => 2, # Display priority in the listing
# :shipping_service => 'UPSNextDay',
# :shipping_service_cost => Money.new(1000, 'USD'),
# :shipping_surcharge => Money.new(299, 'USD')
# ),
Ebay::Types::ShippingServiceOptions.new(
:shipping_service_priority => 1, # Display priority in the listing
:shipping_service => #ebayTemplate.shipSvc,
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_surcharge => Money.new((#ebayTemplate.shipSurcharge*100).to_d, #ebayTemplate.currency)
)
],
:international_shipping_service_options => [
Ebay::Types::InternationalShippingServiceOptions.new(
:shipping_service => 'USPSPriorityMailInternational',
:shipping_service_cost => Money.new((#ebayTemplate.shipSvcCost*100).to_d, #ebayTemplate.currency),
:shipping_service_priority => 2,
:ship_to_location => #ebayTemplate.shipToLocation
)
]
),
:return_policy => Ebay::Types::ReturnPolicy.new (
:description => 'this product for suckers only!',
:returns_accepted_option => 'ReturnsAccepted'
)
#:condition_id => 1000
)
#response = #ebay.add_item(:item => item)
As you can see, it is just a mutation of the example given by Cody Fauser. The condition_id at the bottom will bring up an error as there is no such attribute. It seems to me there is no facility for this in the gem since the requirement came into existence after the gem was created. I have not been able to find any other gems to connect with ebay. I have also noticed, there are very little complaints about this even though people are still downloading the gem (10 people downloaded it today). I think there are quite a number of people writing for ebay. Is there a key word I am missing to specify the condition? A work around that people have been using? Another gem I have missed?
There is an existing item_conditions_codes.rb in the gem's type directory and only has two values New and Used. Guess you could add more values in there. However still needs mapping to ID's per the updating (and changed from Attributes) method
You have to modify in the gem library in .. ruby/1.8/gems/ebayapi-0.12.0/lib/ebay/types/item.rb
and add the following new lines
# added to allow ConditionID to be pushed into XML
numeric_node :condition_id, 'ConditionID', :optional => true
then in your ruby ebay code use the following convention
:condition_id => 1500,
At least that seems to work for me right now.

Resources