REST API Python Scripts

You are viewing documentation for an older version of Secret Server. If you are using Secret Server Cloud visit the current version of this documentation here. If you are using Secret Server On-Premises choose the version that matches yours from this list.
For release dates, end-of-support timelines, and upgrade guidance, see the Secret Server Product Lifecycle page.

This code sample demonstrates how to use Python 3 to authenticate to Secret Server, retrieve a secret, and update secret fields and items.

This code uses the "requests" module, which makes it simple to communicate via REST. You can install the requests module by running: pip install requests

A token is returned from username and password authentication that is used for all subsequent API calls.

Copy

import http.client
import urllib
import json
import requests

site = '[Your Secret Server Site]' #ex: http://domain.com/SecretServer
authApi = '/oauth2/token'
api = site + '/api/v1'
token = "<TOKEN>"

# REST call to retrieve a secret by ID
def GetSecret(token, secretId):
    headers = {'Authorization':'Bearer ' + token, 'content-type':'application/json'}
    resp = requests.get(api + '/secrets/' + str(secretId), headers=headers)    
    
    if resp.status_code not in (200, 304):
        raise Exception("Error retrieving Secret. %s %s" % (resp.status_code, resp))    
    return resp.json()

# REST call method to update the secret on the server
def UpdateSecret(token, secret):        
    headers = {'Authorization':'Bearer ' + token, 'content-type':'application/json'}
    secretId = secret['id']
    resp = requests.put(api + '/secrets/' + str(secretId), json=secret, headers=headers)    
    
    if resp.status_code not in (200, 304):
        raise Exception("Error updating Secret. %s %s" % (resp.status_code, resp))    
    return resp.json()

# Retrieves the secret item by its "slug" value
def GetItemBySlug(secretItems, slug):
    for x in secret['items']:
        if x['slug'] == slug:
            return x
    raise Exception('Item not found for slug: %s' % slug)

# Updates the secret item on the secret with the updated secret item
def UpdateSecretItem(secret, updatedItem):
    secretItems = secret['items']
    for x in secretItems:
        if x['itemId'] == updatedItem['itemId']:
            x.update(updatedItem)
            return
    raise Exception('Secret item not found for item id: %s' % str(updatedItem['itemId']))


# Get secret with ID = 1
print("Retrieving Secret with id: 1...")
secret = GetSecret(token, 1)
print("Secret Name: " + secret['name'])
print("Secret ID: " + str(secret['id']))
print("Active: " + str(secret['active']))

# Get the "Notes" secret item
notesItem = GetItemBySlug(secret, 'notes')
print("Notes secret field value: %s" % notesItem['itemValue'])
print()

# Change value of "Notes" secret item
print("Updating secret...")
notesItem.update({'itemValue': 'New Notes Value'})
UpdateSecretItem(secret, notesItem)
print("Secret updated.")
print()

# Change secret values
updateValues = {'name':'Updated Secret Name' }
secret.update(updateValues)
updatedSecret = UpdateSecret(token, secret)
notesItem = GetItemBySlug(updatedSecret, 'notes')
print("Updated Secret Name: " + updatedSecret['name'])
print("Notes secret field value: %s" % notesItem['itemValue'])