Myspace Data Availability in Ruby on Rails

Like Facebook Connect, Myspace Data Availability enables your site to take advantage of Myspace accounts. For example, you can have your users login to your site using their Myspace accounts, or list their Myspace friends on your own site.

I didnt find an easy step-by-step tutorial even on a basic thing like getting the myspace user id of the logged in user in the external website; so I figure I’ll write this post to help other Rails developers out there who are new to this.

This is an example. First, in your rhtml, you’ll want a link whereby if the user clicks on that, the user can login using his myspace account and then he can see his myspace user_id in your site (if you can get to this step, it’s easy to add more complicated social features).

<%= link_to ‘See my myspace_user_id’, {:action => ’see_my_myspaceuserid’} %>

Now, how to implement ’see_my_myspaceuserid’ ? You probably are looking at this tutorial here:

http://developer.myspace.com/community/myspace/dataavailability.aspx

Dont be daunted when you read over the ‘Access Delegation’ part. It’s actually a basic Oauth authorization mechanism, and the Rails ‘oauth’ gem will help us a lot. Read about the gem here: http://oauth.rubyforge.org/ , or as usual, the best documentation usually are inside the code itself (in my Windows computer it’s here: C:\ruby\lib\ruby\gems\1.8\gems\oauth-0.2.4\lib\oauth\consumer.rb).

So here’s how the controller looks like:


def see_my_myspaceuserid
@consumer = OAuth::Consumer.new('your OAuth Consumer Key‘, ‘your OAuth Consumer Secret‘, {:site => ‘http://api.myspace.com’, :http_method => :get, :request_token_path => ‘/request_token’, :authorize_path => ‘/authorize’,:access_token_path=>’/access_token’})
@request_token = @consumer.get_request_token
redirect_to @request_token.authorize_url + ‘oauth_callback=display_myspace_user_id’
end

So once the user clicks on the link, he’ll be redirected to myspace to login there. After he logs in there, he’ll be redirected back to your site. Let’s say the callback url is called ‘display_myspace_user_id’, so here’s what it’ll look like:


def display_myspace_user_id
# You can save the @request_token from action 'see_my_myspaceuserid' and use it here
response = @request_token.get_access_token.get('/v1/user.xml')
# Now use REXML::Document to parse response.body, and you'll get the user_id !
end

How do I know that the parameter to access_token is ‘/v1/user.xml’ ?
Read here: http://developer.myspace.com/community/RestfulAPIs/resources.aspx

That’s it. You can use the access_token to do all sorts of REST API calls to Myspace now!
I hope this helps.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.