-
Notifications
You must be signed in to change notification settings - Fork 0
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
Migrate to platform APIs #47
Open
denizs
wants to merge
10
commits into
master
Choose a base branch
from
major/migrate-to-platform-apis
base: master
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.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
00a0346
constants: add PLATFORM_API_SUB_PATH
denizs 37646d7
fmt: unify ENLYZE platform capitalization
denizs 4fbc308
auth: use Bearer auth scheme
denizs 029bc8c
add api_client package implementing PlatformApiClient scaffold
denizs 664558d
api_client/models: unify api_clients.*.models
denizs 14288fc
models: move from site id to uuid
denizs 4761551
adapt EnlyzeClient to use PlatformApiClient
denizs 867fc26
remove api_clients packages
denizs 62bf4cd
adapt docs
denizs 24a321c
fix datetime before today strategy
denizs 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 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,9 @@ | ||
Platform API Client | ||
========================== | ||
|
||
.. currentmodule:: enlyze.api_client.client | ||
|
||
.. autoclass:: _PaginatedResponse | ||
|
||
.. autoclass:: PlatformApiClient() | ||
:members: |
File renamed without changes.
31 changes: 28 additions & 3 deletions
31
docs/api_clients/production_runs/models.rst → docs/api_client/models.rst
This file contains 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
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains 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 |
---|---|---|
|
@@ -20,4 +20,4 @@ User's Guide | |
models | ||
errors | ||
constants | ||
api_clients/index | ||
api_client/index |
File renamed without changes.
This file contains 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,157 @@ | ||
import json | ||
from functools import cache | ||
from http import HTTPStatus | ||
from typing import Any, Iterator, Type, TypeVar | ||
|
||
import httpx | ||
from pydantic import BaseModel, ValidationError | ||
|
||
from enlyze._version import VERSION | ||
from enlyze.auth import TokenAuth | ||
from enlyze.constants import HTTPX_TIMEOUT, PLATFORM_API_SUB_PATH, USER_AGENT | ||
from enlyze.errors import EnlyzeError, InvalidTokenError | ||
|
||
from .models import PlatformApiModel | ||
|
||
T = TypeVar("T", bound=PlatformApiModel) | ||
|
||
USER_AGENT_NAME_VERSION_SEPARATOR = "/" | ||
|
||
|
||
@cache | ||
def _construct_user_agent( | ||
*, user_agent: str = USER_AGENT, version: str = VERSION | ||
) -> str: | ||
return f"{user_agent}{USER_AGENT_NAME_VERSION_SEPARATOR}{version}" | ||
|
||
|
||
class _Metadata(BaseModel): | ||
next_cursor: str | None | ||
|
||
|
||
class _PaginatedResponse(BaseModel): | ||
metadata: _Metadata | ||
data: list[dict[str, Any]] | dict[str, Any] | ||
|
||
|
||
class PlatformApiClient: | ||
"""Client class encapsulating all interaction with the ENLYZE platform API | ||
|
||
:param token: API token for the ENLYZE platform API | ||
:param base_url: Base URL of the ENLYZE platform API | ||
:param timeout: Global timeout for all HTTP requests sent to the ENLYZE platform API | ||
|
||
""" | ||
|
||
def __init__( | ||
self, | ||
*, | ||
token: str, | ||
base_url: str | httpx.URL, | ||
timeout: float = HTTPX_TIMEOUT, | ||
): | ||
self._client = httpx.Client( | ||
auth=TokenAuth(token), | ||
base_url=httpx.URL(base_url).join(PLATFORM_API_SUB_PATH), | ||
timeout=timeout, | ||
headers={"user-agent": _construct_user_agent()}, | ||
) | ||
|
||
@cache | ||
def _full_url(self, api_path: str) -> str: | ||
"""Construct full URL from relative URL""" | ||
return str(self._client.build_request("", api_path).url) | ||
|
||
def get(self, api_path: str, **kwargs: Any) -> Any: | ||
"""Wraps :meth:`httpx.Client.get` with defensive error handling | ||
|
||
:param api_path: Relative URL path inside the API name space (or a full URL) | ||
|
||
:raises: :exc:`~enlyze.errors.EnlyzeError` on request failure | ||
|
||
:raises: :exc:`~enlyze.errors.EnlyzeError` on non-2xx status code | ||
|
||
:raises: :exc:`~enlyze.errors.EnlyzeError` on non-JSON payload | ||
|
||
:returns: JSON payload of the response as Python object | ||
|
||
""" | ||
try: | ||
response = self._client.get(api_path, **kwargs) | ||
except Exception as e: | ||
print(e) | ||
raise EnlyzeError( | ||
"Couldn't read from the ENLYZE platform API " | ||
f"(GET {self._full_url(api_path)})", | ||
) from e | ||
|
||
try: | ||
response.raise_for_status() | ||
except httpx.HTTPStatusError as e: | ||
if e.response.status_code in ( | ||
HTTPStatus.UNAUTHORIZED, | ||
HTTPStatus.FORBIDDEN, | ||
): | ||
raise InvalidTokenError | ||
else: | ||
raise EnlyzeError( | ||
f"ENLYZE platform API returned error {response.status_code}" | ||
f" (GET {self._full_url(api_path)})" | ||
) from e | ||
|
||
try: | ||
return response.json() | ||
except json.JSONDecodeError as e: | ||
raise EnlyzeError( | ||
"ENLYZE platform API didn't return a valid JSON object " | ||
f"(GET {self._full_url(api_path)})", | ||
) from e | ||
|
||
def get_paginated( | ||
self, api_path: str, model: Type[T], **kwargs: Any | ||
) -> Iterator[T]: | ||
"""Retrieve objects from paginated ENLYZE Platform API endpoint via HTTP GET | ||
|
||
:param api_path: Relative URL path inside the ENLYZE Platform API | ||
:param model: Class derived from | ||
:class:`~enlyze.api_client.models.PlatformApiModel` | ||
:raises: :exc:`~enlyze.errors.EnlyzeError` on invalid pagination schema | ||
:raises: :exc:`~enlyze.errors.EnlyzeError` on invalid data schema | ||
:raises: see :py:meth:`get` for more errors raised by this method | ||
:returns: Instances of ``model`` retrieved from the ``api_path`` endpoint | ||
""" | ||
|
||
params = kwargs.pop("params", {}) | ||
|
||
while True: | ||
response_body = self.get(api_path, params=params, **kwargs) | ||
|
||
try: | ||
paginated_response = _PaginatedResponse.model_validate(response_body) | ||
except ValidationError as e: | ||
raise EnlyzeError( | ||
f"Paginated response expected (GET {self._full_url(api_path)})" | ||
) from e | ||
|
||
page_data = paginated_response.data | ||
if not page_data: | ||
break | ||
|
||
# if `data` is a list we assume there are multiple objects inside. | ||
# if `data` is a dict then we treat it as only one object | ||
page_data = page_data if isinstance(page_data, list) else [page_data] | ||
|
||
for elem in page_data: | ||
try: | ||
yield model.model_validate(elem) | ||
except ValidationError as e: | ||
raise EnlyzeError( | ||
f"ENLYZE platform API returned an unparsable {model.__name__} " | ||
f"object (GET {self._full_url(api_path)})" | ||
) from e | ||
|
||
next_cursor = paginated_response.metadata.next_cursor | ||
if next_cursor is None: | ||
break | ||
|
||
params = {**params, "cursor": next_cursor} |
Oops, something went wrong.
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.
This is the synthesis of the previously single client prior to the introduction of Production Runs.