Read custom fields
In this example you'll read your team's custom field definitions, then read the values set on each opportunity and print them by field name.
Steps
- List definitions with
GET /v1/meta/custom-fields?entity_type=opportunity. Each one has anid, ateam_id, aname, atype, andoptions, the allowed values forSELECTandMULTI_SELECTfields. - List opportunities with
GET /v1/opportunities. List responses don't include custom field values. - Retrieve each opportunity with
GET /v1/opportunities/{id}?expand[]=custom_fields. - Match each
custom_fields[].field_idto a definition'sid.
entity_type is required, and opportunity is the only value.
Value shapes
value is JSON, and its shape depends on type. The table shows the shapes GovDash validates when it stores a value. Treat it as a guide, and handle null and shapes you don't expect.
type | value |
|---|---|
TEXT, TEXTAREA, SELECT | string |
MULTI_SELECT | array of strings |
BOOLEAN | boolean |
NUMBER, CURRENCY | number or null |
PERCENTAGE | number from 0 to 100 |
RATING | integer, 0 to 5 by default |
FORMULA | number |
DATE | ISO 8601 string or null |
URL | URL string or null |
NUMBER_RANGE, CURRENCY_RANGE | { "min": number or null, "max": number or null } |
DATE_RANGE | { "start": ..., "end": ... } |
Code
The curl commands read the definitions, then the values on one opportunity. Set OPPORTUNITY_ID first. The -g flag stops curl from reading [] as a pattern. Run the TypeScript sample with npx tsx read-custom-fields.ts on Node.js 20 or later. The Python sample needs requests, which you install with pip install requests.
curlcurl
curl -G "$GOVDASH_API_URL/v1/meta/custom-fields" \
-H "Authorization: Bearer $GOVDASH_API_KEY" \
-H "govdash-version: $GOVDASH_API_VERSION" \
--data-urlencode "entity_type=opportunity"
curl -g "$GOVDASH_API_URL/v1/opportunities/$OPPORTUNITY_ID?expand[]=custom_fields" \
-H "Authorization: Bearer $GOVDASH_API_KEY" \
-H "govdash-version: $GOVDASH_API_VERSION"read-custom-fields.tsTypeScript
const apiVersion = process.env.GOVDASH_API_VERSION
if (!apiVersion) throw new Error("Set GOVDASH_API_VERSION")
const baseUrl = process.env.GOVDASH_API_URL
const apiKey = process.env.GOVDASH_API_KEY
if (!baseUrl || !apiKey)
throw new Error("Set GOVDASH_API_URL and GOVDASH_API_KEY")
const headers = {
Authorization: `Bearer ${apiKey}`,
"govdash-version": apiVersion,
}
type Definition = {
id: string
name: string
type: string
options: string[] | null
}
type Value = { field_id: string; name: string; type: string; value: unknown }
type Opportunity = { id: string; title: string; custom_fields?: Value[] }
type Page<T> = {
edges: { node: T }[]
pageInfo: { hasNextPage: boolean; endCursor: string | null }
}
async function get<T>(path: string, query = new URLSearchParams()): Promise<T> {
for (let attempt = 1; ; attempt++) {
const response = await fetch(`${baseUrl}${path}?${query}`, {
headers,
})
if (response.status === 429 && attempt < 5) {
const seconds = Number(response.headers.get("retry-after") ?? "1")
await new Promise((r) =>
setTimeout(r, seconds * 1000 * 2 ** (attempt - 1)),
)
continue
}
const body = await response.json()
if (!response.ok)
throw new Error(
`${response.status} ${body.error.code}: ${body.error.message}`,
)
return body as T
}
}
async function listAll<T>(
path: string,
params: Record<string, string> = {},
): Promise<T[]> {
const query = new URLSearchParams(params)
const nodes: T[] = []
while (true) {
const page = await get<Page<T>>(path, query)
nodes.push(...page.edges.map((edge) => edge.node))
if (!page.pageInfo.hasNextPage || page.pageInfo.endCursor === null)
return nodes
query.set("cursor", page.pageInfo.endCursor)
}
}
const definitions = await listAll<Definition>("/v1/meta/custom-fields", {
entity_type: "opportunity",
})
const byId = new Map(
definitions.map((definition) => [definition.id, definition]),
)
const opportunities = await listAll<{ id: string }>("/v1/opportunities")
for (const { id } of opportunities) {
const opportunity = await get<Opportunity>(
`/v1/opportunities/${id}`,
new URLSearchParams({ "expand[]": "custom_fields" }),
)
console.log(opportunity.title)
for (const field of opportunity.custom_fields ?? []) {
const definition = byId.get(field.field_id)
console.log(
` ${definition?.name ?? field.name} (${field.type}):`,
JSON.stringify(field.value),
)
}
}read_custom_fields.pyPython
import json
import os
import time
import requests
BASE_URL = os.environ["GOVDASH_API_URL"]
session = requests.Session()
session.headers["Authorization"] = "Bearer " + os.environ["GOVDASH_API_KEY"]
session.headers["govdash-version"] = os.environ["GOVDASH_API_VERSION"]
def get(path, params=None):
for attempt in range(1, 6):
response = session.get(BASE_URL + path, params=params)
if response.status_code == 429 and attempt < 5:
time.sleep(float(response.headers.get("retry-after", "1")) * 2 ** (attempt - 1))
continue
body = response.json()
if not response.ok:
raise RuntimeError(f"{response.status_code} {body['error']['code']}: {body['error']['message']}")
return body
def list_all(path, params=None):
query = dict(params or {})
while True:
page = get(path, query)
for edge in page["edges"]:
yield edge["node"]
if not page["pageInfo"]["hasNextPage"]:
return
query["cursor"] = page["pageInfo"]["endCursor"]
definitions = {d["id"]: d for d in list_all("/v1/meta/custom-fields", {"entity_type": "opportunity"})}
for summary in list(list_all("/v1/opportunities")):
opportunity = get(f"/v1/opportunities/{summary['id']}", {"expand[]": "custom_fields"})
print(opportunity["title"])
for field in opportunity.get("custom_fields", []):
definition = definitions.get(field["field_id"])
name = definition["name"] if definition else field["name"]
print(f" {name} ({field['type']}):", json.dumps(field["value"]))Notes
- This example makes one read per opportunity. For a large team, read only opportunities that changed since your last run (see Sync incrementally), or spread the reads out to stay inside the rate limits.
- Don't fail on a
typeyou don't recognize. GovDash may add types.