@@ -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,56 @@ 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 --------
197- >>> from posit.connect import Client
198- >>> client = Client().with_user_session_token("my-user-session-token")
209+ ```python
210+ from posit.connect import Client
211+ client = Client().with_user_session_token("my-user-session-token")
212+ ```
213+
214+ Example using user session token from Shiny session:
215+ ```python
216+ from posit.connect import Client
217+ from shiny.express import render, session
218+
219+ client = Client()
220+
221+ @reactive.calc
222+ def visitor_client():
223+ ## read the user session token and generate a new client
224+ user_session_token = session.http_conn.headers.get(
225+ "Posit-Connect-User-Session-Token"
226+ )
227+ return client.with_user_session_token(user_session_token)
228+ @render.text
229+ def user_profile():
230+ # fetch the viewer's profile information
231+ return visitor_client().me
232+ ```
233+
234+ Example of when the visitor's token could not be retrieved (for
235+ example, if this app allows unauthenticated access) and handle
236+ that in cases where a token is expected.
237+ ```python
238+ from posit.connect import Client
239+ import requests
240+
241+ # Simulate request without header
242+ mock_request = requests.Request()
243+ visitor_client = None
244+ token = request.headers.get("Posit-Connect-User-Session-Token")
245+ if token:
246+ visitor_client = Client().with_user_session_token(token)
247+ else:
248+ print("This app requires a user session token to operate.")
249+ ```
199250 """
200251 if token is None or token == "" :
201252 raise ValueError ("token must be set to non-empty string." )
0 commit comments