# Poll an API for New Items on a Schedule

> A Type.com automation example. Every 15 minutes, code reads a Custom API, posts only the items created since the last run, and saves its progress.

Canonical page: https://docs.type.com/automations/examples/poll-with-checkpoint/

Some services cannot send events. For these, read the service on a schedule and remember where you stopped. Every 15 minutes, this automation reads new incidents from a status API, posts them in the Space, and saves a checkpoint.

| | |
| --- | --- |
| **Trigger** | An interval schedule, every 15 minutes |
| **Stages** | `findNew` (code) → `postAndSave` (code) |
| **Needs** | A [Custom API connection](https://docs.type.com/connectors-and-skills/custom-apis/index.md) in the Space |

## How it runs

```mermaid
flowchart LR
  every15Minutes(["every15Minutes · schedule"])
  findNew["findNew · code"]
  postAndSave["postAndSave · code"]
  every15Minutes -->|entry| findNew
  findNew -->|next| postAndSave
```

Each node in the graph is one key in the code:

| Node | Type | What it does |
| --- | --- | --- |
| `every15Minutes` | Trigger | Starts a run every 15 minutes. |
| `findNew` | Code stage | Reads incidents created since the checkpoint. Completes the run when nothing is new. |
| `postAndSave` | Code stage | Posts the new incidents, moves the checkpoint forward, and completes the run. |

## The code

```ts title="src/main.ts"
import {
  automation,
  code,
  complete,
  next,
  recurringEventSchema,
} from "@type-dot-com/sdk/automations";

// Replace with your Custom API connection and Space.
const statusApiConnectionId = "orgint_example";
const spaceId = "ch_example";

// The shape of GET /v1/incidents in the service's API.
const incidentList = z.looseObject({
  incidents: z.array(
    z.looseObject({
      id: z.string(),
      title: z.string(),
      createdAt: z.string(),
    }),
  ),
});

// What this automation remembers between runs.
const progress = z.object({
  lastCreatedAt: z.string(),
});

// What the first stage passes to the second.
const newIncidents = z.object({
  incidents: z.array(z.object({ id: z.string(), title: z.string(), createdAt: z.string() })),
  latestCreatedAt: z.string(),
});

export default automation({
  output: z.object({ newIncidents: z.number() }),

  deployment: {
    subscriptions: {
      every15Minutes: {
        title: "New incidents",
        description: "Post incidents that were created since the last check",
        source: {
          kind: "recurring",
          schedule: { kind: "interval", everySeconds: 900 },
        },
        entry: "findNew",
      },
    },
  },

  stages: {
    // 1. Read the incidents created since the last saved checkpoint.
    findNew: code({
      input: recurringEventSchema,
      transitions: ["postAndSave"],
      async run({ ctx, input }) {
        // The first run has no checkpoint. Start from this run's time.
        const saved = progress.safeParse(ctx.checkpoint?.value);
        const since = saved.success ? saved.data.lastCreatedAt : input.scheduledAt;

        const response = await ctx.read.request(
          {
            organizationIntegrationId: statusApiConnectionId,
            method: "GET",
            path: "/v1/incidents",
            query: { created_after: since },
          },
          incidentList,
        );
        if (response.isErr()) {
          return err(response.error);
        }

        const incidents = response.value.incidents.map((incident) => ({
          id: incident.id,
          title: incident.title,
          createdAt: incident.createdAt,
        }));

        // Nothing new: end the run. The checkpoint stays the same.
        if (incidents.length === 0) {
          return complete({ newIncidents: 0 });
        }

        // The newest creation time becomes the next checkpoint.
        let latestCreatedAt = since;
        for (const incident of incidents) {
          if (incident.createdAt > latestCreatedAt) {
            latestCreatedAt = incident.createdAt;
          }
        }

        return next("postAndSave", { incidents, latestCreatedAt });
      },
    }),

    // 2. Post the new incidents, then move the checkpoint forward.
    postAndSave: code({
      input: newIncidents,
      transitions: [],
      async run({ ctx, input }) {
        const lines = input.incidents.map((incident) => `- ${incident.title}`);

        const sent = await ctx.write.sendMessage(
          {
            channelId: spaceId,
            content: `New incidents:\n${lines.join("\n")}`,
          },
          { effectKey: `incidents:${input.latestCreatedAt}` },
        );
        if (sent.isErr()) {
          return err(sent.error);
        }

        // Save the checkpoint in the stage that finishes the work.
        // Type saves it only when this stage succeeds.
        const staged = ctx.saveCheckpoint({ lastCreatedAt: input.latestCreatedAt });
        if (staged.isErr()) {
          return err(staged.error);
        }

        return complete({ newIncidents: input.incidents.length });
      },
    }),
  },
});
```

## How it works

1. **`ctx.checkpoint`** is `null` on the first run, and `{ value, version }` after a stage saves one. `progress.safeParse` checks the saved value, because an older revision could have saved another shape.
2. **`ctx.read.request`** sends a `GET` to the Custom API connection. Type adds the credentials. The result is the parsed response body, checked against `incidentList`.
3. **A quiet run ends early.** With no new incidents, `findNew` completes, and the checkpoint stays the same.
4. **The checkpoint moves only after the post.** `postAndSave` calls `ctx.saveCheckpoint()` after the message is sent. Type saves the checkpoint only when the stage succeeds. If the post fails, the next run reads the same incidents again.

## Test it

A fixture answers the API request in `integrationResponses`. This fixture tests a run with no new incidents:

```json title="fixtures.json"
[
  {
    "name": "ends early when nothing is new",
    "subscriptionId": "every15Minutes",
    "checkpoint": { "lastCreatedAt": "2026-11-05T09:45:00.000Z" },
    "payload": { "scheduledAt": "2026-11-05T10:00:00.000Z" },
    "integrationResponses": [
      {
        "request": {
          "organizationIntegrationId": "orgint_example",
          "method": "GET",
          "path": "/v1/incidents",
          "query": { "created_after": "2026-11-05T09:45:00.000Z" }
        },
        "response": {
          "connection": { "id": "orgint_example", "name": "Status API", "baseUrl": "https://status.example.com" },
          "data": { "incidents": [] },
          "headers": {},
          "status": 200,
          "statusText": "OK",
          "success": true,
          "truncated": false
        }
      }
    ],
    "expectedOutput": { "newIncidents": 0 }
  }
]
```

## Make it yours

| Value | Replace with |
| --- | --- |
| `orgint_example` | Your Custom API connection ID. |
| `ch_example` | The ID of your Space. |
| `/v1/incidents`, `created_after` | The path and the query parameter of your API. |
| `everySeconds: 900` | Any multiple of 60, at least 60. |

> **Tip:** Use events when the service can send them. Events are faster, and they do not start runs when nothing changed.

## Related

- [Keep state between runs](https://docs.type.com/automations/state/index.md): how checkpoints work.
- [Write safely](https://docs.type.com/automations/safe-writes/index.md): make a repeated write safe.
- [Call connected apps and APIs](https://docs.type.com/automations/call-integrations/index.md): `ctx.read` and `ctx.write`.
