linkedin Ruby Gem

repository·master·Indexed 20 days ago

https://github.com/hexgnu/linkedin

A Ruby wrapper for the LinkedIn REST APIs that provides an interface for interacting with the LinkedIn developer platform. It includes support for OAuth2 authentication, retrieving user and company profiles, managing network connections, sending messages, and interacting with groups and job bookmarks.

Tokens
7.7K
Snippets
46
Records
51
Agent score
73%

What's inside linkedin

  1. Authenticate with LinkedIn via OAuth2

    master

    To use the LinkedIn API, you must first authenticate using OAuth2. This involves initializing a LinkedIn::Client with your consumer key and secret, generating an authorization URL, and then exchanging the authorization code (received via a callback) for access tokens.

    1. Initialize Client: LinkedIn::Client.new(consumer_key, consumer_secret)
    2. Generate URL: Use client.authorize_url with your redirect_uri and desired scope (e.g., r_basicprofile+r_emailaddress).
    3. Exchange Code: After the user authorizes, LinkedIn redirects to your callback with a code parameter. Use client.authorize_from_request(params[:code], :redirect_uri => '...') to obtain the access token.
    4. Persistent Session: You can later re-authorize using a previously saved access token with client.authorize_from_access("ACCESS_TOKEN").
    require 'rubygems'
    require 'linkedin'
    
    # 1. Initialize
    client = LinkedIn::Client.new('your_consumer_key', 'your_consumer_secret')
    
    # 2. Get Authorization URL
    url = client.authorize_url(:redirect_uri => 'https://www.yourdomain.com/callback', :state => SecureRandom.uuid, :scope => "r_basicprofile+r_emailaddress")
    
    # 3. Exchange code from callback for access token
    # params[:code] is provided by the LinkedIn redirect
    access_token = client.authorize_from_request(params[:code], :redirect_uri => 'https://www.yourdomain.com/callback')
    
    # 4. Or use a saved token later
    client.authorize_from_access("OU812")
  2. Understand LinkedIn::Mash key transformations

    master

    The LinkedIn::Mash class automatically transforms LinkedIn API keys into more idiomatic Ruby (snake_case) keys. Key mappings include:

    • _total becomes total
    • values becomes all
    • numResults becomes total_results
    • All other camelCase or hyphenated keys are converted to underscore format.
  3. Authorize users via OAuth2 flow

    master

    The LinkedIn::Helpers::Authorization module provides methods to manage the LinkedIn OAuth2 lifecycle. Depending on your application type, you can authorize users using an authorization code or a direct access token.

    Web Applications

    For web applications, use authorize_from_request by passing the code received from the LinkedIn callback and the request parameters (e.g., params[:oauth_verifier]).

    Desktop Applications

    For desktop applications, the verifier is the PIN provided by LinkedIn to the user.

    Direct Token Assignment

    If you already possess an access token, use authorize_from_access to set the internal @auth_token state.

    # For Web Apps
    authorize_from_request(params[:code], params)
    
    # For Desktop Apps
    authorize_from_request(code, { oauth_verifier: user_provided_pin })
    
    # Using an existing token
    authorize_from_access("EXISTING_ACCESS_TOKEN")
  4. Implement LinkedIn authentication in a Sinatra app

    master

    This pattern demonstrates how to manage LinkedIn OAuth2 sessions in a Sinatra application using session to store access tokens and a helper to initialize the LinkedIn::Client with the stored token.

    require "rubygems"
    require "haml"
    require "sinatra"
    require "linkedin"
    
    enable :sessions
    
    helpers do
      def login?
        !session[:atoken].nil?
      end
    
      def profile
        linkedin_client.profile unless session[:atoken].nil?
      end
    
      private
      def linkedin_client
        client = LinkedIn::Client.new(settings.api, settings.secret)
        client.authorize_from_access(session[:atoken])
        client
      end
    end
    
    configure do
      set :api, "your_api_key"
      set :secret, "your_secret"
    end
    
    get "/auth" do
      client = LinkedIn::Client.new(settings.api, settings.secret)
      request_token = client.request_token(:oauth_callback => "http://#{request.host}:#{request.port}/auth/callback")
      session[:rtoken] = request_token.token
      session[:rsecret] = request_token.secret
      redirect client.request_token.authorize_url
    end
    
    get "/auth/callback" do
      client = LinkedIn::Client.new(settings.api, settings.secret)
      if session[:atoken].nil?
        pin = params[:oauth_verifier]
        atoken, asecret = client.authorize_from_request(session[:rtoken], session[:rsecret], pin)
        session[:atoken] = atoken
        session[:asecret] = asecret
      end
      redirect "/"
    end
  5. Send a message to network members

    master

    To send a message, you must have the w_messages permission. The send_message method takes a subject, a body, and an array of recipient IDs.

    # client is a LinkedIn::Client
    response = client.send_message("subject", "body", ["person_1_id", "person_2_id"])
  6. Access user profiles

    master

    Use the profile method on a LinkedIn::Client instance to retrieve profile information. You can fetch the authenticated user's profile, a specific user by ID or URL, or filter specific fields.

    • Authenticated User: client.profile
    • By ID: client.profile(:id => 'ID')
    • By URL: client.profile(:url => 'URL')
    • Specific Fields: Use the :fields option to request specific data (e.g., positions).
    • Email Search: Use the :email option for multi-email searches.
    # Get current user profile
    client.profile
    
    # Get profile by ID
    client.profile(:id => 'gNma67_AdI')
    
    # Get profile by URL
    client.profile(:url => 'http://www.linkedin.com/in/netherland')
    
    # Get profile with specific fields (e.g., positions)
    user = client.profile(:fields => %w(positions))
    companies = user.positions.all.map{|t| t.company}
    
    # Multi-email search
    account_exists = client.profile(:email => 'email=yy@zz.com,email=xx@yy.com', :fields => ['id'])
  7. Access network updates and connections

    master

    Retrieve information about the authenticated user's network, including updates, connections, and profile pictures.

    # Get network updates
    client.network_updates
    
    # Get only profile picture changes
    client.network_updates(:type => 'PICT')
    
    # View connections
    client.connections
    
    # Get a connection's picture URL
    client.picture_urls(:id => 'id_of_connection')
    
    # Get a connection's picture URL via HTTPS
    client.picture_urls(:id => 'id_of_connection', :secure => "true")
  8. Configure the LinkedIn gem

    master

    Use the LinkedIn.configure block to set global configuration settings for the gem. This is typically done in a Rails initializer (e.g., config/initializers/linkedin.rb).

    You can set the following attributes:

    • token: Your consumer token.
    • secret: Your consumer secret.
    • default_profile_fields: An array of profile fields to be requested by default (e.g., ['educations', 'positions']).
    LinkedIn.configure do |config|
      config.token = 'consumer_token'
      config.secret = 'consumer_secret'
      config.default_profile_fields = ['educations', 'positions']
    end
  9. Configure OAuth2 host and path options

    master

    The authorization helper uses specific hosts for different parts of the OAuth flow. By default, it uses:

    • API Host (api.linkedin.com): Used for request and access token exchanges.
    • Auth Host (www.linkedin.com): Used for the initial authorize/authenticate redirect.

    You can override these via @consumer_options using the following keys:

    KeyDescription
    :api_hostThe base URL for API requests (Default: https://api.linkedin.com)
    :auth_hostThe base URL for authentication redirects (Default: https://www.linkedin.com)
    :<type>_urlFull URL override for :token_url or :authorize_url
    :<type>_pathPath override for :token_path or :authorize_path