Skip to content
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

feat(api): update via SDK Studio #19

Merged
merged 1 commit into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ from honcho import Honcho

client = Honcho(
# This is the default and can be omitted
api_key=os.environ.get("HONCHO_AUTH_TOKEN"),
api_key=os.environ.get("HONCHO_API_KEY"),
# defaults to "local".
environment="demo",
)
Expand All @@ -42,7 +42,7 @@ print(app.id)

While you can provide an `api_key` keyword argument,
we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
to add `HONCHO_AUTH_TOKEN="My API Key"` to your `.env` file
to add `HONCHO_API_KEY="My API Key"` to your `.env` file
so that your API Key is not stored in source control.

## Async usage
Expand All @@ -56,7 +56,7 @@ from honcho import AsyncHoncho

client = AsyncHoncho(
# This is the default and can be omitted
api_key=os.environ.get("HONCHO_AUTH_TOKEN"),
api_key=os.environ.get("HONCHO_API_KEY"),
# defaults to "local".
environment="demo",
)
Expand Down
49 changes: 34 additions & 15 deletions src/honcho/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from ._types import (
NOT_GIVEN,
Omit,
Headers,
Timeout,
NotGiven,
Transport,
Expand All @@ -25,7 +26,7 @@
)
from ._version import __version__
from ._streaming import Stream as Stream, AsyncStream as AsyncStream
from ._exceptions import HonchoError, APIStatusError
from ._exceptions import APIStatusError
from ._base_client import (
DEFAULT_MAX_RETRIES,
SyncAPIClient,
Expand Down Expand Up @@ -57,7 +58,7 @@ class Honcho(SyncAPIClient):
with_streaming_response: HonchoWithStreamedResponse

# client options
api_key: str
api_key: str | None

_environment: Literal["local", "demo"] | NotGiven

Expand Down Expand Up @@ -87,14 +88,10 @@ def __init__(
) -> None:
"""Construct a new synchronous honcho client instance.

This automatically infers the `api_key` argument from the `HONCHO_AUTH_TOKEN` environment variable if it is not provided.
This automatically infers the `api_key` argument from the `HONCHO_API_KEY` environment variable if it is not provided.
"""
if api_key is None:
api_key = os.environ.get("HONCHO_AUTH_TOKEN")
if api_key is None:
raise HonchoError(
"The api_key client option must be set either by passing api_key to the client or by setting the HONCHO_AUTH_TOKEN environment variable"
)
api_key = os.environ.get("HONCHO_API_KEY")
self.api_key = api_key

self._environment = environment
Expand Down Expand Up @@ -147,6 +144,8 @@ def qs(self) -> Querystring:
@override
def auth_headers(self) -> dict[str, str]:
api_key = self.api_key
if api_key is None:
return {}
return {"Authorization": f"Bearer {api_key}"}

@property
Expand All @@ -158,6 +157,17 @@ def default_headers(self) -> dict[str, str | Omit]:
**self._custom_headers,
}

@override
def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None:
if self.api_key and headers.get("Authorization"):
return
if isinstance(custom_headers.get("Authorization"), Omit):
return

raise TypeError(
'"Could not resolve authentication method. Expected the api_key to be set. Or for the `Authorization` headers to be explicitly omitted"'
)

def copy(
self,
*,
Expand Down Expand Up @@ -251,7 +261,7 @@ class AsyncHoncho(AsyncAPIClient):
with_streaming_response: AsyncHonchoWithStreamedResponse

# client options
api_key: str
api_key: str | None

_environment: Literal["local", "demo"] | NotGiven

Expand Down Expand Up @@ -281,14 +291,10 @@ def __init__(
) -> None:
"""Construct a new async honcho client instance.

This automatically infers the `api_key` argument from the `HONCHO_AUTH_TOKEN` environment variable if it is not provided.
This automatically infers the `api_key` argument from the `HONCHO_API_KEY` environment variable if it is not provided.
"""
if api_key is None:
api_key = os.environ.get("HONCHO_AUTH_TOKEN")
if api_key is None:
raise HonchoError(
"The api_key client option must be set either by passing api_key to the client or by setting the HONCHO_AUTH_TOKEN environment variable"
)
api_key = os.environ.get("HONCHO_API_KEY")
self.api_key = api_key

self._environment = environment
Expand Down Expand Up @@ -341,6 +347,8 @@ def qs(self) -> Querystring:
@override
def auth_headers(self) -> dict[str, str]:
api_key = self.api_key
if api_key is None:
return {}
return {"Authorization": f"Bearer {api_key}"}

@property
Expand All @@ -352,6 +360,17 @@ def default_headers(self) -> dict[str, str | Omit]:
**self._custom_headers,
}

@override
def _validate_headers(self, headers: Headers, custom_headers: Headers) -> None:
if self.api_key and headers.get("Authorization"):
return
if isinstance(custom_headers.get("Authorization"), Omit):
return

raise TypeError(
'"Could not resolve authentication method. Expected the api_key to be set. Or for the `Authorization` headers to be explicitly omitted"'
)

def copy(
self,
*,
Expand Down
33 changes: 26 additions & 7 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
from pydantic import ValidationError

from honcho import Honcho, AsyncHoncho, APIResponseValidationError
from honcho._types import Omit
from honcho._models import BaseModel, FinalRequestOptions
from honcho._constants import RAW_RESPONSE_HEADER
from honcho._exceptions import HonchoError, APIStatusError, APITimeoutError, APIResponseValidationError
from honcho._exceptions import APIStatusError, APITimeoutError, APIResponseValidationError
from honcho._base_client import DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, make_request_options

from .utils import update_env
Expand Down Expand Up @@ -326,9 +327,18 @@ def test_validate_headers(self) -> None:
request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("Authorization") == f"Bearer {api_key}"

with pytest.raises(HonchoError):
client2 = Honcho(base_url=base_url, api_key=None, _strict_response_validation=True)
_ = client2
client2 = Honcho(base_url=base_url, api_key=None, _strict_response_validation=True)

with pytest.raises(
TypeError,
match="Could not resolve authentication method. Expected the api_key to be set. Or for the `Authorization` headers to be explicitly omitted",
):
client2._build_request(FinalRequestOptions(method="get", url="/foo"))

request2 = client2._build_request(
FinalRequestOptions(method="get", url="/foo", headers={"Authorization": Omit()})
)
assert request2.headers.get("Authorization") is None

def test_default_query_option(self) -> None:
client = Honcho(
Expand Down Expand Up @@ -1017,9 +1027,18 @@ def test_validate_headers(self) -> None:
request = client._build_request(FinalRequestOptions(method="get", url="/foo"))
assert request.headers.get("Authorization") == f"Bearer {api_key}"

with pytest.raises(HonchoError):
client2 = AsyncHoncho(base_url=base_url, api_key=None, _strict_response_validation=True)
_ = client2
client2 = AsyncHoncho(base_url=base_url, api_key=None, _strict_response_validation=True)

with pytest.raises(
TypeError,
match="Could not resolve authentication method. Expected the api_key to be set. Or for the `Authorization` headers to be explicitly omitted",
):
client2._build_request(FinalRequestOptions(method="get", url="/foo"))

request2 = client2._build_request(
FinalRequestOptions(method="get", url="/foo", headers={"Authorization": Omit()})
)
assert request2.headers.get("Authorization") is None

def test_default_query_option(self) -> None:
client = AsyncHoncho(
Expand Down