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.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, base_request: HTTP, token:) ⇒ 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
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)

    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



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

def initialize(base_url:, base_request: HTTP, token:)
  @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



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

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