Accessing Content via API

API Keys

API Keys allow you to programmatically access content on Posit Connect and use the Connect Server API. They are a substitute for logging in to Connect to publish or access content.

All accounts types are able to use API Keys, though the set of allowable operations varies according to the type of account and content sharing settings. Some example uses:

  • Users with administrator accounts can use the Connect Server API to understand which users have logged into Connect.
  • Folks with publisher accounts can use rsconnect-python to publish Shiny applications to Connect.
  • Someone with a viewer account can write code to download data sets from a pin published by one of their colleagues.

An API Key is associated with the user who creates it. API Keys are not associated with any specific content item. API Keys allow access to the Connect Server API and also to published content. Your API key has the same rights and permissions as you. If you are able to visit some content using the Connect dashboard, your API Key can be used to programmatically interact with that same content.

It is a recommended practice to create a new API Key for each external tool that needs access to content hosted on Connect, and to give each Key a name that helps you identify the tool that uses it. When the tool no longer needs access, or if you cannot trust the Key at any time, you can quickly revoke access by deleting the Key.

Note to administrators

API Keys need to be allowed through an authentication proxy in order to reach Connect. The Proxied Authentication section of the Posit Connect Admin Guide has more information about adding API Key support to your proxy.

Note that RStudio handles authentication differently. For more information on connecting with the RStudio, see the Publishing from RStudio page.

To access content with an API Key, you must provide an HTTP header whose Key is Authorization and value is Key THE_API_KEY. The X-RSC-Authorization header is also accepted in a similar fashion.

All requests to content must be made to the target URL of the published content. You can find the target URL by clicking the Open Solo button in the upper-right of the Content View page. (Note: on narrow screens, the Open Solo button might be located in the menu in the upper-right of the Content View.)

Open Solo button.

Creating and deleting an API Key

To create an API Key, click on the circular picture in the top-right portion of the screen. The picture might have your username next to it if you are viewing Posit Connect on a large screen.

User menu with Profile, API Keys, and Logout items.

Click API Keys in the menu that appears. This takes you to the API Keys page.

API Keys page showing no API Keys created.

On the API Keys page, click New API Key and follow the prompt to name your API Key.

Dialog titled Create API Key with the name 'my_api_key' entered.

After creating an API Key, you can view the Key and are given an opportunity to put it in a safe location. Once you close the dialog, you will not be shown the API Key again. This helps to keep your user account safe.

A created API Key.

If you have lost an API Key, or if you simply don’t need to use the API Key anymore, remove the API Key by clicking the trash bin icon on the far right column of the API Key list.

API Key list showing 'my_api_key' and a trash bin icon.

When you click the trash bin icon, Connect prompts you to confirm that you want to delete the API Key. Successfully deleting the API Key shows a green status message at the top of the screen.

Using an API Key

This section contains examples of how to use API Keys to obtain or interact with content deployed to Posit Connect. These examples assume that your Posit Connect API Key is available in the environment variable CONNECT_API_KEY.

export CONNECT_API_KEY=q9R4ylb3K3RPB7AB46il8mxjjcYsaClW

The examples in this section use the curl command-line utility to perform basic authenticated API Key requests against content hosted by Posit Connect.

The API Keys from Code section shows how to make these same requests from Python and R. The Connect Server API Cookbook contains recipes which interact with the Connect Server API using API Keys.

Static content

You can use API Keys to download resources associated with static content (plots and previously rendered HTML).

Assume you have published a plot to Posit Connect and it has the URL: http://rsc.company.com/content/24/target.html.

Download this content using your API Key and the curl command-line program:

curl -O -H "Authorization: Key ${CONNECT_API_KEY}" \
    "http://rsc.company.com/content/24/target.html"

The -O option tells curl to write a file named by the remote filename. In this case, it would write to the target.html file.

Write to a different filename (output.html in this example) using the -o option:

curl -o output.html -H "Authorization: Key ${CONNECT_API_KEY}" \
    "http://rsc.company.com/content/24/target.html"

Plumber

You can use API Keys to interact with a Plumber API.

Using the plumber API definition:

## plumber.R

#* @get /mean
normalMean <- function(samples=10){
  data <- rnorm(samples)
  mean(data)
}

The function normalMean is exposed through the /mean endpoint. It takes an optional samples query argument.

Assume this Plumber API is available on Posit Connect with the URL: http://rsc.company.com/content/24/.

You can call this API using an API Key and the curl command-line program:

curl -H "Authorization: Key ${CONNECT_API_KEY}" \
    "http://rsc.company.com/content/24/mean?samples=5"

Using API Keys from code

The Plumber and static content examples show that we can access different types of content using API Keys. Those requests use the command-line utility curl. This section shows how to use API Keys from your Python and R code.

All of these examples assume that your Posit Connect API Key is available in the environment variable CONNECT_API_KEY and the base URL to your Posit Connect server is in the CONNECT_SERVER environment variable.

export CONNECT_API_KEY=q9R4ylb3K3RPB7AB46il8mxjjcYsaClW
export CONNECT_SERVER=https://rsc.company.com/

Python3 with urllib

The urllib package is a collection of modules for working with URLs. It is part of the Python3 standard library. This example performs an HTTP GET request against the Plumber API we used earlier.

# -*- coding: utf-8 -*-
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()

headers = { "Authorization": "Key %s" % connect_api_key }

request_url = build_url(connect_server, "/content/24/mean", samples = 5)
request = urllib.request.Request(request_url, headers = headers)
response = urllib.request.urlopen(request)
data = response.read()
encoding = response.info().get_content_charset("utf-8")
result = json.loads(data.decode(encoding))

The result object is defined by parsing the JSON response data. It contains the result computed by normalMean in our Plumber API.

R with httr

The httr package lets you make HTTP requests from R. This example performs an HTTP GET request against the same Plumber API we used earlier with curl.

library(httr)

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

resp <- httr::GET(connectServer, 
    path = "/content/24/mean", 
    query = list(samples = 5),
    add_headers(Authorization = paste0("Key ", connectAPIKey)))
result <- httr::content(resp, as = "parsed")

The result object is defined by parsing the JSON response data. It contains the result computed by normalMean in our Plumber API.