Reference for hub_sdk/base/api_client.py
Improvements
This page is sourced from https://github.com/ultralytics/hub-sdk/blob/main/hub_sdk/base/api_client.py. Have an improvement or example to add? Open a Pull Request — thank you! 🙏
Summary
class hub_sdk.base.api_client.APIClientError
APIClientError(self, message: str, status_code: int | None = None)
Bases: Exception
Custom exception class for API client errors.
Args
| Name | Type | Description | Default |
|---|---|---|---|
message | str | A human-readable error message. | required |
status_code | int, optional | The HTTP status code associated with the error. | None |
Attributes
| Name | Type | Description |
|---|---|---|
message | str | A human-readable error message. |
status_code | int, optional | The HTTP status code associated with the error, if available. |
Methods
| Name | Description |
|---|---|
__str__ | Return a string representation of the APIClientError instance. |
Source code in hub_sdk/base/api_client.py
View on GitHubclass APIClientError(Exception):
"""Custom exception class for API client errors.
Attributes:
message (str): A human-readable error message.
status_code (int, optional): The HTTP status code associated with the error, if available.
"""
def __init__(self, message: str, status_code: int | None = None):
"""Initialize the APIClientError instance.
Args:
message (str): A human-readable error message.
status_code (int, optional): The HTTP status code associated with the error.
"""
super().__init__(message)
self.status_code = status_code
self.message = message
method hub_sdk.base.api_client.APIClientError.__str__
def __str__(self) -> str
Return a string representation of the APIClientError instance.
Source code in hub_sdk/base/api_client.py
View on GitHubdef __str__(self) -> str:
"""Return a string representation of the APIClientError instance."""
return f"{self.__class__.__name__}: {self.args[0]}"
class hub_sdk.base.api_client.APIClient
APIClient(self, base_url: str, headers: dict | None = None)
Represents an API client for making requests to a specified base URL.
Args
| Name | Type | Description | Default |
|---|---|---|---|
base_url | str | The base URL for the API. | required |
headers | Dict, optional | Headers to be included in each request. | None |
Attributes
| Name | Type | Description |
|---|---|---|
base_url | str | The base URL for the API. |
headers | Dict, optional | Headers to be included in each request. |
logger | logging.Logger | An instance of the logger for logging purposes. |
Methods
| Name | Description |
|---|---|
_make_request | Make an HTTP request to the API. |
delete | Make a DELETE request to the API. |
get | Make a GET request to the API. |
patch | Make a PATCH request to the API. |
post | Make a POST request to the API. |
put | Make a PUT request to the API. |
Source code in hub_sdk/base/api_client.py
View on GitHubclass APIClient:
"""Represents an API client for making requests to a specified base URL.
Attributes:
base_url (str): The base URL for the API.
headers (Dict, optional): Headers to be included in each request.
logger (logging.Logger): An instance of the logger for logging purposes.
"""
def __init__(self, base_url: str, headers: dict | None = None):
"""Initialize an instance of the APIClient class.
Args:
base_url (str): The base URL for the API.
headers (Dict, optional): Headers to be included in each request.
"""
self.base_url = base_url
self.headers = headers
self.logger = logger
method hub_sdk.base.api_client.APIClient._make_request
def _make_request(
self,
method: str,
endpoint: str,
data: dict | None = None,
json: dict | None = None,
params: dict | None = None,
files: dict | None = None,
stream: bool = False,
) -> requests.Response | None
Make an HTTP request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
method | str | The HTTP method to use for the request (e.g., "GET", "POST"). | required |
endpoint | str | The endpoint to append to the base URL for the request. | required |
data | Dict, optional | Data to be sent in the request's body. | None |
json | Dict, optional | JSON data to be sent in the request's body. | None |
params | Dict, optional | Query parameters for the request. | None |
files | Dict, optional | Files to be sent as part of the form data. | None |
stream | bool | Whether to stream the response content. | False |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP request, None if it fails and |
Raises
| Type | Description |
|---|---|
APIClientError | If an error occurs during the request, this exception is raised with an appropriate message based on the HTTP status code. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef _make_request(
self,
method: str,
endpoint: str,
data: dict | None = None,
json: dict | None = None,
params: dict | None = None,
files: dict | None = None,
stream: bool = False,
) -> requests.Response | None:
"""Make an HTTP request to the API.
Args:
method (str): The HTTP method to use for the request (e.g., "GET", "POST").
endpoint (str): The endpoint to append to the base URL for the request.
data (Dict, optional): Data to be sent in the request's body.
json (Dict, optional): JSON data to be sent in the request's body.
params (Dict, optional): Query parameters for the request.
files (Dict, optional): Files to be sent as part of the form data.
stream (bool): Whether to stream the response content.
Returns:
(Optional[requests.Response]): The response object from the HTTP request, None if it fails and
HUB_EXCEPTIONS is off.
Raises:
APIClientError: If an error occurs during the request, this exception is raised with an appropriate message
based on the HTTP status code.
"""
# Overwrite the base url if a http url is submitted
url = endpoint if endpoint.startswith("http") else self.base_url + endpoint
kwargs = {"params": params, "files": files, "headers": self.headers, "stream": stream}
# Determine the request data based on 'data' or 'json_data'
if json is not None:
kwargs["json"] = json
else:
kwargs["data"] = data
try:
response = requests.request(method, url, **kwargs)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
status_code = None
# To handle Timeout and ConnectionError exceptions
if hasattr(e, "response") and e.response is not None:
status_code = e.response.status_code
error_msg = ErrorHandler(status_code, headers=response.headers).handle()
self.logger.error(error_msg)
if not HUB_EXCEPTIONS:
raise APIClientError(error_msg, status_code=status_code) from e
method hub_sdk.base.api_client.APIClient.delete
def delete(self, endpoint: str, params: dict | None = None) -> requests.Response | None
Make a DELETE request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
endpoint | str | The endpoint to append to the base URL for the request. | required |
params | dict, optional | Parameters to include in the request. | None |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP DELETE request, or None if it fails. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef delete(self, endpoint: str, params: dict | None = None) -> requests.Response | None:
"""Make a DELETE request to the API.
Args:
endpoint (str): The endpoint to append to the base URL for the request.
params (dict, optional): Parameters to include in the request.
Returns:
(Optional[requests.Response]): The response object from the HTTP DELETE request, or None if it fails.
"""
return self._make_request("DELETE", endpoint, params=params)
method hub_sdk.base.api_client.APIClient.get
def get(self, endpoint: str, params = None) -> requests.Response | None
Make a GET request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
endpoint | str | The endpoint to append to the base URL for the request. | required |
params | dict, optional | Query parameters for the request. | None |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP GET request, None if it fails. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef get(self, endpoint: str, params=None) -> requests.Response | None:
"""Make a GET request to the API.
Args:
endpoint (str): The endpoint to append to the base URL for the request.
params (dict, optional): Query parameters for the request.
Returns:
(Optional[requests.Response]): The response object from the HTTP GET request, None if it fails.
"""
return self._make_request("GET", endpoint, params=params)
method hub_sdk.base.api_client.APIClient.patch
def patch(self, endpoint: str, data: dict | None = None, json: dict | None = None) -> requests.Response | None
Make a PATCH request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
endpoint | str | The endpoint to append to the base URL for the request. | required |
data | Dict, optional | Data to be sent in the request's body. | None |
json | Dict, optional | JSON data to be sent in the request's body. | None |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP PATCH request. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef patch(self, endpoint: str, data: dict | None = None, json: dict | None = None) -> requests.Response | None:
"""Make a PATCH request to the API.
Args:
endpoint (str): The endpoint to append to the base URL for the request.
data (Dict, optional): Data to be sent in the request's body.
json (Dict, optional): JSON data to be sent in the request's body.
Returns:
(Optional[requests.Response]): The response object from the HTTP PATCH request.
"""
return self._make_request("PATCH", endpoint, data=data, json=json)
method hub_sdk.base.api_client.APIClient.post
def post(
self,
endpoint: str,
data: dict | None = None,
json: dict | None = None,
files: dict | None = None,
stream=False,
) -> requests.Response | None
Make a POST request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
endpoint | str | The endpoint to append to the base URL for the request. | required |
data | Dict, optional | Data to be sent in the request's body. | None |
json | Dict, optional | JSON data to be sent in the request's body. | None |
files | Dict, optional | Files to be included in the request. | None |
stream | bool | If True, the response content will be streamed. | False |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP POST request. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef post(
self,
endpoint: str,
data: dict | None = None,
json: dict | None = None,
files: dict | None = None,
stream=False,
) -> requests.Response | None:
"""Make a POST request to the API.
Args:
endpoint (str): The endpoint to append to the base URL for the request.
data (Dict, optional): Data to be sent in the request's body.
json (Dict, optional): JSON data to be sent in the request's body.
files (Dict, optional): Files to be included in the request.
stream (bool): If True, the response content will be streamed.
Returns:
(Optional[requests.Response]): The response object from the HTTP POST request.
"""
return self._make_request("POST", endpoint, data=data, json=json, files=files, stream=stream)
method hub_sdk.base.api_client.APIClient.put
def put(self, endpoint: str, data: dict | None = None, json: dict | None = None) -> requests.Response | None
Make a PUT request to the API.
Args
| Name | Type | Description | Default |
|---|---|---|---|
endpoint | str | The endpoint to append to the base URL for the request. | required |
data | Dict, optional | Data to be sent in the request's body. | None |
json | Dict, optional | JSON data to be sent in the request's body. | None |
Returns
| Type | Description |
|---|---|
Optional[requests.Response] | The response object from the HTTP PUT request. |
Source code in hub_sdk/base/api_client.py
View on GitHubdef put(self, endpoint: str, data: dict | None = None, json: dict | None = None) -> requests.Response | None:
"""Make a PUT request to the API.
Args:
endpoint (str): The endpoint to append to the base URL for the request.
data (Dict, optional): Data to be sent in the request's body.
json (Dict, optional): JSON data to be sent in the request's body.
Returns:
(Optional[requests.Response]): The response object from the HTTP PUT request.
"""
return self._make_request("PUT", endpoint, data=data, json=json)