Breaking

Post Top Ad

Your Ad Spot

martes, 10 de diciembre de 2019

API de desarrollo con Ruby

Quiero compartir con ustedes algunos códigos recortados que administran las API DEV. https://docs.dev.to/ ). Cada fragmento utiliza la gema rest-client , un simple cliente HTTP y REST para Ruby. En el futuro serán recogidos en una joya :).

Artículos

Los artículos son todas las publicaciones que los usuarios crean en DEV

Artículos publicados

Este punto final permite al cliente recuperar una lista de artículos.
Los "artículos" son todas las publicaciones que los usuarios crean en DEV que generalmente aparecen en el feed. Pueden ser una publicación de blog, una pregunta de discusión, un hilo de ayuda, etc., pero se conoce como artículo dentro del código.
Por defecto, devolverá los artículos publicados y destacados ordenados por popularidad descendente.
Cada página contendrá 30 artículos.
Las respuestas, de acuerdo con la combinación de parámetros, se almacenan en caché durante 24 horas.
require 'rest-client'
require 'json'

def articles(params: {})
  response = RestClient.get("https://dev.to/api/articles", { params: params })
  articles = JSON.parse(response.body)

  articles
rescue RestClient::ExceptionWithResponse => err
  err.response
  []
end
articles(params: { username: 'daviducolo' })

=> [{"type_of"=>"article",
  "id"=>212407,
  "title"=>"RubyGems Telegram Bot",
  "description"=>"Bot wrapper for the RubyGems.org API",
  "cover_image"=>nil,
  "readable_publish_date"=>"Nov 28",
  "social_image"=>"https://dev.to/social_previews/article/212407.png",
  "tag_list"=>["webdev", "rails", "ruby", "showdev"],
  "tags"=>"webdev, rails, ruby, showdev",
  "slug"=>"rubygems-telegram-bot-4bo6",
  "path"=>"/daviducolo/rubygems-telegram-bot-4bo6",
  "url"=>"https://dev.to/daviducolo/rubygems-telegram-bot-4bo6",
  "canonical_url"=>"https://dev.to/daviducolo/rubygems-telegram-bot-4bo6",
  "comments_count"=>0,
  "positive_reactions_count"=>5,
  "collection_id"=>nil,
  "created_at"=>"2019-11-28T14:43:27Z",
  "edited_at"=>"2019-12-10T08:47:57Z",
  "crossposted_at"=>nil,
  "published_at"=>"2019-11-28T14:43:27Z",
  "last_comment_at"=>"2019-11-28T14:43:27Z",
  "published_timestamp"=>"2019-11-28T14:43:27Z",
...
}]

Un artículo publicado

Este punto final permite al cliente recuperar un único artículo publicado dada su identificación.
Las respuestas se almacenan en caché durante 5 minutos.
require 'rest-client'
require 'json'

def article(id:)
  response = RestClient.get("https://dev.to/api/articles/#{id}")
  article = JSON.parse(response.body)

  article
rescue RestClient::ExceptionWithResponse => err
  puts err.response
  nil
end  
article(id: 214552)

=> {"type_of"=>"article",
 "id"=>212407,
 "title"=>"RubyGems Telegram Bot",
 "description"=>"Bot wrapper for the RubyGems.org API",
 "cover_image"=>nil,
 "readable_publish_date"=>"Nov 28",
 "social_image"=>"https://dev.to/social_previews/article/212407.png",
 "tag_list"=>"webdev, rails, ruby, showdev",
 "tags"=>["webdev", "rails", "ruby", "showdev"],
 "slug"=>"rubygems-telegram-bot-4bo6",
 "path"=>"/daviducolo/rubygems-telegram-bot-4bo6",
 "url"=>"https://dev.to/daviducolo/rubygems-telegram-bot-4bo6",
 "canonical_url"=>"https://dev.to/daviducolo/rubygems-telegram-bot-4bo6",
 "comments_count"=>0,
 "positive_reactions_count"=>5,
 "collection_id"=>nil,
 "created_at"=>"2019-11-28T14:43:27Z",
 "edited_at"=>"2019-12-10T08:47:57Z",
 "crossposted_at"=>nil,
 "published_at"=>"2019-11-28T14:43:27Z",
 "last_comment_at"=>"2019-11-28T14:43:27Z",
 "published_timestamp"=>"2019-11-28T14:43:27Z",
 "body_html"=>
  "<p>Hi I started a little implementation of a Telegram Bot Around RubyGems.org API. Take a look at <a href=\"https://t.me/rubyg_bot\">https://t.me/rubyg_bot</a>, and give me some feedbacks.</p>\n\n<p>GitHub public repository coming soon. </p>\n\n<p>You can control Bot by sending these commands:</p>\n\n<p><strong>/info</strong> - type gem name and get some basic information type<br>\n<strong>/search</strong> - type gem name and get an array of active gems that match the query<br>\n<strong>/gems</strong> - type author username and get top 50 gems owned by specified username<br>\n<strong>/updated</strong> - returns the 50 most recently updated gems<br>\n<strong>/latest</strong> - returns the 50 gems most recently added to RubyGems.org<br>\n<strong>/popular</strong> - returns an array containing the top 50 downloaded gem versions of all time<br>\n<strong>/versions</strong> - type gem name and get an array (latest 50) of version details</p>\n\n<p><a href=\"https://res.cloudinary.com/practicaldev/image/fetch/s--mtvFjJEg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.ibb.co/9bQNgPG/Screenshot-2019-11-28-at-16-23-10.png\" class=\"article-body-image-wrapper\"><img src=\"https://res.cloudinary.com/practicaldev/image/fetch/s--mtvFjJEg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://i.ibb.co/9bQNgPG/Screenshot-2019-11-28-at-16-23-10.png\" alt=\"App Screeshot\" loading=\"lazy\"></a></p>\n\n<p>A little video demonstration<br>\n<a href=\"https://twitter.com/daviducolo/status/1199731530429554688\">https://twitter.com/daviducolo/status/1199731530429554688</a></p>\n\n",
 "body_markdown"=>
  "---\ntitle: RubyGems Telegram Bot\npublished: true\ndescription: Bot wrapper for the RubyGems.org API\ntags: webdev,rails,ruby,showdev\n---\n\nHi I started a little implementation of a Telegram Bot Around RubyGems.org API. Take a look at https://t.me/rubyg_bot, and give me some feedbacks.\n\nGitHub public repository coming soon. \n\nYou can control Bot by sending these commands:\n\n**/info** - type gem name and get some basic information type\n**/search** - type gem name and get an array of active gems that match the query\n**/gems** - type author username and get top 50 gems owned by specified username\n**/updated** - returns the 50 most recently updated gems\n**/latest** - returns the 50 gems most recently added to RubyGems.org\n**/popular** - returns an array containing the top 50 downloaded gem versions of all time\n**/versions** - type gem name and get an array (latest 50) of version details\n\n\n![App Screeshot](https://i.ibb.co/9bQNgPG/Screenshot-2019-11-28-at-16-23-10.png)\n\n\n\nA little video demonstration\nhttps://twitter.com/daviducolo/status/1199731530429554688\n\n\n\n\n",
 "user"=>
  {"name"=>"Davide Santangelo",
   "username"=>"daviducolo",
   "twitter_username"=>"daviducolo",
   "github_username"=>"davidesantangelo",
   "website_url"=>"http://www.davidesantangelo.com",
   "profile_image"=>"https://res.cloudinary.com/practicaldev/image/fetch/s--jMRKagS9--/c_fill,f_auto,fl_progressive,h_640,q_auto,w_640/https://thepracticaldev.s3.amazonaws.com/uploads/user/profile_image/2717/P6rt05x6.jpg",
   "profile_image_90"=>"https://res.cloudinary.com/practicaldev/image/fetch/s--8bDrK9qZ--/c_fill,f_auto,fl_progressive,h_90,q_auto,w_90/https://thepracticaldev.s3.amazonaws.com/uploads/user/profile_image/2717/P6rt05x6.jpg"},
 "flare_tag"=>{"name"=>"showdev", "bg_color_hex"=>"#091b47", "text_color_hex"=>"#b2ffe1"}}

Artículos de usuario

pregunta de discusión, un hilo de ayuda, etc., pero se conoce como artículo dentro del código.
Los artículos publicados estarán en orden de publicación cronológica inversa.
Devolverá los artículos publicados con paginación. Por defecto, una página contendrá 30 artículos.
require 'rest-client'
require 'json'

def user_articles(params: {}, api_key: )
  response = RestClient::Request.execute(method: :get, url: "https://dev.to/api/articles/me", timeout: 10, headers: { params: params, "api-key" => api_key })                       
  articles = JSON.parse(response.body)

  articles
rescue RestClient::Unauthorized, RestClient::Forbidden => err
  puts 'Access denied'
  puts err.response
  []
rescue RestClient::ExceptionWithResponse => err
  puts err.response
  []
end  

No hay comentarios.:

Publicar un comentario

Dejanos tu comentario para seguir mejorando!

Post Top Ad

Your Ad Spot

Páginas