GovDash
Menu

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

  1. List definitions with GET /v1/meta/custom-fields?entity_type=opportunity. Each one has an id, a team_id, a name, a type, and options, the allowed values for SELECT and MULTI_SELECT fields.
  2. List opportunities with GET /v1/opportunities. List responses don't include custom field values.
  3. Retrieve each opportunity with GET /v1/opportunities/{id}?expand[]=custom_fields.
  4. Match each custom_fields[].field_id to a definition's id.

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.

typevalue
TEXT, TEXTAREA, SELECTstring
MULTI_SELECTarray of strings
BOOLEANboolean
NUMBER, CURRENCYnumber or null
PERCENTAGEnumber from 0 to 100
RATINGinteger, 0 to 5 by default
FORMULAnumber
DATEISO 8601 string or null
URLURL 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 type you don't recognize. GovDash may add types.