Building a Python API
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 upgrading 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:
-
Create a new directory for your project:
Terminal window mkdir common-grants-apicd common-grants-api -
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-apinpxships with Node.js. Bun users can runbunxinstead.pnpm dlxcan’t runcg init.The command also leaves
main.tsp,tspconfig.yaml,package.json,package-lock.json, andnode_modules/behind. The Python project doesn’t use them, so you can delete them. -
Install the dependencies:
Terminal window make installIf Poetry picks an older interpreter, run
poetry env use python3.11first. -
Run the project:
Terminal window make dev -
Open the API docs at
http://localhost:8000/docs. PressCtrl+Cin the terminal to stop the server 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
- 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
- …
Next steps
Section titled “Next steps”Once the template is running, upgrade the SDK and connect the API to your data.
Upgrade the SDK
Section titled “Upgrade the SDK”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:
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 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:
make check-typesmake testValidate 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-openapinpx @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. 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.
Validate data with the SDK
Section titled “Validate data with the SDK”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 protocolopportunity = OpportunityBase.model_validate(raw_data)Implementing services
Section titled “Implementing services”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/opportunitiesGET /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_opportunitiesmethod. - Add
response_model_exclude_unset=Trueto each route decorator insrc/common_grants/routes/opportunities.py, so optional fields you don’t set are omitted instead of sent asnull, which the protocol rejects.
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:
"""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 OpportunityBasefrom 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 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.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_fieldsif fields and fields.legacy_id: fields.legacy_id.value # intAt 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.