Setting a Content Item’s Vanity URL

Problem

You need to set a vanity URL for a content item.

Solution

Use the unique identifier (GUID) for the content item to set its vanity URL.

from posit import connect
import polars as pl

client = connect.Client()

CONTENT_GUID = "154bd2af-e8fa-4aa4-aab8-dcef701f4af9"
VANITY_URL = "/my-new-vanity-url/"

response = client.put(f"v1/content/{CONTENT_GUID}/vanity", json={"path": VANITY_URL})
results_df = pl.DataFrame(response.json())

A successful response includes the content GUID, the new vanity URL, and the creation time.

>>> results_df
shape: (1, 3)
┌─────────────────────────────────┬─────────────────────┬──────────────────────┐
│ content_guid                    ┆ path                ┆ created_time         │
---------
strstrstr
╞═════════════════════════════════╪═════════════════════╪══════════════════════╡
154bd2af-e8fa-4aa4-aab8-dcef70… ┆ /my-new-vanity-url/2024-04-25T18:27:16Z
└─────────────────────────────────┴─────────────────────┴──────────────────────┘

If the vanity URL you wish to use is already in use, the Connect server will return a 409 Conflict HTTP status.

ClientError: Vanity path conflicts with one or more already in use. (Error Code: 51, HTTP Status: 409 Conflict)
library(connectapi)
client <- connect()

CONTENT_GUID <- "154bd2af-e8fa-4aa4-aab8-dcef701f4af9"
VANITY_URL <- "/my-new-vanity-url/"

# The vanity_is_available() function returns TRUE if vanity_url is available
# on the server.
if (vanity_is_available(client, VANITY_URL)) {
  content <- content_item(client, CONTENT_GUID)
  set_vanity_url(content, VANITY_URL)
}

A successful response prints the content GUID and vanity URL.

Posit Connect Content Vanity URL: 
  Content GUID: 154bd2af-e8fa-4aa4-aab8-dcef701f4af9
  Vanity URL: /my-new-vanity-url/

If you call set_vanity_url() with an unavailabile vanity path, the Connect server will return a 409 Conflict HTTP status. However, the example above uses the vanity_is_available() function to avoid this.

Error in `self$raise_error()`:
! https://rsc.radixu.com/__api__/v1/content/154bd2af-e8fa-4aa4-aab8-dcef701f4af9/vanity request failed with Client error: (409) Conflict