Using Python
Learn how to implement a CommonGrants API in Python using the FastAPI web framework and the CommonGrants Python SDK.
Quickstart
Section titled “Quickstart”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.
First steps
Section titled “First steps”Get a FastAPI project up and running with the following steps:
-
Open the FastAPI template repository on GitHub and click Use this template to create your own repository from it.
-
Clone your new repository:
Terminal window git clone https://github.com/<you>/<your-api>.gitcd <your-api> -
Install the dependencies:
Terminal window make installIf Poetry picks an older interpreter, run
poetry env use python3.11first. -
Check that everything works before you change anything:
Terminal window make ciThis runs the format, lint, and type checks, then the test suite with coverage.
-
Run the project:
Terminal window make dev -
Open the API docs at
http://localhost:8000/docsto try a request from the browser. -
Or, in another terminal, make a few requests with
curl:Terminal window # A page of opportunities, most recently modified firstcurl 'http://localhost:8000/common-grants/opportunities?pageSize=2'# Filtered and sorted searchcurl -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 modelscurl http://localhost:8000/openapi.jsonPress
Ctrl+Cin the server’s terminal to stop it when you’re done.
Project structure
Section titled “Project structure”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
- …
Next steps
Section titled “Next steps”Once the template is running, validate your spec and connect the API to your data.
Validate your spec
Section titled “Validate your spec”Generate the OpenAPI spec from the FastAPI app and check it against the CommonGrants v0.5 base spec:
make gen-openapipnpm dlx @common-grants/cli@0.5.0 check spec openapi.yaml --protocol-version 0.5.0npx @common-grants/cli@0.5.0 check spec openapi.yaml --protocol-version 0.5.0bunx @common-grants/cli@0.5.0 check spec openapi.yaml --protocol-version 0.5.0The 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.
Validate data with the SDK
Section titled “Validate data with the SDK”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 protocolopportunity = OpportunityBase.model_validate(raw_data)Implementing services
Section titled “Implementing services”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/opportunitiesGET /common-grants/opportunities/{oppId}POST /common-grants/opportunities/search
Specific changes to make:
- Implement the interface’s
list,get, andsearchmethods against a real data source, e.g. a database query or a remote API call, including the sorting and filtering insearch, and validate each record with an SDK model. - Pass your implementation to
create_app()insrc/common_grants/api.pyin place offixture_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.
Adding custom fields
Section titled “Adding custom fields”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.
Define a plugin
Section titled “Define a plugin”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:
"""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 OpportunityBasefrom 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 fieldsOpportunity = my_plugin.schemas.Opportunity.common_schemaCustomField[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.
Use the plugin’s schema
Section titled “Use the plugin’s schema”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_fieldsif fields and fields.legacy_id: fields.legacy_id.value # intThe 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.
Upgrading from an earlier SDK
Section titled “Upgrading from an earlier SDK”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:
poetry add common-grants-sdk@^0.9.0The 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:
make check-typesmake test