Skip to content

Building a Python API

Learn how to implement a CommonGrants API in Python using the FastAPI web framework and the CommonGrants Python SDK.

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

Get a FastAPI 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, accepting the default answers at the prompts:

    Terminal window
    npx @common-grants/cli@0.4.1 init --template fast-api

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

    The command also leaves main.tsp, tspconfig.yaml, package.json, package-lock.json, and node_modules/ behind. The Python project doesn’t use them, so you can delete them.

  3. Install the dependencies:

    Terminal window
    make install

    If Poetry picks an older interpreter, run poetry env use python3.11 first.

  4. Run the project:

    Terminal window
    make dev
  5. Open the API docs at http://localhost:8000/docs. Press Ctrl+C in the terminal to stop the server when you’re done.

The template includes the following files and directories:

  • Makefile # Development workflow commands
  • README.md # Project documentation
  • pyproject.toml # Python project configuration and dependencies
  • poetry.lock # Locked versions of dependencies (created by make install)
  • .coveragerc # Test coverage configuration
  • .gitignore # Files Git ignores
  • Directorysrc/
    • Directorycommon_grants/
      • api.py # FastAPI application setup and config
      • constants.py # Set ORGANIZATION_DOMAIN to your domain for stable opportunity IDs
      • Directoryroutes/ # API route handlers
        • …
      • Directoryschemas/ # Re-exports the SDK’s Pydantic models
        • …
      • Directoryscripts/ # OpenAPI generator
        • …
      • Directoryservices/ # Business logic and data operations
        • …
  • Directorytests/
    • conftest.py # Shared test fixtures
    • Directorycommon_grants/
      • Directoryroutes/ # Route-related tests
        • …

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

The common-grants-sdk package provides Pydantic models, an extension framework, and an HTTP client that match protocol v0.5. The template pins an older release, so upgrade it:

Terminal window
poetry add common-grants-sdk@0.9.0

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

Import path Description
common_grants_sdk.schemas.pydantic Pydantic models for opportunities, awards, filters, and responses
common_grants_sdk.extensions Custom field and plugin framework
common_grants_sdk.client HTTP client with auth, pagination, and search

The SDK also ships the v0.5 award models, award filters, and a client.awards resource, which follow the same patterns as their opportunity counterparts. The template doesn’t implement the award routes, which are optional in v0.5.

SDK 0.9 types model constructors with snake_case field names, and the template passes camelCase keyword arguments. The app and tests still run, but make check-types reports errors until you rename the arguments in src/common_grants/services/opportunity.py, src/common_grants/services/utils.py, and tests/conftest.py: for example, pageSize=page_size becomes page_size=page_size. Leave dictionary keys such as "pageSize" alone, since they’re the wire format. Then confirm the project type-checks and passes its tests:

Terminal window
make check-types
make test

Generate the OpenAPI spec from the FastAPI app and check it against the CommonGrants v0.5 base spec:

Terminal window
make gen-openapi
npx @common-grants/cli@0.5.0 check spec openapi.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. make check-spec runs the same check with a globally installed cg 0.5.0 or later.

cg check spec validates the API specification, not the running server. To check the code, run make test and make dev. Press Ctrl+C to stop the server.

The template’s src/common_grants/schemas/__init__.py re-exports the SDK’s models, so the routes and services already use them. Validate records from your data source the same way:

from common_grants_sdk.schemas.pydantic import OpportunityBase
# raw_data is a record from your data source
# Raises a ValidationError if it doesn't match the protocol
opportunity = OpportunityBase.model_validate(raw_data)

The services layer in src/common_grants/services/ holds the business logic and data operations for the API. Focus on opportunity.py, which implements the OpportunityService class behind these routes:

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

Specific changes to make:

  • Replace the mock data with a real data source, e.g. a database query or a remote API call, and validate each record with an SDK model.
  • Add the sorting and filtering logic to the OpportunityService.search_opportunities method.
  • Add response_model_exclude_unset=True to each route decorator in src/common_grants/routes/opportunities.py, so optional fields you don’t set are omitted instead of sent as null, which the protocol rejects.

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 registers an Opportunity schema with a typed custom_fields property:

src/common_grants/schemas/plugin.py
"""Custom fields for this API's data source."""
from typing import Optional
from common_grants_sdk.extensions import (
CustomField,
CustomFieldSet,
PluginMeta,
PluginSchemas,
define_plugin,
schema,
)
from common_grants_sdk.schemas.pydantic import OpportunityBase
from pydantic import Field
class OppFields(CustomFieldSet):
"""Custom fields on the Opportunity schema."""
legacy_id: Optional[CustomField[int]] = Field(
default=None,
description="Maps to the opportunity_id in the legacy system",
)
my_plugin = define_plugin(
PluginSchemas(Opportunity=schema(common_schema=OpportunityBase[OppFields])),
meta=PluginMeta(name="my-system", source_system="grants.example.gov"),
)
# Opportunity model with typed custom fields
Opportunity = my_plugin.schemas.Opportunity.common_schema

CustomField[int] derives the field’s fieldType of integer, so there is nothing else to declare. The snake_case attribute legacy_id is legacyId on the wire.

Validate your data with the plugin’s schema instead of the base model, for example in a service. The custom field is validated and fully typed:

from common_grants.schemas.plugin import Opportunity
opportunity = Opportunity.model_validate({
"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},
},
})
fields = opportunity.custom_fields
if fields and fields.legacy_id:
fields.legacy_id.value # int

At runtime Opportunity is a subclass of OpportunityBase, so the template’s response models accept it. Pyright treats the custom-fields type parameter as invariant, though. Once the service returns Opportunity records, change its OpportunityBase annotations to Opportunity, and build the list and search responses with Paginated[Opportunity] and Filtered[Opportunity, dict] instead of OpportunitiesListResponse and OpportunitiesSearchResponse, or make check-types fails. Custom fields the plugin doesn’t declare are kept under their wire keys in custom_fields.model_extra.

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