Find users and set a custom attribute¶
The goal: find a Domo user by email address, show one custom attribute's current value on that user, and set a new value.
A custom attribute is a named field that every user in your instance can carry, such as
region or cost_center. This recipe sets the value for one user. The attribute
itself must already exist in Domo.
The script only reads until you switch writing on
APPLY = False near the top of the script is a plain True/False switch. While it is
False, the script lists users, shows the current value and stops before it changes
anything. Change it to True to write. Try a test user first.
Before you start¶
- crew-dcs is installed, and your
.envfile holdsDOMO_INSTANCEandDOMO_ACCESS_TOKEN(how). - The user behind the token can manage users in Domo. A token can only do what its owner can do.
- Add one more line to your
.envfile:DOMO_USER_EMAIL=person@example.com, the user you want to change. - A custom attribute already exists. In Domo, open the Admin area and look for the user
attributes list (the menu name differs by Domo version). Note the attribute's key, its short id. This
recipe uses
region. ChangeATTRIBUTE_KEYin the script to your own key.
The script¶
Save this as set_user_attribute.py next to your .env file:
import asyncio
import os
from dotenv import load_dotenv
from crew_dcs.auth import DomoTokenAuth
from crew_dcs.routes import user as user_routes
from crew_dcs.routes.user import UserAttributes_IssuerType
load_dotenv() # copies the lines in .env into environment variables
APPLY = False # False = look only. True = also write the new value.
ATTRIBUTE_KEY = "region" # the key of an attribute that already exists in Domo
NEW_VALUE = "EMEA"
USER_EMAIL = os.environ["DOMO_USER_EMAIL"]
async def read_attribute(auth, user_id):
"""Ask Domo for one user and return the current value of ATTRIBUTE_KEY."""
res = await user_routes.search_users(
auth=auth,
body={
"includeDeleted": False,
"includeSupport": False,
"filters": [
{
"field": "id",
"filterType": "value",
"values": [user_id],
"operator": "EQ",
}
],
"attributes": ["id", "displayName", ATTRIBUTE_KEY], # the fields to return
},
)
# .get() gives None, instead of an error, when the attribute has no value yet.
return res.response[0].get(ATTRIBUTE_KEY)
async def main():
async with DomoTokenAuth(
domo_instance=os.environ["DOMO_INSTANCE"],
domo_access_token=os.environ["DOMO_ACCESS_TOKEN"],
) as auth:
# 1. List users. Each one is a dictionary.
res = await user_routes.get_all_users(auth=auth)
print(len(res.response), "users in this instance")
for user in res.response[:3]: # [:3] means "the first three"
print(" ", user.get("id"), user.get("displayName"), user.get("emailAddress"))
# 2. Find one user by email address.
res = await user_routes.search_users_by_email(
user_email_ls=[USER_EMAIL], auth=auth
)
# This list comprehension keeps only the users whose email matches exactly,
# ignoring capital letters.
matches = [
u
for u in res.response
if (u.get("emailAddress") or "").lower() == USER_EMAIL.lower()
]
if not matches:
print("No user has the email", USER_EMAIL)
return
user_id = matches[0]["id"]
print("Found:", matches[0].get("displayName"), "- id", user_id)
# 3. Check the attribute exists, and show its current value.
res = await user_routes.get_user_attributes(
auth=auth, issuer_type_ls=[UserAttributes_IssuerType.CUSTOM]
)
keys = [attribute["key"] for attribute in res.response] # just the keys
print("Custom attributes in this instance:", keys)
if ATTRIBUTE_KEY not in keys:
print(ATTRIBUTE_KEY, "is not a custom attribute here. Create it in Domo first.")
return
old_value = await read_attribute(auth, user_id)
print("Current", ATTRIBUTE_KEY, "=", old_value)
if not APPLY:
print("APPLY is False, so nothing was changed.")
return
# 4. Write the new value, then read it back.
res = await user_routes.update_user(
auth=auth,
user_id=user_id,
user_property_ls=[{"key": ATTRIBUTE_KEY, "values": [NEW_VALUE]}],
)
print("update ok:", res.is_success, "- status", res.status)
print("Now", ATTRIBUTE_KEY, "=", await read_attribute(auth, user_id))
asyncio.run(main())
Run it with uv run python set_user_attribute.py from the project folder where you
installed crew-dcs. (In a virtual environment, activate it and run
python set_user_attribute.py.) Run it once as it is and read the output. When you are
happy with it, change APPLY to True and run it again.
Undo it¶
The script prints the current value before it writes. To put it back, set NEW_VALUE to
that printed old value, keep APPLY = True, and run the script again. If the old value
was None, the user had no value, and this script cannot clear it. Clear it in Domo. If the attribute holds several values, the script reads and restores only the first one, so check the user in Domo before you write.
What you should see¶
The names and ids will be your own. With APPLY = False, yours will look like this:
42 users in this instance
1001 Ada Admin ada@example.com
1002 Ben Builder ben@example.com
1003 Cy Consumer cy@example.com
Found: Ben Builder - id 1002
Custom attributes in this instance: ['region', 'costcenter']
Current region = None
APPLY is False, so nothing was changed.
With APPLY = True, the last lines become:
Current region = None
update ok: True - status 200
Now region = EMEA
What the script does¶
get_all_userslists every user. It takes onlyauth.res.responseis a list of dictionaries (sets of named values, likeuser["displayName"]).search_users_by_emailtakes a list of emails, even for one person. It is a text search, so the script keeps only the exact match. If it finds nobody, the route raisesSearchUserNotFoundErrorbefore the script's own check runs.get_user_attributeslists attribute definitions.issuer_type_lslimits the list toCUSTOM, the ones made in your instance, so Domo's built-in attributes stay out.search_usersis the general search. Theattributeslist names the fields you want back, and each one comes back as a plainname: valuepair on the user. The script uses it to read the value before and after the write.update_usersends the new values, and runs only whenAPPLYisTrue. Each item inuser_property_lsis a dictionary with akey(the attribute) andvalues(a list of text values). The value is always a list, even for one value.
Each route raises an error when Domo answers with a failure, so when a call returns, it worked.
The class version¶
For this task the route version is the simpler one. The DomoUser class
(crew_dcs.classes.DomoUser) is handy for a user's standard fields such as name and
title. Setting a custom attribute goes through the same update_user route either way.
Check it in Domo¶
Open the Admin area, go to People, open the user, and look at the user's attributes. The value should match what the script printed. (Where attributes appear differs by Domo version.) Domo's API for user attributes is not documented by Domo, so trust the Domo screen over the script's last line.
Errors you might hit¶
Each one is a kind of DomoError. The Errors page shows how to catch them.
All of them are importable from crew_dcs.routes.user.
| Error | Likely cause |
|---|---|
SearchUserNotFoundError |
The search found nobody. Check the email spelling. |
User_GET_Error |
Domo refused a read. The token's user may not be allowed to see users. A wrong or expired token also lands here, with "Authentication required (HTTP 401)" in the message. |
User_CRUD_Error |
Domo refused the update. Check the attribute key, and that the token's user can edit users. |
UserAttributes_GET_Error |
The list of attributes could not be read. |
Python can also stop the script before Domo is involved. KeyError: 'DOMO_USER_EMAIL' means the
line is missing from .env. That is a Python error, not a Domo one. To test a token on its own,
use who_am_i() from Authenticating to Domo.