-
Notifications
You must be signed in to change notification settings - Fork 87
Feature/improved api client #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
dylanburkey
wants to merge
9
commits into
game-by-virtuals:main
Choose a base branch
from
Athena-GenAI:feature/improved-api-client
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
9420c18
feat: Add improved API client with better error handling and configur…
dylanburkey 4705c4e
test: Add comprehensive tests for API client
dylanburkey 591b060
fix: Update API client error handling and retry logic
dylanburkey c0399e1
fix: Update retry logic to exclude auth and validation errors
dylanburkey f68f865
fix: Make retry logic a static method
dylanburkey df79b4b
fix: Move retry predicate function outside class
dylanburkey fa6e5d2
test: Update test expectations for API and network errors
dylanburkey d740caf
test: Add tenacity import and update test assertions
dylanburkey 713b503
chore: Add .coverage to gitignore
dylanburkey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,6 +5,7 @@ | |
*.pyc | ||
*__pycache__ | ||
*.json | ||
.coverage | ||
|
||
*.DS_Store | ||
dist/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
pytest>=7.0.0 | ||
responses>=0.23.0 | ||
pytest-cov>=4.0.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
""" | ||
API client module for the GAME SDK. | ||
|
||
This module provides a dedicated API client for making requests to the GAME API, | ||
handling authentication, errors, and response parsing consistently. | ||
""" | ||
|
||
import requests | ||
from typing import Dict, Any, Optional | ||
from game_sdk.game.config import config | ||
from game_sdk.game.exceptions import APIError, AuthenticationError, ValidationError | ||
from game_sdk.game.custom_types import ActionResponse, FunctionResult | ||
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception | ||
|
||
|
||
def should_retry(exception): | ||
"""Determine if we should retry the request based on the exception type.""" | ||
if isinstance(exception, (AuthenticationError, ValidationError)): | ||
return False | ||
return isinstance(exception, (APIError, requests.exceptions.RequestException)) | ||
|
||
|
||
class GameAPIClient: | ||
"""Client for interacting with the GAME API. | ||
|
||
This class handles all API communication, including authentication, | ||
request retries, and error handling. | ||
|
||
Attributes: | ||
api_key (str): API key for authentication | ||
base_url (str): Base URL for API requests | ||
session (requests.Session): Reusable session for API requests | ||
""" | ||
|
||
def __init__(self, api_key: Optional[str] = None): | ||
"""Initialize the API client. | ||
|
||
Args: | ||
api_key (str): API key for authentication | ||
|
||
Raises: | ||
ValueError: If API key is not provided | ||
""" | ||
if not api_key: | ||
raise ValueError("API key is required") | ||
|
||
self.api_key = api_key | ||
self.base_url = config.api_url | ||
self.session = requests.Session() | ||
self.session.headers.update({ | ||
"Authorization": f"Bearer {api_key}", | ||
"Content-Type": "application/json" | ||
}) | ||
|
||
@retry( | ||
stop=stop_after_attempt(3), | ||
wait=wait_exponential(multiplier=1, min=4, max=10), | ||
retry=retry_if_exception(should_retry) | ||
) | ||
def make_request( | ||
self, | ||
method: str, | ||
endpoint: str, | ||
data: Optional[Dict[str, Any]] = None, | ||
params: Optional[Dict[str, Any]] = None | ||
) -> Dict[str, Any]: | ||
"""Make an HTTP request to the API. | ||
|
||
Args: | ||
method (str): HTTP method (GET, POST, etc.) | ||
endpoint (str): API endpoint | ||
data (Optional[Dict[str, Any]], optional): Request body. Defaults to None. | ||
params (Optional[Dict[str, Any]], optional): Query parameters. Defaults to None. | ||
|
||
Raises: | ||
AuthenticationError: If authentication fails | ||
ValidationError: If request validation fails | ||
APIError: For other API-related errors | ||
|
||
Returns: | ||
Dict[str, Any]: API response data | ||
""" | ||
url = f"{self.base_url}/{endpoint.lstrip('/')}" | ||
|
||
try: | ||
response = self.session.request( | ||
method=method, | ||
url=url, | ||
json=data, | ||
params=params | ||
) | ||
|
||
response.raise_for_status() | ||
return response.json() | ||
|
||
except requests.exceptions.HTTPError as e: | ||
if response.status_code == 401: | ||
# Don't retry auth errors | ||
raise AuthenticationError("Authentication failed") from e | ||
elif response.status_code == 422: | ||
# Don't retry validation errors | ||
raise ValidationError("Invalid request data") from e | ||
else: | ||
# Retry other HTTP errors | ||
raise APIError(f"API request failed: {str(e)}") from e | ||
except requests.exceptions.RequestException as e: | ||
# Retry network errors | ||
raise APIError(f"Request failed: {str(e)}") from e | ||
|
||
def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: | ||
"""Make a GET request. | ||
|
||
Args: | ||
endpoint (str): API endpoint | ||
params (Optional[Dict[str, Any]], optional): Query parameters. Defaults to None. | ||
|
||
Returns: | ||
Dict[str, Any]: API response data | ||
""" | ||
return self.make_request("GET", endpoint, params=params) | ||
|
||
def post(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]: | ||
"""Make a POST request. | ||
|
||
Args: | ||
endpoint (str): API endpoint | ||
data (Dict[str, Any]): Request body | ||
|
||
Returns: | ||
Dict[str, Any]: API response data | ||
""" | ||
return self.make_request("POST", endpoint, data=data) | ||
|
||
def put(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]: | ||
"""Make a PUT request. | ||
|
||
Args: | ||
endpoint (str): API endpoint | ||
data (Dict[str, Any]): Request body | ||
|
||
Returns: | ||
Dict[str, Any]: API response data | ||
""" | ||
return self.make_request("PUT", endpoint, data=data) | ||
|
||
def delete(self, endpoint: str) -> Dict[str, Any]: | ||
"""Make a DELETE request. | ||
|
||
Args: | ||
endpoint (str): API endpoint | ||
|
||
Returns: | ||
Dict[str, Any]: API response data | ||
""" | ||
return self.make_request("DELETE", endpoint) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
""" | ||
Configuration module for the GAME SDK. | ||
|
||
This module provides centralized configuration management for the SDK. | ||
""" | ||
|
||
from dataclasses import dataclass | ||
|
||
|
||
@dataclass | ||
class Config: | ||
"""Configuration settings for the GAME SDK. | ||
|
||
Attributes: | ||
api_url (str): Base URL for API requests | ||
default_timeout (int): Default timeout for API requests in seconds | ||
""" | ||
api_url: str = "https://sdk.game.virtuals.io" | ||
default_timeout: int = 30 | ||
|
||
|
||
# Global configuration instance | ||
config = Config() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
""" | ||
Custom exceptions for the GAME SDK. | ||
|
||
This module provides custom exception classes for better error handling | ||
and more informative error messages. | ||
""" | ||
|
||
|
||
class GameSDKError(Exception): | ||
"""Base exception class for all GAME SDK errors.""" | ||
pass | ||
|
||
|
||
class APIError(GameSDKError): | ||
"""Raised when an API request fails.""" | ||
pass | ||
|
||
|
||
class AuthenticationError(APIError): | ||
"""Raised when API authentication fails.""" | ||
pass | ||
|
||
|
||
class ValidationError(APIError): | ||
"""Raised when request validation fails.""" | ||
pass |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure if we need this, given that we have a pyproject.toml
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pyproject.toml
is for abstract dependencies.requirements.txt
andrequirements-dev.txt
are for pinned dependencies.Reference: