GovDash
Menu

Create and update an opportunity

In this example you'll create an opportunity, move it to a phase with an estimated value, and then delete it.

Steps

  1. Get a phase id from GET /v1/meta/phases. Each phase has an id, a name, and an order in your pipeline.
  2. Create the opportunity with POST /v1/opportunities. Send title and classification.
  3. Change fields with PATCH /v1/opportunities/{id}. Send only the fields you want to change. A phase can require fields, such as a custom field, before an opportunity can move into it. If the opportunity doesn't have them yet, the move fails with 422 validation_failed and the message names the missing fields.
  4. Delete it with DELETE /v1/opportunities/{id}.

Create fields

FieldTypeRequired
titlestringYes. Unique within the team.
classificationUNCLASSIFIED or CUIYes. CUI needs a CUI key.
team_idstringNo. If you send it, it must be your token's team, or you get 400.
descriptionstringNo
phase_idstringNo. From List phases. Defaults to the first active phase.
solicitation_numberstringNo
agency_idstringNo. An agency from GET /v1/agencies.
estimated_valuenumberNo. US dollars.
due_dateISO 8601 timestampNo
posted_dateISO 8601 timestampNo
source_urlstringNo

To leave a field empty, omit it. Create doesn't accept null.

Update fields

PATCH accepts title, description, phase_id, solicitation_number, agency_id, estimated_value, due_date, and posted_date. Send at least one. Fields you leave out keep their values. Send null to clear description, agency_id, estimated_value, due_date, or posted_date. You can replace solicitation_number but not clear it. You can't change source_url or classification after you create the opportunity.

Both endpoints reject fields they don't list with 400 bad_request.

Code

The curl commands run the steps in order. Set OPPORTUNITY_ID from the create response and PHASE_ID from the phases list. Run the TypeScript sample with npx tsx create-opportunity.ts on Node.js 20 or later. The Python sample needs requests, which you install with pip install requests.

curlcurl
curl "$GOVDASH_API_URL/v1/meta/phases" \
  -H "Authorization: Bearer $GOVDASH_API_KEY" \
  -H "govdash-version: $GOVDASH_API_VERSION"

curl "$GOVDASH_API_URL/v1/opportunities" \
  -X POST \
  -H "Authorization: Bearer $GOVDASH_API_KEY" \
  -H "govdash-version: $GOVDASH_API_VERSION" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "API test opportunity",
    "classification": "UNCLASSIFIED",
    "due_date": "2026-12-15T17:00:00Z"
  }'

curl "$GOVDASH_API_URL/v1/opportunities/$OPPORTUNITY_ID" \
  -X PATCH \
  -H "Authorization: Bearer $GOVDASH_API_KEY" \
  -H "govdash-version: $GOVDASH_API_VERSION" \
  -H "Content-Type: application/json" \
  -d "{\"phase_id\": \"$PHASE_ID\", \"estimated_value\": 250000}"

curl "$GOVDASH_API_URL/v1/opportunities/$OPPORTUNITY_ID" \
  -X DELETE \
  -H "Authorization: Bearer $GOVDASH_API_KEY" \
  -H "govdash-version: $GOVDASH_API_VERSION"
create-opportunity.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,
}

class GovDashError extends Error {
  constructor(
    readonly status: number,
    readonly code: string,
    message: string,
  ) {
    super(`${status} ${code}: ${message}`)
  }
}

async function call<T>(
  method: string,
  path: string,
  body?: unknown,
): Promise<T> {
  const response = await fetch(`${baseUrl}${path}`, {
    method,
    headers: {
      ...headers,
      ...(body === undefined ? {} : { "Content-Type": "application/json" }),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  })
  if (response.status === 202) return undefined as T
  const json = await response.json()
  if (!response.ok)
    throw new GovDashError(response.status, json.error.code, json.error.message)
  return json as T
}

type Opportunity = {
  id: string
  title: string
  phase: { id: string; name: string }
  estimated_value: number | null
}
type Phase = { id: string; name: string; order: number }

const phases = await call<{ edges: { node: Phase }[] }>(
  "GET",
  "/v1/meta/phases",
)
const phase = phases.edges
  .map((e) => e.node)
  .sort((a, b) => a.order - b.order)[1]
if (!phase) throw new Error("This example needs at least two phases")

let opportunity: Opportunity
try {
  opportunity = await call<Opportunity>("POST", "/v1/opportunities", {
    title: "API test opportunity",
    classification: "UNCLASSIFIED",
    due_date: "2026-12-15T17:00:00Z",
  })
} catch (error) {
  if (error instanceof GovDashError && error.code === "conflict") {
    throw new Error(
      "An opportunity with this title already exists. Pick another title.",
    )
  }
  throw error
}
console.log("Created", opportunity.id, "in", opportunity.phase.name)

try {
  const updated = await call<Opportunity>(
    "PATCH",
    `/v1/opportunities/${opportunity.id}`,
    {
      phase_id: phase.id,
      estimated_value: 250000,
    },
  )
  console.log("Moved to", updated.phase.name, "worth", updated.estimated_value)
} catch (error) {
  // The phase needs fields this opportunity doesn't have yet.
  if (!(error instanceof GovDashError && error.code === "validation_failed")) {
    throw error
  }
  console.log("Couldn't move it:", error.message)
}

await call<void>("DELETE", `/v1/opportunities/${opportunity.id}`)
console.log("Deletion queued")
create_opportunity.pyPython
import os

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"]


class GovDashError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status = status
        self.code = code


def call(method, path, body=None):
    response = session.request(method, BASE_URL + path, json=body)
    if response.status_code == 202:
        return None
    data = response.json()
    if not response.ok:
        raise GovDashError(response.status_code, data["error"]["code"], data["error"]["message"])
    return data


phases = sorted((edge["node"] for edge in call("GET", "/v1/meta/phases")["edges"]), key=lambda p: p["order"])
if len(phases) < 2:
    raise SystemExit("This example needs at least two phases")
phase = phases[1]

try:
    opportunity = call("POST", "/v1/opportunities", {
        "title": "API test opportunity",
        "classification": "UNCLASSIFIED",
        "due_date": "2026-12-15T17:00:00Z",
    })
except GovDashError as error:
    if error.code == "conflict":
        raise SystemExit("An opportunity with this title already exists. Pick another title.")
    raise
print("Created", opportunity["id"], "in", opportunity["phase"]["name"])

try:
    updated = call("PATCH", f"/v1/opportunities/{opportunity['id']}", {
        "phase_id": phase["id"],
        "estimated_value": 250000,
    })
    print("Moved to", updated["phase"]["name"], "worth", updated["estimated_value"])
except GovDashError as error:
    # The phase needs fields this opportunity doesn't have yet.
    if error.code != "validation_failed":
        raise
    print("Couldn't move it:", error)

call("DELETE", f"/v1/opportunities/{opportunity['id']}")
print("Deletion queued")

What can go wrong

ResponseCause
409 conflictAn opportunity with this title already exists. Nothing was created.
422 validation_failedGovDash won't make the change, such as moving to a phase whose required fields the opportunity doesn't have.
400 bad_requestA field the endpoint doesn't accept, a wrong type, an empty PATCH body, or a team_id that isn't your team.
403 forbiddenThe service account's role can't create or edit opportunities, or an UNCLASSIFIED key sent CUI.