Skip to content

Building a TypeScript API

Learn how to implement a CommonGrants API in TypeScript using the Express.js web framework and the CommonGrants TypeScript SDK.

This guide walks you through setting up a new project from the CommonGrants Express.js template, then adding the SDK to validate your data and define custom fields.

Get an Express.js project up and running with the following steps:

  1. Create a new directory for your project:

    Terminal window
    mkdir common-grants-api
    cd common-grants-api
  2. Set up your project using the CommonGrants CLI:

    Terminal window
    npx @common-grants/cli@0.4.1 init --template express-js

    npx ships with Node.js. Bun users can run bunx instead. pnpm dlx can’t run cg init.

  3. Create pnpm-workspace.yaml, which cg init doesn’t create:

    pnpm-workspace.yaml
    allowBuilds:
    "@scarf/scarf": false
    esbuild: false
    overrides:
    "ajv@>=7.0.0-alpha.0 <8.18.0": ">=8.18.0"
    "brace-expansion@>=1 <1.1.21": "1.1.21"
    "brace-expansion@>=3 <5.0.12": "5.0.12"
    "fast-uri@>=3 <3.1.8": "3.1.8"
    "flatted@<3.4.0": "3.4.2"
    "minimatch@>=3 <3.1.5": "3.1.5"
    "path-to-regexp@>=0.1 <0.1.13": "0.1.13"
    "picomatch@>=2 <2.3.2": "2.3.2"
    "picomatch@>=4 <4.0.4": "4.0.4"
    "proxy-addr@>=1.1.0 <2.0.8": "2.0.8"
    "qs@<6.16.0": "6.16.0"
    "rollup@>=4 <4.59.0": "4.60.1"
    "source-map-js@>=1 <1.2.2": "1.2.2"
    "tar@<7.5.21": "7.5.21"
    "vite@>=7.0.0 <=7.3.1": ">=7.3.2"
    "yaml@>=2 <2.8.3": "2.8.3"

    allowBuilds skips optional install scripts. Without it, pnpm stops every pnpm run command with an “Ignored build scripts” error. overrides sets security floors for transitive dependencies and matches the scaffolded pnpm-lock.yaml.

  4. Install the dependencies:

    Terminal window
    pnpm install
  5. Run the project:

    Terminal window
    pnpm run dev
  6. Open the API docs at http://localhost:3000/docs. Press Ctrl+C in the terminal to stop the server when you’re done.

The template includes the following files and directories:

  • package.json # Node.js project configuration and dependencies
  • pnpm-lock.yaml # Locked versions of dependencies
  • pnpm-workspace.yaml # pnpm settings (created in step 3)
  • tsconfig.json # TypeScript configuration
  • tspconfig.yaml # TypeSpec emitter configuration
  • eslint.config.js # ESLint configuration
  • .prettierrc # Prettier configuration
  • .prettierignore # Files Prettier skips
  • .gitignore # Files Git ignores
  • README.md # Project documentation
  • main.tsp # Empty file left by cg init, safe to delete
  • Directorysrc/
    • Directoryapi/
      • index.ts # Express application setup and config
      • Directorycontrollers/ # Request handlers and routers
        • …
      • Directoryerrors/ # API error types
        • …
      • Directorymiddleware/ # Error handling and validation middleware
        • …
      • Directoryschemas/ # Zod schemas for (de)serialization
        • …
      • Directoryservices/ # Business logic and data operations
        • …
    • Directorytypespec/
      • main.tsp # The TypeSpec specification for your API

Once the template is running, add the SDK and connect the API to your data.

The @common-grants/sdk package provides Zod schemas, TypeScript types, and an extension framework that match the current protocol version. Install it, the matching TypeSpec library, and the CommonGrants CLI:

Terminal window
pnpm add --save-exact @common-grants/sdk@0.9.0 @common-grants/core@0.5.0
pnpm add --save-exact -D @common-grants/cli@0.5.0 @typespec/compiler@1.17.0 @typespec/http@1.17.0 @typespec/openapi@1.17.0 @typespec/openapi3@1.17.0 @typespec/json-schema@1.17.0 @typespec/rest@0.87.0 @typespec/versioning@0.87.0

The SDK is split into modules, each with its own import path:

Import path Description
@common-grants/sdk/schemas Zod schemas for data validation
@common-grants/sdk/types Inferred TypeScript types
@common-grants/sdk/constants Runtime enum constants
@common-grants/sdk/extensions Custom field and plugin framework
@common-grants/sdk/client HTTP client with auth, pagination, and search

The SDK exposes its modules through package.json exports, which the template’s "moduleResolution": "node" setting ignores. In tsconfig.json, replace "module": "CommonJS" and "moduleResolution": "node" with:

tsconfig.json
"module": "NodeNext",
"moduleResolution": "NodeNext",

Point the template’s TypeSpec spec at protocol v0.5 so the API docs at /docs match the SDK’s schemas. Replace src/typespec/main.tsp with:

src/typespec/main.tsp
import "@typespec/http";
import "@typespec/versioning";
import "@common-grants/core";
using TypeSpec.Http;
@service(#{ title: "CommonGrants API" })
@Versioning.useDependency(CommonGrants.Versions.v0_5)
namespace Custom;
@tag("Opportunities")
@route("/common-grants/opportunities")
namespace Routes {
alias OpportunitiesRouter = CommonGrants.Routes.Opportunities;
op list is OpportunitiesRouter.list;
op read is OpportunitiesRouter.read;
op search is OpportunitiesRouter.search;
}

Besides the version, this moves @Versioning.useDependency onto the service namespace and nests the routes under it. The template’s original layout applies the version incorrectly, so the read route comes out as /common-grants/opportunities/{id}/{oppId}.

Compile the spec and check it against the CommonGrants v0.5 base spec:

Terminal window
pnpm run typespec
pnpm exec cg check spec tsp-output/@typespec/openapi3/openapi.Custom.yaml --protocol-version 0.5.0

The check should report Spec is compliant with base spec, with 3 warnings. The warnings list the award routes, which are optional in v0.5 and not implemented by the template. Errors, such as a missing or extra route, fail the command with exit code 1.

cg check spec validates the API specification, not the running server. To check the code, confirm it type-checks and runs:

Terminal window
pnpm exec tsc --noEmit
pnpm run dev

Press Ctrl+C to stop the server.

The docs now describe v0.5 models, but the API’s responses still follow the template’s own schemas until you swap in the SDK’s, as described next.

The template ships its own Zod schemas in src/api/schemas/. The SDK provides maintained equivalents for the opportunity and award models, filters, and responses, so you can replace the template’s schemas as you build:

import { OpportunityBaseSchema } from "@common-grants/sdk/schemas";
import type { OpportunityBase } from "@common-grants/sdk/types";
// rawData is a record from your data source
// Throws a ZodError if it doesn't match the protocol
const opportunity: OpportunityBase = OpportunityBaseSchema.parse(rawData);

The services layer in src/api/services/ holds the business logic and data operations for the API. Focus on opportunity.service.ts, which implements the OpportunitiesService class behind these routes:

  • GET /common-grants/opportunities
  • GET /common-grants/opportunities/{oppId}
  • POST /common-grants/opportunities/search

Specific changes to make in this file:

  • Replace the mock data with a real data source, e.g. a database query or a remote API call, and parse each record with an SDK schema.
  • Look opportunities up by id instead of title in OpportunitiesService.getOpportunityByTitle.
  • Add the sorting and filtering logic to the OpportunitiesService.searchOpportunities method.

When adopting the CommonGrants protocol, you may need to include information about a funding opportunity that is not explicitly defined by the CommonGrants model for opportunities. The protocol supports this through the customFields property on the OpportunityBase model, and the SDK’s extensions module gives those fields types.

For example, let’s say you need to add a legacyId field to map opportunities to an existing ID system.

Create a plugin that declares the custom field. The plugin compiles an Opportunity schema with a typed customFields property:

src/api/schemas/plugin.ts
import { z } from "zod";
import { definePlugin } from "@common-grants/sdk/extensions";
/** Custom fields for this API's data source */
export const myPlugin = definePlugin({
meta: {
name: "my-system",
sourceSystem: "grants.example.gov",
capabilities: ["customFields"],
},
schemas: {
Opportunity: {
customFields: {
legacyId: {
fieldType: "integer",
description: "Maps to the opportunity_id in the legacy system",
},
},
},
},
} as const);
/** Opportunity schema with typed custom fields */
export const OpportunitySchema = myPlugin.schemas.Opportunity.commonSchema;
export type Opportunity = z.infer<typeof OpportunitySchema>;

The as const is only required when the specs are assigned to a variable before the call, but the SDK keeps it by convention.

Parse your data with the plugin’s schema instead of the base schema, for example in a new file under src/api/. The custom field is validated and fully typed:

import { OpportunitySchema, type Opportunity } from "./schemas/plugin";
const opportunity: Opportunity = OpportunitySchema.parse({
id: "573525f2-8e15-4405-83fb-e6523511d893",
title: "STEM Education Grant Program",
description: "Improving STEM education in underserved communities",
status: { value: "open" },
createdAt: "2025-01-01T00:00:00Z",
lastModifiedAt: "2025-01-15T00:00:00Z",
customFields: {
legacyId: { name: "legacyId", fieldType: "integer", value: 12345 },
},
});
opportunity.customFields?.legacyId?.value; // number

The template’s services still import their own Opportunity type from src/api/schemas. Replace those imports with the plugin’s schema and type as you wire in real data, so the two don’t collide.

For a one-off extension without a plugin, use withCustomFields() from the same module. See the extensions guide for custom filters, transforms, and publishing plugins.