Class: Oauth2ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/oauth2_api_client.rb,
lib/oauth2_api_client/version.rb,
lib/oauth2_api_client/response_error.rb,
lib/oauth2_api_client/token_provider.rb

Overview

The Oauth2ApiClient class is a client wrapped around the oauth2 and http-rb gem to interact with APIs using oauth2 for authentication with automatic token caching and renewal.

Defined Under Namespace

Classes: ResponseError, TokenProvider

Constant Summary collapse

VERSION =
"3.2.1"

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, token: nil, base_request: HTTP) ⇒ Oauth2ApiClient

Creates a new Oauth2ApiClient

Examples:

client = Oauth2ApiClient.new(
  base_url: "https://api.example.com",
  token: "the api token"
)

client.post("/orders", json: { address: "..." }).status.success?
client.headers("User-Agent" => "API Client").timeout(read: 5, write: 5).get("/orders").parse(:json)
client = Oauth2ApiClient.new(
  base_url: "https://api.example.com",
  token: Oauth2ApiClient::TokenProvider.new(
    client_id: "the client id",
    client_secret: "the client secret",
    oauth_token_url: "https://auth.example.com/oauth2/token",
    cache: Rails.cache
  )
)

Parameters:

  • base_url (String)

    The base url of the API to interact with

  • token (String, Oauth2ApiClient::TokenProvider) (defaults to: nil)

    Allows to pass an existing token received via external sources or an instance of ‘Oauth2ApiClient::TokenProvider` which is capable of generating tokens when client id, client secret, etc. is given



43
44
45
46
47
# File 'lib/oauth2_api_client.rb', line 43

def initialize(base_url:, token: nil, base_request: HTTP)
  @base_url = base_url
  @token = token
  @request = base_request
end

Instance Method Details

#tokenString

Returns a oauth2 token to use for authentication

Returns:

  • (String)

    The token



53
54
55
56
57
# File 'lib/oauth2_api_client.rb', line 53

def token
  return if @token.nil?

  @token.respond_to?(:to_str) ? @token.to_str : @token.token
end