# Quickstart

Source: https://developers.novilabs.com/forecasts/quickstart/

> Create an API token, make your first call and read a done plan's oil and gas curves.

This page takes you from no token to a done plan's cumulative curves in three calls. You need a Novi login with access
to Forecasts.

1. **Create a token.** In the Forecasts app, open **Settings**, then **API tokens**. Name the token, pick how long it
   lasts (7, 30 or 90 days, 1 year, or a custom 1 to 365 days; 90 is the default) and create it. Copy it now: Novi
   shows it only once.

   <Screenshot name="api-tokens-create" alt="The Create a token form: a name, and expiry choices of 7, 30 or 90 days, 1 year or custom, with 90 days selected." width={768} height={278} />
   <Screenshot name="api-tokens-copy" alt="After creating a token, Forecasts shows it once with a Copy token button and the note: Copy your new token now. Novi can't show it again." width={768} height={447} />

   If **API tokens** is missing from Settings, ask your company's Novi administrator for the Access MCP permission.

2. **Set your base URL and token.** Use the host you sign in to Novi at.

   ```sh
   export NOVI_API_BASE="https://<your-company>.novilabs.io/forecasts/api/v1"
   # Paste the token at the prompt so it stays out of your shell history.
   read -rs NOVI_API_TOKEN && export NOVI_API_TOKEN
   ```

3. **Check who you are.** `GET /me` answers with the account the token acts as.

   ```sh
   curl -sS --fail-with-body \
     -H "Authorization: Bearer $NOVI_API_TOKEN" \
     "$NOVI_API_BASE/me"
   ```

   ```json
   { "tenant": "example", "user": { "id": "7", "email": "user@example.com" }, "role": "customer" }
   ```

4. **List your done plans.** `origin=all` includes your Legacy Forecasts[^legacy] beside the plans made in Forecasts.
   Each row's `origin.engine` says which: `v2` or `fe`.

   ```sh
   curl -sS --fail-with-body \
     -H "Authorization: Bearer $NOVI_API_TOKEN" \
     "$NOVI_API_BASE/plans?origin=all&status=done&limit=5"
   ```

5. **Read a plan's curves.** `GET /plans/{id}/curves` returns each well's cumulative volume every 30 days, to its EUR on a plan made with `eur: true`:
   `cum[m-1]` is the cumulative at day 30·m, so `cum[11]` is the volume to day 360.

   ```sh
   PLAN_ID="<a plan id from the list>"
   curl -sS --fail-with-body --compressed \
     -H "Authorization: Bearer $NOVI_API_TOKEN" \
     "$NOVI_API_BASE/plans/$PLAN_ID/curves?limit=10"
   ```

   <Screenshot name="plan-results-cumulative" alt="Cumulative oil by day online for each well in a done plan, in the Production tab of Forecasts." width={539} height={621} caption="The plan's cumulative oil per well in the Forecasts app, first 3 years." />

## The same calls in code

**Python**

```python
import os

import requests

BASE = os.environ["NOVI_API_BASE"]
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['NOVI_API_TOKEN']}"

def get(path, **params):
    r = session.get(f"{BASE}{path}", params=params, timeout=60)
    r.raise_for_status()
    return r.json()

print(get("/me"))

plans = get("/plans", origin="all", status="done", limit=5)["plans"]
for plan in plans:
    print(plan["id"], plan["name"], plan["origin"]["engine"])
if not plans:
    raise SystemExit("No done plans yet: run one in the Forecasts app or with POST /plans.")

plan_id = plans[0]["id"]
params = {"limit": 100}
while True:
    page = get(f"/plans/{plan_id}/curves", **params)
    for well in page["wells"]:
        oil = well.get("curves", {}).get("oil", {}).get("P50", {})
        cum = oil.get("cum", [])
        if len(cum) > 11 and cum[11] is not None:
            print(well["label"], "oil to day 360:", cum[11], "bbl")
    if page["next_cursor"] is None:
        break
    params["cursor"] = page["next_cursor"]
```

**TypeScript**

```ts
const BASE = process.env.NOVI_API_BASE ?? '';
const headers = { Authorization: `Bearer ${process.env.NOVI_API_TOKEN ?? ''}` };

async function get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
  const url = new URL(BASE + path);
  for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
  const res = await fetch(url, { headers });
  if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
  return (await res.json()) as T;
}

type PlanList = {
  plans: { id: string; name: string | null; origin?: { engine: string } }[];
  next_cursor: string | null;
};
type Curve = { cum?: (number | null)[]; error?: string };
type CurvesPage = {
  wells: { label: string; curves?: { oil?: { P50?: Curve } } }[];
  next_cursor: string | null;
};

async function main() {
  console.log(await get('/me'));

  const { plans } = await get<PlanList>('/plans', { origin: 'all', status: 'done', limit: '5' });
  for (const plan of plans) console.log(plan.id, plan.name, plan.origin?.engine);
  if (plans.length === 0) throw new Error('No done plans yet: run one in the Forecasts app or with POST /plans.');

  const params: Record<string, string> = { limit: '100' };
  for (;;) {
    const page = await get<CurvesPage>(`/plans/${plans[0].id}/curves`, params);
    for (const well of page.wells) {
      const cum = well.curves?.oil?.P50?.cum ?? [];
      const day360 = cum[11];
      if (day360 != null) console.log(well.label, 'oil to day 360:', day360, 'bbl');
    }
    if (page.next_cursor === null) break;
    params.cursor = page.next_cursor;
  }
}

main().catch(err => {
  console.error(err);
  process.exit(1);
});
```

The TypeScript runs on Node 18 or later, which has `fetch` built in.

> **Ask for less:**
> Lists page with `limit` and an opaque `cursor`: pass `next_cursor` back until it is `null`. Send
> `Accept-Encoding: gzip` (curl's `--compressed`) and responses over 1 KB come back compressed.

## Next

- Learn what each curve point means, and how Novi labels Low and High, in
  [Forecasts and curves](https://developers.novilabs.com/forecasts/guides/forecasts-and-curves/).
- Run your own plan in [Plans and wells](https://developers.novilabs.com/forecasts/guides/plans-and-wells/).
- Keep another tool in step with [Partner sync](https://developers.novilabs.com/forecasts/guides/partner-sync/).

[^legacy]: Legacy Forecasts are dynamic imports from Forecast Engine v1.
