@@ -182,6 +182,11 @@ def with_user_session_token(self, token: str) -> Client:
182182 a user session token will not exist, which will cause this method to result in an error needing
183183 to be handled in your application.
184184
185+ Depending on the type of application you are building, the user session token is retrieved in
186+ a variety of ways. For example, in Streamlit and Shiny applications, the token is stored in the
187+ context or session object headers using the `Posit-Connect-User-Session-Token` key. For API
188+ applications, the token is added to the request headers.
189+
185190 Parameters
186191 ----------
187192 token : str
@@ -192,10 +197,50 @@ def with_user_session_token(self, token: str) -> Client:
192197 Client
193198 A new Client instance authenticated with an API key exchanged for the user session token.
194199
200+ Raises
201+ ------
202+ ValueError
203+ If the provided token is `None` or empty or if the exchange response is malformed.
204+ ClientError
205+ If the token exchange request with the Connect Server fails.
206+
195207 Examples
196208 --------
197209 >>> from posit.connect import Client
198210 >>> client = Client().with_user_session_token("my-user-session-token")
211+
212+ Example using user session token from Shiny session:
213+ >>> from posit.connect import Client
214+ >>> from shiny.express import render, session
215+ >>>
216+ >>> client = Client()
217+ >>>
218+ >>> @reactive.calc
219+ >>> def visitor_client():
220+ ... ## read the user session token and generate a new client
221+ ... user_session_token = session.http_conn.headers.get("Posit-Connect-User-Session-Token")
222+ ... return client.with_user_session_token(user_session_token)
223+ ...
224+ >>> @render.text
225+ >>> def user_profile():
226+ ... # fetch the viewer's profile information
227+ ... return visitor_client().me
228+
229+ Example with fallback when header is missing in API request:
230+ >>> from posit.connect import Client
231+ >>> import requests
232+ >>>
233+ >>> def get_client(request):
234+ ... base_client = Client()
235+ ... token = request.headers.get("Posit-Connect-User-Session-Token")
236+ ... if token:
237+ ... return base_client.with_user_session_token(token)
238+ ... else:
239+ ... return base_client
240+ ...
241+ >>> # Simulate request without header
242+ >>> mock_request = requests.Request()
243+ >>> client = get_client(mock_request) # Returns original client
199244 """
200245 if token is None or token == "" :
201246 raise ValueError ("token must be set to non-empty string." )
0 commit comments