Skip to content

Using Python

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 using the SDK to validate your data and define custom fields.

Get a FastAPI project up and running with the following steps:

  1. Open the FastAPI template repository on GitHub and click Use this template to create your own repository from it.

  2. Clone your new repository:

    Terminal window
    git clone https://github.com/<you>/<your-api>.git
    cd <your-api>
  3. Install the dependencies:

    Terminal window
    make install

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

  4. Check that everything works before you change anything:

    Terminal window
    make ci

    This runs the format, lint, and type checks, then the test suite with coverage.

  5. Run the project:

    Terminal window
    make dev
  6. Open the API docs at http://localhost:8000/docs to try a request from the browser.

  7. Or, in another terminal, make a few requests with curl:

    Terminal window
    # A page of opportunities, most recently modified first
    curl 'http://localhost:8000/common-grants/opportunities?pageSize=2'
    # Filtered and sorted search
    curl -X POST http://localhost:8000/common-grants/opportunities/search \
    -H 'Content-Type: application/json' \
    -d '{"filters":{"status":{"operator":"in","value":["open"]}},"sorting":{"sortBy":"title","sortOrder":"asc"}}'
    # The OpenAPI document, generated from the SDK's models
    curl http://localhost:8000/openapi.json

    Press Ctrl+C in the server’s terminal to stop it when you’re done.

The template includes the following files and directories:

  • Makefile # Development workflow commands
  • README.md # Project documentation
  • PORTING.md # Walkthrough for connecting your own data
  • pyproject.toml # Python project configuration and dependencies
  • poetry.lock # Locked versions of dependencies
  • .coveragerc # Test coverage configuration
  • .gitignore # Files Git ignores
  • Directorysrc/
    • Directorycommon_grants/
      • api.py # FastAPI application setup; choose the data source here
      • constants.py # Set ORGANIZATION_DOMAIN to your domain for stable opportunity IDs
      • Directorydata/ # Bundled sample opportunities
        • …
      • Directoryroutes/ # API route handlers
        • …
      • Directoryschemas/ # The opportunity model the API serves
        • …
      • Directoryscripts/ # OpenAPI generator
        • …
      • Directoryservices/ # The data source interface and its sample-data implementation
        • …
  • Directorytests/ # Test suites for the app, routes, sample data, and OpenAPI document
    • …

Once the template is running, validate your spec and connect the API to your data.

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

Terminal window
make gen-openapi
Terminal window
pnpm dlx @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.

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 routes and services already use the SDK’s models, and src/common_grants/schemas/opportunity.py defines the opportunity model the API serves as the SDK’s OpportunityBase. 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 data operations for the API. repository.py defines the OpportunityRepository interface behind these routes, and fixtures.py implements it over the bundled sample data:

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

Specific changes to make:

  • Implement the interface’s list, get, and search methods against a real data source, e.g. a database query or a remote API call, including the sorting and filtering in search, and validate each record with an SDK model.
  • Pass your implementation to create_app() in src/common_grants/api.py in place of fixture_repository.

The template’s routes already omit optional fields you don’t set instead of sending them as null. Its PORTING.md walks through stable IDs, date and money handling, and which tests to keep.

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. Replace the contents of the template’s opportunity model file with it, since the routes, response models, and services all read Opportunity from there:

src/common_grants/schemas/opportunity.py
"""Custom fields for this API's data source."""
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: CustomField[int] | None = 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.opportunity 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

The template’s response models and services are built on Opportunity, so they serve the custom field and make check-types still passes. 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.

The common-grants-sdk package provides Pydantic models, an extension framework, and an HTTP client that match protocol v0.5. The template depends on SDK 0.9. If your project started from an earlier version of the template, which depended on SDK 0.8, 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 earlier versions of the template pass camelCase keyword arguments. The app and tests still run, but make check-types reports errors until you rename the arguments. In the template, SearchSorting(sortBy=...) in src/common_grants/routes/opportunities.py becomes SearchSorting(sort_by=...), and PaginatedBodyParams(pageSize=...) in tests/test_fixtures.py becomes PaginatedBodyParams(page_size=...). Leave sortOrder= alone, since the template’s SearchSorting declares that field with its camelCase alias, and 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