API Reference
This page contains the complete API reference for the Swift OAuth2 Client.
oauth2_client.config.OAuth2Config
dataclass
Configuration class for OAuth2 authentication.
This class holds the necessary information for OAuth2 authentication, including the token URL, client credentials, and requested scopes.
Attributes:
| Name | Type | Description |
|---|---|---|
token_url |
str
|
The URL to obtain the OAuth2 token. |
client_id |
str
|
The client ID for OAuth2 authentication. |
client_secret |
str
|
The client secret for OAuth2 authentication. |
scopes |
List[str]
|
A list of scopes to request for the OAuth2 token. |
Example
config = OAuth2Config(
token_url="https://api.example.com/oauth/token",
client_id="your_client_id",
client_secret="your_client_secret",
scopes=["read", "write"]
)
oauth2_client.api_client.APIClient
Client for making authenticated API calls using OAuth2.
This class provides a synchronous interface for API calls, internally using an asynchronous client.
Attributes:
| Name | Type | Description |
|---|---|---|
token_manager |
TokenManager
|
Manages OAuth2 tokens synchronously. |
async_client |
APIClientAsync
|
The underlying asynchronous client. |
__enter__()
Enter the runtime context related to this object.
Returns:
| Name | Type | Description |
|---|---|---|
APIClient |
The client instance. |
Example
with APIClient(config, "https://api.example.com") as client:
response, status = client.call_api("GET", "/users")
__exit__(exc_type, exc_val, exc_tb)
Exit the runtime context related to this object.
This method calls close() to ensure all resources are properly released.
__init__(config, base_url)
Initialize the APIClient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config |
Optional[OAuth2Config]
|
OAuth2 configuration. If None, no authentication is used. |
required |
base_url |
str
|
The base URL for API calls. |
required |
call_api(method, path, body=None, additional_headers=None)
Make an API call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
str
|
HTTP method (e.g., "GET", "POST"). |
required |
path |
str
|
API endpoint path. |
required |
body |
Any
|
Request body. Defaults to None. |
None
|
additional_headers |
Optional[Dict[str, str]]
|
Additional HTTP headers. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Union[bytes, str, Dict], int, str]
|
Tuple[Union[bytes, str, Dict], int, str]: Response body, status code, and content type. |
Example
response, status, content_type = client.call_api("GET", "/users")
print(f"Status: {status}, Content-Type: {content_type}, Response: {response}")
close()
Close the client and its underlying resources.
This method should be called when the client is no longer needed.
download_file(method, path, body=None, additional_headers=None, dest_path=None)
Download a file from the API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
str
|
HTTP method (usually "GET"). |
required |
path |
str
|
API endpoint path. |
required |
body |
Any
|
Request body. Defaults to None. |
None
|
additional_headers |
Optional[Dict[str, str]]
|
Additional HTTP headers. Defaults to None. |
None
|
dest_path |
Optional[Union[str, Path]]
|
Destination path to save the file. If None, returns the file content. |
None
|
Returns:
| Type | Description |
|---|---|
Union[str, bytes]
|
Union[str, bytes]: File content or success message. |
Example
result = client.download_file("GET", "/files/document.pdf", dest_path="local_document.pdf")
print(result)
oauth2_client.token_manager.TokenManager
A synchronous wrapper for the asynchronous TokenManagerAsync class.
This class provides a blocking, synchronous interface for acquiring and refreshing OAuth2 tokens, using an asyncio event loop to run the asynchronous methods of TokenManagerAsync.
Attributes:
| Name | Type | Description |
|---|---|---|
_async_token_manager |
TokenManagerAsync
|
An instance of the TokenManagerAsync class. |
_loop |
AbstractEventLoop
|
The asyncio event loop to run async methods. |
Example usage
import asyncio
from token_manager import TokenManager
from token_manager_async import TokenManagerAsync
from config import OAuth2Config
# Step 1: Initialize the OAuth2 configuration
config = OAuth2Config(
client_id="your_client_id",
client_secret="your_client_secret",
token_url="https://oauth2-server.com/token",
scopes=["scope1", "scope2"]
)
# Step 2: Create an instance of TokenManagerAsync with the configuration
async_token_manager = TokenManagerAsync(config)
# Step 3: Get an asyncio event loop (or create a new one)
loop = asyncio.get_event_loop()
# Step 4: Initialize the TokenManager with the async token manager and the event loop
token_manager = TokenManager(async_token_manager=async_token_manager, loop=loop)
# Step 5: Use the TokenManager to get a valid token synchronously
token = token_manager.get_valid_token()
# Output the token
print(f"Access Token: {token}")
access_token: str
property
writable
Accesses the current OAuth2 access token.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The current OAuth2 access token. |
expires_at: float
property
writable
Accesses the expiration time of the current OAuth2 access token.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The expiration time of the token in UNIX time. |
__init__(async_token_manager, loop)
Initializes the TokenManager with an async token manager and event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
async_token_manager |
TokenManagerAsync
|
The asynchronous token manager responsible for managing tokens. |
required |
loop |
AbstractEventLoop
|
The asyncio event loop used to run async tasks. |
required |
get_valid_token()
Retrieves a valid OAuth2 token synchronously, refreshing it if necessary.
This method wraps the async get_valid_token method from TokenManagerAsync and runs it in the provided event loop.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A valid OAuth2 access token. |
refresh_token()
Refreshes the OAuth2 access token synchronously.
This method wraps the async refresh_token method from TokenManagerAsync and runs it in the provided event loop.
Returns:
| Type | Description |
|---|---|
|
None |
oauth2_client.api_client_async.APIClientAsync
Asynchronous client for making authenticated API calls using OAuth2.
This class handles API calls, including automatic token management and request/response processing.
Attributes:
| Name | Type | Description |
|---|---|---|
base_url |
str
|
The base URL for API calls. |
token_manager |
TokenManager
|
Manages OAuth2 tokens. |
http_client |
AsyncClient
|
Asynchronous HTTP client. |
Example
config = OAuth2Config(...)
async with APIClientAsync(config, "https://api.example.com") as client:
response, status = await client.call_api("GET", "/users")
__aenter__()
async
Async context manager entry.
__aexit__(exc_type, exc_val, exc_tb)
async
Async context manager exit.
__init__(config, base_url)
Initialize the APIClientAsync.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config |
Optional[OAuth2Config]
|
OAuth2 configuration. If None, no authentication is used. |
required |
base_url |
str
|
The base URL for API calls. |
required |
call_api(method, path, body=None, additional_headers=None)
async
Make an authenticated API call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
str
|
HTTP method (e.g., "GET", "POST"). |
required |
path |
str
|
API endpoint path. |
required |
body |
Any
|
Request body. Defaults to None. |
None
|
additional_headers |
Optional[Dict[str, str]]
|
Additional HTTP headers. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Union[bytes, str, Dict], int, str]
|
Tuple[Union[bytes, str, Dict], int, str]: Response body, status code, and content type. |
Raises:
| Type | Description |
|---|---|
APIError
|
If the API call fails. |
Example
response, status, content_type = await client.call_api("GET", "/users")
print(f"Status: {status}, Content-Type: {content_type}, Response: {response}")
close()
async
Close the HTTP client session.
download_file(method, path, body=None, additional_headers=None, dest_path=None)
async
Download a file from the API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
str
|
HTTP method (usually "GET"). |
required |
path |
str
|
API endpoint path. |
required |
body |
Any
|
Request body. Defaults to None. |
None
|
additional_headers |
Optional[Dict[str, str]]
|
Additional HTTP headers. Defaults to None. |
None
|
dest_path |
Optional[Union[str, Path]]
|
Destination path to save the file. If None, returns the file content. |
None
|
Returns:
| Type | Description |
|---|---|
Union[str, bytes]
|
Union[str, bytes]: File content or success message. |
Example
result = await client.download_file("GET", "/files/document.pdf", dest_path="local_document.pdf")
print(result)
oauth2_client.token_manager_async.TokenManagerAsync
Manages OAuth2 token acquisition and renewal.
This class is responsible for obtaining and refreshing OAuth2 tokens as needed for API authentication.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
OAuth2Config
|
The OAuth2 configuration. |
access_token |
str
|
The current access token. |
expires_at |
float
|
The expiration time of the current token. |
lock |
Lock
|
A lock for thread-safe token refresh operations. |
Example
config = OAuth2Config(...)
token_manager = TokenManagerAsync(config)
token = await token_manager.get_valid_token()
__init__(config)
Initialize the TokenManagerAsync.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config |
OAuth2Config
|
The OAuth2 configuration. |
required |
get_valid_token()
async
Get a valid OAuth2 token, refreshing if necessary.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A valid OAuth2 access token. |
Raises:
| Type | Description |
|---|---|
TokenRefreshError
|
If token refresh fails. |
refresh_token()
async
Refresh the OAuth2 token.
This method obtains a new access token from the OAuth2 server.
Raises:
| Type | Description |
|---|---|
TokenRefreshError
|
If token refresh fails. |
oauth2_client.exceptions
This module contains custom exceptions for the OAuth2Client.
APIError
Bases: OAuth2ClientError
Raised when an API call fails.
OAuth2ClientError
Bases: Exception
Base exception for OAuth2Client.
TokenRefreshError
Bases: OAuth2ClientError
Raised when token refresh fails.
Helper Functions
oauth2_client.api_client.new_api_client(config, base_url)
Create a new APIClient instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config |
Optional[OAuth2Config]
|
OAuth2 configuration. If None, no authentication is used. |
required |
base_url |
str
|
The base URL for API calls. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
APIClient |
APIClient
|
A new APIClient instance. |
Example
config = OAuth2Config(...)
client = new_api_client(config, "https://api.example.com")
oauth2_client.api_client_async.new_api_client_async(config, base_url)
Create a new APIClientAsync instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config |
Optional[OAuth2Config]
|
OAuth2 configuration. If None, no authentication is used. |
required |
base_url |
str
|
The base URL for API calls. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
APIClientAsync |
APIClientAsync
|
A new APIClientAsync instance. |
Example
config = OAuth2Config(...)
client = new_api_client_async(config, "https://api.example.com")
async with client:
# Use the client