Posit Connect Server API Cookbook

Version 2023.07.0

Introduction

This guide contains recipes for interacting with the 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 will need:

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

Your Posit Connect server URL is the same URL you use to access the Posit 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 chapter of the Posit Connect User Guide explains how to provision a Posit Connect API Key. We recommend that you create a Posit Connect API Key for each unique application that needs API access to Posit Connect.

Once you’ve provisioned a Posit Connect API Key, use environment variables to obtain the Posit 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 Posit Connect API Key.

Environments and Environment Variables

Configuring your Posit Connect server URL and API Key with environment variables gives you quite a bit of flexibility when deploying your code into different Posit 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 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 Posit 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 will obtain the Posit 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")

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 Posit Connect. The “Vars” tab in the Posit 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.

Sticky Sessions

Posit Connect can be deployed with multiple instances in a highly available, load-balanced configuration. The load balancer routing traffic to these Posit 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 Posit 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.

Posit Connect needs sticky sessions so 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.

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))
)
# ...

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": "Key %s" % 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)
# ...