How can I call an API (for example Flickr API) in Ruby on Rails? Newbie question

后端 未结 2 1061
心在旅途
心在旅途 2021-02-03 15:07

Im building my first app in rails and I would like to call Flickr\'s API

I know I can use flickr-fu, rflickr or other gem but I want to do it myself from scratch to lear

相关标签:
2条回答
  • 2021-02-03 15:52

    First you need some kind of an XML parser to handle the data you got. Nokogiri is a much used parser, but it might be a little too much. In that case find a more simple one.

    This should be enough.

    But if you really want to the be represented as you suggest in your example, you need to (recursively) iterate through your XML document and put it in some structure. Take a look at Ruby access magic to see how you can dynamically build such a structure. Another possibility is to create classes for all the groups of details (as flickr-fu does), which is much more efficient since the data is known on beforehand.

    PS You can cheat a bit by looking to other solutions, this way you will still learn to do it yourself, but you do not need to re-invent the wheel completely. In fact combine the idea of several implementations and you might come up with something even better!

    0 讨论(0)
  • 2021-02-03 15:53
    include 'rubygems'
    include 'httparty'
    
    class Flickr
      include HTTParty
    
      base_uri 'api.flickr.com'
    
      def self.getPhotos(uid)
        return get('/services/rest/', :query => {
          :method => 'flickr.people.getPublicPhotos',
          :api_key => 'api key goes here',
          :user_id => uid})
      end
    end
    

    and then call

    Flickr.getPhotos('12345678')
    
    0 讨论(0)
提交回复
热议问题