Skip to content

feat: support short-lived tokens endpoint #517

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

Merged
merged 4 commits into from
Apr 14, 2025
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
30 changes: 30 additions & 0 deletions deepgram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,14 @@
# ErrorResponse,
)

# auth client classes
from .clients import AuthRESTClient, AsyncAuthRESTClient

# auth client responses
from .clients import (
GrantTokenResponse,
)

# manage client classes/input
from .clients import ManageClient, AsyncManageClient
from .clients import (
Expand Down Expand Up @@ -495,6 +503,20 @@ def asyncmanage(self):
"""
return self.Version(self._config, "asyncmanage")

@property
def auth(self):
"""
Returns an AuthRESTClient instance for managing short-lived tokens.
"""
return self.Version(self._config, "auth")

@property
def asyncauth(self):
"""
Returns an AsyncAuthRESTClient instance for managing short-lived tokens.
"""
return self.Version(self._config, "asyncauth")

@property
@deprecation.deprecated(
deprecated_in="3.4.0",
Expand Down Expand Up @@ -606,6 +628,14 @@ def v(self, version: str = ""):
parent = "selfhosted"
filename = "async_client"
classname = "AsyncSelfHostedClient"
case "auth":
parent = "auth"
filename = "client"
classname = "AuthRESTClient"
case "asyncauth":
parent = "auth"
filename = "async_client"
classname = "AsyncAuthRESTClient"
case _:
self._logger.error("parent unknown: %s", self._parent)
self._logger.debug("Version.v LEAVE")
Expand Down
6 changes: 6 additions & 0 deletions deepgram/clients/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@
Balance,
)

# auth
from .auth import AuthRESTClient, AsyncAuthRESTClient
from .auth import (
GrantTokenResponse,
)

# selfhosted
from .selfhosted import (
OnPremClient,
Expand Down
9 changes: 9 additions & 0 deletions deepgram/clients/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

from .client import AuthRESTClient
from .client import AsyncAuthRESTClient
from .client import (
GrantTokenResponse,
)
11 changes: 11 additions & 0 deletions deepgram/clients/auth/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

from .v1.client import AuthRESTClient as AuthRESTClientLatest
from .v1.async_client import AsyncAuthRESTClient as AsyncAuthRESTClientLatest
from .v1.response import GrantTokenResponse as GrantTokenResponseLatest

AuthRESTClient = AuthRESTClientLatest
AsyncAuthRESTClient = AsyncAuthRESTClientLatest
GrantTokenResponse = GrantTokenResponseLatest
8 changes: 8 additions & 0 deletions deepgram/clients/auth/v1/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT
from .client import AuthRESTClient
from .async_client import AsyncAuthRESTClient
from .response import (
GrantTokenResponse,
)
51 changes: 51 additions & 0 deletions deepgram/clients/auth/v1/async_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

import logging

from ....utils import verboselogs
from ....options import DeepgramClientOptions
from ...common import AbstractAsyncRestClient
from .response import GrantTokenResponse


class AsyncAuthRESTClient(AbstractAsyncRestClient):
"""
A client class for handling authentication endpoints.
Provides method for generating a temporary JWT token.
"""

_logger: verboselogs.VerboseLogger
_config: DeepgramClientOptions
_endpoint: str

def __init__(self, config: DeepgramClientOptions):
self._logger = verboselogs.VerboseLogger(__name__)
self._logger.addHandler(logging.StreamHandler())
self._logger.setLevel(config.verbose)
self._config = config
self._endpoint = "v1/auth/grant"
super().__init__(config)

async def grant_token(self):
"""
Generates a temporary JWT with a 30 second TTL.

Returns:
GrantTokenResponse: An object containing the authentication token and its expiration time.

Raises:
DeepgramTypeError: Raised for known API errors.
"""
self._logger.debug("AuthRestClient.grant_token ENTER")

url = f"{self._config.url}/{self._endpoint}"
self._logger.info("url: %s", url)
result = await self.post(url, headers={"Authorization": f"Token {self._config.api_key}"})
self._logger.info("json: %s", result)
res = GrantTokenResponse.from_json(result)
self._logger.verbose("result: %s", res)
self._logger.notice("grant_token succeeded")
self._logger.debug("AuthRestClient.grant_token LEAVE")
return res
51 changes: 51 additions & 0 deletions deepgram/clients/auth/v1/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Copyright 2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

import logging

from ....utils import verboselogs
from ....options import DeepgramClientOptions
from ...common import AbstractSyncRestClient
from .response import GrantTokenResponse


class AuthRESTClient(AbstractSyncRestClient):
"""
A client class for handling authentication endpoints.
Provides method for generating a temporary JWT token.
"""

_logger: verboselogs.VerboseLogger
_config: DeepgramClientOptions
_endpoint: str

def __init__(self, config: DeepgramClientOptions):
self._logger = verboselogs.VerboseLogger(__name__)
self._logger.addHandler(logging.StreamHandler())
self._logger.setLevel(config.verbose)
self._config = config
self._endpoint = "v1/auth/grant"
super().__init__(config)

def grant_token(self):
"""
Generates a temporary JWT with a 30 second TTL.

Returns:
GrantTokenResponse: An object containing the authentication token and its expiration time.

Raises:
DeepgramTypeError: Raised for known API errors.
"""
self._logger.debug("AuthRestClient.grant_token ENTER")

url = f"{self._config.url}/{self._endpoint}"
self._logger.info("url: %s", url)
result = self.post(url, headers={"Authorization": f"Token {self._config.api_key}"})
self._logger.info("json: %s", result)
res = GrantTokenResponse.from_json(result)
self._logger.verbose("result: %s", res)
self._logger.notice("grant_token succeeded")
self._logger.debug("AuthRestClient.grant_token LEAVE")
return res
24 changes: 24 additions & 0 deletions deepgram/clients/auth/v1/response.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

from dataclasses import dataclass, field
from dataclasses_json import config as dataclass_config

from ...common import (
BaseResponse,
)

@dataclass
class GrantTokenResponse(BaseResponse):
"""
The response object for the authentication grant token endpoint.
"""
access_token: str = field(
metadata=dataclass_config(field_name='access_token'),
default="",
)
expires_in: int = field(
metadata=dataclass_config(field_name='expires_in'),
default=30,
)
33 changes: 33 additions & 0 deletions examples/auth/async_token/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

import asyncio
import os
from dotenv import load_dotenv
from deepgram.utils import verboselogs

from deepgram import (
DeepgramClient,
DeepgramClientOptions
)

load_dotenv()

async def main():
try:
# STEP 1 Create a Deepgram client using the DEEPGRAM_API_KEY from your environment variables
config = DeepgramClientOptions(
verbose=verboselogs.SPAM,
)
deepgram: DeepgramClient = DeepgramClient(os.getenv("DEEPGRAM_API_KEY", ""), config)

# STEP 2 Call the grant_token method on the auth rest class
response = await deepgram.asyncauth.v("1").grant_token()
print(f"response: {response}\n\n")
except Exception as e:
print(f"Exception: {e}")


if __name__ == "__main__":
asyncio.run(main())
32 changes: 32 additions & 0 deletions examples/auth/token/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Copyright 2023-2024 Deepgram SDK contributors. All Rights Reserved.
# Use of this source code is governed by a MIT license that can be found in the LICENSE file.
# SPDX-License-Identifier: MIT

import os
from dotenv import load_dotenv
from deepgram.utils import verboselogs

from deepgram import (
DeepgramClient,
DeepgramClientOptions
)

load_dotenv()

def main():
try:
# STEP 1 Create a Deepgram client using the DEEPGRAM_API_KEY from your environment variables
config = DeepgramClientOptions(
verbose=verboselogs.SPAM,
)
deepgram: DeepgramClient = DeepgramClient(os.getenv("DEEPGRAM_API_KEY", ""), config)

# STEP 2 Call the grant_token method on the auth rest class
response = deepgram.auth.v("1").grant_token()
print(f"response: {response}\n\n")
except Exception as e:
print(f"Exception: {e}")


if __name__ == "__main__":
main()