Skip to content

Instantly share code, notes, and snippets.

@katogiso
Last active August 16, 2016 13:38
Show Gist options
  • Save katogiso/c0eead67b24c0c94927e50bb56c5a27d to your computer and use it in GitHub Desktop.
Save katogiso/c0eead67b24c0c94927e50bb56c5a27d to your computer and use it in GitHub Desktop.
Sample script of qiita web api access
#!/usr/local/bin/ruby -W0
require 'net/http'
require 'uri'
require 'json'
require 'pp'
class QiitaGet
attr_accessor :base_url, :debug
def initialize
@base_url = "http://qiita.com/api/v2"
@debug = false
end
def get_schema( options={} )
if options[:pretty]
return get_pretty( "schema", {locale: "en"} )
else
return get("schema", {locale: "en"} )
end
end
def get_pretty( component, options={} )
return JSON.pretty_generate( JSON.parse( get(component, options ) ) )
end
def get( component, options={} )
uri = uri( @base_url + "/#{component}" + get_options(options) )
return access( http( uri.host ), request_get( uri ) ).body
end
def uri( address )
return URI.parse( address )
end
def get_options( options )
if options.is_a? Hash then
tmp = []
options.each_pair { |k,v|
tmp << "#{k.to_s}=#{v}"
}
return "?#{tmp.join("&")}"
end
return ""
end
def http( host )
http = Net::HTTP.new( host )
http.set_debug_output $stderr if @debug
return http
end
def request_get( uri )
return Net::HTTP::Get.new(uri.request_uri)
end
def access( http, req )
begin
resp = http.request(req)
case resp
when Net::HTTPSuccess
return resp
else
pp resp
print_request( req )
exit
end
rescue => e
pp e
print_request( req )
end
end
def print_request( req )
pp "PATH : #{req.path}"
pp "BDOY : #{req.body}"
end
end
#--------------------
# initialization
#--------------------
#qiita = QiitaGet.new
#-----------------------------------------------
# write the qiita schema in a file as qiita.json
#-----------------------------------------------
#File.open( "qiita.json", "w" ) { |f|
# f.write qiita.get_schema({pretty: true })
#}
#-----------------------------------------------
# get the tags data which are from top 1 to 100
#-----------------------------------------------
#printf( "%s\n", qiita.get_pretty( "tags", {page: 1, per_page: 100, sort: "count" } ) )
#-----------------------------------------------
# Error access ( hoge isn't a qiita api )
#-----------------------------------------------
#printf( "%s\n", qiita.get_pretty( "hoge", {page: 1, per_page: 100, sort: "count" } ) ) #!/usr/local/bin/ruby -W0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment