Skip to content
Open
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ This is an autogenerated python SDK for OpenFGA. It provides a wrapper around th
- [Write Assertions](#write-assertions)
- [Calling Other Endpoints](#calling-other-endpoints)
- [Retries](#retries)
- [Redirects](#redirects)
- [API Endpoints](#api-endpoints)
- [Models](#models)
- [OpenTelemetry](#opentelemetry)
Expand Down Expand Up @@ -1413,6 +1414,17 @@ async def main():
```


### Redirects

By default the SDK follows HTTP redirects returned by the server, as aiohttp and urllib3 do. If your FGA server is not expected to redirect, you can turn this off with `follow_redirects=False`, so a 3xx response is raised as an `ApiException` with the status code instead of the request being sent to the new location. aiohttp and urllib3 already drop the `Authorization` header on cross-host redirects, but a 307/308 from the token endpoint would still forward the client secret, and any custom headers go along too. It applies to token requests too.

```python
config = ClientConfiguration(
api_url=environ.get("FGA_API_URL"),
follow_redirects=False,
)
```

### Error Handling

The SDK provides comprehensive error handling with detailed error information and convenient helper methods.
Expand Down
8 changes: 5 additions & 3 deletions openfga_sdk/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ async def __call_api(
)
except (RateLimitExceededError, ServiceException) as e:
_telemetry_attributes = TelemetryAttributes.fromResponse(
response=e.body.decode("utf-8"),
response=bytes(e.body or b"").decode("utf-8", errors="replace"),
credentials=self.configuration.credentials,
attributes=_telemetry_attributes,
start=start,
Expand All @@ -317,7 +317,8 @@ async def __call_api(
await asyncio.sleep(wait_time_in_sec)

continue
e.body = e.body.decode("utf-8")
if isinstance(e.body, (bytes, bytearray)):
e.body = bytes(e.body).decode("utf-8", errors="replace")
response_type = response_types_map.get(e.status, None)
if response_type is not None:
e.parsed_exception = self.__deserialize(
Expand Down Expand Up @@ -359,7 +360,8 @@ async def __call_api(

continue
except ApiException as e:
e.body = e.body.decode("utf-8")
if isinstance(e.body, (bytes, bytearray)):
e.body = bytes(e.body).decode("utf-8", errors="replace")
response_type = response_types_map.get(e.status, None)
if response_type is not None:
e.parsed_exception = self.__deserialize(
Expand Down
2 changes: 2 additions & 0 deletions openfga_sdk/client/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def __init__(
| None
) = None,
headers: dict[str, str] | None = None,
follow_redirects: bool = True,
):
super().__init__(
api_scheme,
Expand All @@ -54,6 +55,7 @@ def __init__(
timeout_millisec=timeout_millisec,
telemetry=telemetry,
headers=headers,
follow_redirects=follow_redirects,
)
self._authorization_model_id = authorization_model_id

Expand Down
12 changes: 12 additions & 0 deletions openfga_sdk/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ class Configuration:
in PEM format
:param api_url: str - the URL of the FGA server
:param timeout_millisec: int | None - the default timeout in milliseconds for requests
:param follow_redirects: bool - whether to follow HTTP redirects from the server.
Defaults to True. When False, a 3xx response is raised as an ApiException.
"""

_default = None
Expand Down Expand Up @@ -202,6 +204,7 @@ def __init__(
) = None,
timeout_millisec: int | None = None,
headers: dict[str, str] | None = None,
follow_redirects: bool = True,
):
"""Constructor"""
self._url = api_url
Expand All @@ -216,6 +219,10 @@ def __init__(
self._retry_params = RetryParams()

self._timeout_millisec = timeout_millisec or 5000 * 60
self.follow_redirects = follow_redirects
"""Follow HTTP redirects returned by the server. When False, a 3xx
response is raised as an ApiException instead of being followed.
"""
"""Default Base url
"""
self.server_index = 0
Expand Down Expand Up @@ -658,6 +665,11 @@ def is_valid(self):
f"timeout_millisec not within reasonable range (0,60000), {self._timeout_millisec}"
)

if not isinstance(self.follow_redirects, bool):
raise FgaValidationException(
f"follow_redirects must be a bool, got {type(self.follow_redirects).__name__}"
)

if self._headers is not None:
for key, value in self._headers.items():
if not isinstance(key, str):
Expand Down
4 changes: 4 additions & 0 deletions openfga_sdk/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ def __init__(
self.proxy = configuration.proxy
self.proxy_headers = configuration.proxy_headers
self._timeout_millisec = configuration.timeout_millisec
self._follow_redirects = (
getattr(configuration, "follow_redirects", True) is not False
)
self.pool_manager = aiohttp.ClientSession(connector=connector, trust_env=True)
# aiohttp 3.10+ resends GET, HEAD, PUT and DELETE once by itself when a
# kept-alive connection drops. Turn that off, as aiohttp.test_utils does,
Expand Down Expand Up @@ -223,6 +226,7 @@ async def build_request(
"url": url,
"timeout": timeout,
"headers": headers,
"allow_redirects": self._follow_redirects,
Comment thread
cvas22 marked this conversation as resolved.
Resolved
}

if self.proxy:
Expand Down
8 changes: 5 additions & 3 deletions openfga_sdk/sync/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ def __call_api(
)
except (RateLimitExceededError, ServiceException) as e:
_telemetry_attributes = TelemetryAttributes.fromResponse(
response=e.body.decode("utf-8"),
response=bytes(e.body or b"").decode("utf-8", errors="replace"),
credentials=self.configuration.credentials,
attributes=_telemetry_attributes,
start=start,
Expand All @@ -314,7 +314,8 @@ def __call_api(

time.sleep(wait_time_in_sec)
continue
e.body = e.body.decode("utf-8")
if isinstance(e.body, (bytes, bytearray)):
e.body = bytes(e.body).decode("utf-8", errors="replace")
response_type = response_types_map.get(e.status, None)
if response_type is not None:
e.parsed_exception = self.__deserialize(
Expand Down Expand Up @@ -351,7 +352,8 @@ def __call_api(
time.sleep(min(random_time(retry, min_wait_in_ms), max_wait_in_sec))
continue
except ApiException as e:
e.body = e.body.decode("utf-8")
if isinstance(e.body, (bytes, bytearray)):
e.body = bytes(e.body).decode("utf-8", errors="replace")
response_type = response_types_map.get(e.status, None)
if response_type is not None:
e.parsed_exception = self.__deserialize(
Expand Down
4 changes: 4 additions & 0 deletions openfga_sdk/sync/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,9 @@ def __init__(
maxsize = 4

self._timeout_millisec = configuration.timeout_millisec
self._follow_redirects = (
getattr(configuration, "follow_redirects", True) is not False
)

if hasattr(configuration, "proxy") and configuration.proxy is not None:
self.pool_manager: urllib3.ProxyManager | urllib3.PoolManager = (
Expand Down Expand Up @@ -287,6 +290,7 @@ def build_request(
"timeout": timeout,
"headers": headers,
"preload_content": _preload_content,
"redirect": self._follow_redirects,
}

if query_params:
Expand Down
2 changes: 1 addition & 1 deletion openfga_sdk/telemetry/attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def fromResponse(
response.status
)

if response.body is not None:
if isinstance(response.body, dict):
response_model_id = response.body.get(
"openfga-authorization-model-id"
) or response.body.get("openfga_authorization_model_id")
Expand Down
Loading