Posit Connect Server API Cookbook

Version 2024.03.0

Introduction

This guide contains recipes for interacting with the Posit Connect Server API from code. The recipes are intended to be straightforward enough to be implemented in any programming language you wish to use.

Getting started

You need:

  • The URL for your Connect server
  • A Connect API Key for your account on the server

Your Connect server URL is the same URL you use to access the Connect dashboard, minus the connect path. If you access the dashboard at https://rsc.company.com/connect/, the server URL is https://rsc.company.com/.

The API Keys section of the Posit Connect User Guide explains how to provision a Connect API Key. We recommend using a different Connect API Key for each unique application that needs API access to Connect.

Once you’ve provisioned a Connect API Key, use environment variables to obtain the Connect server URL and API Key. Environment variables keep the literal URL and Key values from your source code, meaning you can share that code without worrying about accidentally sharing your Connect API Key.

Environments and environment variables

Configuring your Connect server URL and API Key with environment variables gives you quite a bit of flexibility when deploying your code into different Connect servers running in different environments.

Code that loads the server URL and API Key from environment variables can be used in development, staging, or production environments. The same code can run in all three environments.

Setup for Python

You can configure environment variables in development via your operating system’s features.

For Mac or Linux:

# ~/.bashrc
# The CONNECT_SERVER URL must have a trailing slash.
CONNECT_SERVER="https://rsc.company.com/"
CONNECT_API_KEY="mysupersecretapikey"

Give these environment variables values when code is deployed to Connect. The Vars tab in the Connect dashboard lets you configure environment variables for each piece of content. The Environment Variables section of the Posit Connect User Guide discusses how to use the Vars tab to configure environment variables.

Setup for R

Use .Renviron files to configure environment variables in development.

Here is a sample .Renviron file that you can use in your development environment. It defines Connect the server URL and API Key you use while developing. The .Renviron file is loaded by every R session spawned under your user account.

# ~/.Renviron
# The CONNECT_SERVER URL must have a trailing slash.
CONNECT_SERVER="https://rsc.company.com/"
CONNECT_API_KEY="mysupersecretapikey"

Your code obtains the Connect server URL and API Key from the environment. The Sys.getenv function lets us load environment variables in R.

connectServer <- Sys.getenv("CONNECT_SERVER")
connectAPIKey <- Sys.getenv("CONNECT_API_KEY")

Sticky sessions

Connect can be deployed with multiple instances in a highly available, load-balanced configuration. The load balancer routing traffic to these Connect servers must be configured with sticky sessions using session cookies.

Note

The High Availability and Load Balancing chapter of the Posit Connect Admin Guide provides details about running a cluster of Connect instances.

Sticky Session cookies are returned by the load balancer to a client with the first HTTP response. The client adds that cookie to all subsequent requests. The load balancer uses session cookies to determine what server should receive the incoming request.

Connect needs sticky sessions so that requests from the same client can be routed to the same server. This is how your browser maintains connectivity to the server running an application on your behalf.

curl

The curl command-line utility can use an on-disk cookie jar to receive and send HTTP cookies, including those used for sticky sessions. The -c and --cookie-jar options tell curl to write cookies to the named file. The -b and --cookie options tell curl to read cookies from that file.

#
# Write cookies from our first request.
curl -c cookie-jar.txt \
    -H "Authorization: Key ${CONNECT_API_KEY}" \
    "http://rsc.company.com/content/24/mean?samples=5"
# Use those session cookies later.
curl -b cookie-jar.txt \
    -H "Authorization: Key ${CONNECT_API_KEY}" \
    "http://rsc.company.com/content/24/mean?samples=5"

The Cookies chapter of the Everything curl book has more information about using cookies with curl.

Python3 with urllib

The http.cookiejar package is part of the Python3 standard library. This is a basic example that retains cookies in-memory within a Python process.

import http.cookiejar
import json
import os
import urllib.parse
import urllib.request

connect_server = os.getenv("CONNECT_SERVER")
connect_api_key = os.getenv("CONNECT_API_KEY")

def build_url(base, path, **kwargs):
    query = urllib.parse.urlencode(kwargs)
    parts = urllib.parse.urlparse(base)
    parts = parts._replace(path = path, query = query)
    return parts.geturl()

jar = http.cookiejar.CookieJar()
processor = urllib.request.HTTPCookieProcessor(jar)
opener = urllib.request.build_opener(processor)

headers = { "Authorization": f"Key {connect_api_key}" }

# The initial request using the cookie jar will have no HTTP session cookies.
request_url = build_url(connect_server, "/content/24/mean", samples = 5)
request = urllib.request.Request(request_url, headers = headers)
response = opener.open(request)
# ...

# Later requests retain cookies set by the previous request.
request_url = build_url(connect_server, "/content/24/mean", samples = 10)
request = urllib.request.Request(request_url, headers = headers)
response = opener.open(request)
# ...

Python3 with requests

The requests library is another common tool used to perform HTTP operations in Python. It uses Session objects to persist cookies across requests. This is a basic example that retains cookies in-memory within a Python process using the requests library.


import os
import requests

connect_server = os.getenv("CONNECT_SERVER")
connect_api_key = os.getenv("CONNECT_API_KEY")

session = requests.Session()
session.headers.update({ "Authorization": f"Key {connect_api_key}" })

# The initial request using the Session will have no HTTP session cookies.
response = session.get(
    f"{connect_server}/content/24/mean?samples=5",
)
# ...

# Later requests retain cookies set by the previous request.
response = session.get(
    f"{connect_server}/content/24/mean?samples=5",
)

R with httr

The httr R package automatically maintains cookies across requests within an R session. No additional code is needed.

library(httr)

connectServer <- Sys.getenv("CONNECT_SERVER")
connectAPIKey <- Sys.getenv("CONNECT_API_KEY")

# The initial request in an R session will have no HTTP session cookies.
resp <- httr::GET(connectServer, 
  path = "/content/24/mean",
  query = list(samples = 5),
  add_headers(Authorization = paste("Key", connectAPIKey))
)
# ...

# Later requests retain cookies set by the previous request.
resp <- httr::GET(connectServer, 
  path = "/content/24/mean",
  query = list(samples = 10),
  add_headers(Authorization = paste("Key", connectAPIKey))
)
# ...