Skip to content
Merged
Changes from 2 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
45 changes: 45 additions & 0 deletions src/posit/connect/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ def with_user_session_token(self, token: str) -> Client:
a user session token will not exist, which will cause this method to result in an error needing
to be handled in your application.

Depending on the type of application you are building, the user session token is retrieved in
a variety of ways. For example, in Streamlit and Shiny applications, the token is stored in the
context or session object headers using the `Posit-Connect-User-Session-Token` key. For API
applications, the token is added to the request headers.

Parameters
----------
token : str
Expand All @@ -192,10 +197,50 @@ def with_user_session_token(self, token: str) -> Client:
Client
A new Client instance authenticated with an API key exchanged for the user session token.

Raises
------
ValueError
If the provided token is `None` or empty or if the exchange response is malformed.
ClientError
If the token exchange request with the Connect Server fails.

Examples
--------
>>> from posit.connect import Client
>>> client = Client().with_user_session_token("my-user-session-token")

Example using user session token from Shiny session:
>>> from posit.connect import Client
>>> from shiny.express import render, session
>>>
>>> client = Client()
>>>
>>> @reactive.calc
>>> def visitor_client():
... ## read the user session token and generate a new client
... user_session_token = session.http_conn.headers.get(
... "Posit-Connect-User-Session-Token"
... )
... return client.with_user_session_token(user_session_token)
>>> @render.text
>>> def user_profile():
... # fetch the viewer's profile information
... return visitor_client().me

Example with fallback when header is missing in API request:
>>> from posit.connect import Client
>>> import requests
>>>
>>> def get_client(request):
... base_client = Client()
... token = request.headers.get("Posit-Connect-User-Session-Token")
... if token:
... return base_client.with_user_session_token(token)
... else:
... return base_client
>>> # Simulate request without header
>>> mock_request = requests.Request()
>>> client = get_client(mock_request) # Returns original client
"""
if token is None or token == "":
raise ValueError("token must be set to non-empty string.")
Expand Down
Loading