# Create bill
Source: https://docs.grainledger.com/api-reference/bills/create-bill
/openapi.json post /api/v1/bills
# Delete bill
Source: https://docs.grainledger.com/api-reference/bills/delete-bill
/openapi.json delete /api/v1/bills/{id}
# Get bill
Source: https://docs.grainledger.com/api-reference/bills/get-bill
/openapi.json get /api/v1/bills/{id}
# List bills
Source: https://docs.grainledger.com/api-reference/bills/list-bills
/openapi.json get /api/v1/bills
# Update bill
Source: https://docs.grainledger.com/api-reference/bills/update-bill
/openapi.json patch /api/v1/bills/{id}
# List accounts
Source: https://docs.grainledger.com/api-reference/coding-reference-data/list-accounts
/openapi.json get /api/v1/accounts
Returns active postable chart-of-accounts entries ordered by account number. Summary accounts are excluded. Not paginated. Requires accounts:read.
# List dimensions
Source: https://docs.grainledger.com/api-reference/coding-reference-data/list-dimensions
/openapi.json get /api/v1/dimensions
Returns active dimensions (such as Department, Location, or Project) with their active values. Not paginated. Requires accounts:read.
# List vendors
Source: https://docs.grainledger.com/api-reference/coding-reference-data/list-vendors
/openapi.json get /api/v1/vendors
Returns active vendors ordered by name. Not paginated. Requires vendors:read.
# Create contribution
Source: https://docs.grainledger.com/api-reference/contributions/create-contribution
/openapi.json post /api/v1/contributions
Use Idempotency-Key for duplicate-safe retries. The same key and validated input return the existing contribution (201); different input or a deleted original returns 409. Keys are scoped to organization and OAuth application, API key, or unmanaged OAuth user. External IDs alone do not deduplicate split gifts.
# Delete contribution
Source: https://docs.grainledger.com/api-reference/contributions/delete-contribution
/openapi.json delete /api/v1/contributions/{id}
# Get contribution
Source: https://docs.grainledger.com/api-reference/contributions/get-contribution
/openapi.json get /api/v1/contributions/{id}
# List contributions
Source: https://docs.grainledger.com/api-reference/contributions/list-contributions
/openapi.json get /api/v1/contributions
# Update contribution
Source: https://docs.grainledger.com/api-reference/contributions/update-contribution
/openapi.json patch /api/v1/contributions/{id}
# Create donor
Source: https://docs.grainledger.com/api-reference/donors/create-donor
/openapi.json post /api/v1/donors
# Delete donor
Source: https://docs.grainledger.com/api-reference/donors/delete-donor
/openapi.json delete /api/v1/donors/{id}
# Get donor
Source: https://docs.grainledger.com/api-reference/donors/get-donor
/openapi.json get /api/v1/donors/{id}
# List donors
Source: https://docs.grainledger.com/api-reference/donors/list-donors
/openapi.json get /api/v1/donors
# Update donor
Source: https://docs.grainledger.com/api-reference/donors/update-donor
/openapi.json patch /api/v1/donors/{id}
# List funds
Source: https://docs.grainledger.com/api-reference/funds/list-funds
/openapi.json get /api/v1/funds
Returns all active, assignable funds in the authenticated organization, ordered by name. Inactive funds and summary funds (funds with subfunds) are excluded. The response is not paginated. Use each id as fundId when creating contributions or mapping giving-provider funds. Requires funds:read for organization API keys and Grain-managed OAuth apps; OAuth users must also have permission to view funds. Existing keys and OAuth grants must explicitly include the new scope.
# Create giving batch
Source: https://docs.grainledger.com/api-reference/giving-batches/create-giving-batch
/openapi.json post /api/v1/batches
Creates an empty or populated batch without posting accounting. contributionIds atomically replace membership.
# Delete giving batch
Source: https://docs.grainledger.com/api-reference/giving-batches/delete-giving-batch
/openapi.json delete /api/v1/batches/{id}
Unlinks and preserves contributions. Accounting-frozen resources return 409.
# Get giving batch
Source: https://docs.grainledger.com/api-reference/giving-batches/get-giving-batch
/openapi.json get /api/v1/batches/{id}
# List giving batches
Source: https://docs.grainledger.com/api-reference/giving-batches/list-giving-batches
/openapi.json get /api/v1/batches
Returns giving batches, not pledge-card review batches. Totals are derived from current contribution membership.
# Update giving batch
Source: https://docs.grainledger.com/api-reference/giving-batches/update-giving-batch
/openapi.json patch /api/v1/batches/{id}
Recalculates totals after amount, fee, or membership changes. SETTLED is an accounting-owned state and cannot be set here.
# Add household member
Source: https://docs.grainledger.com/api-reference/households/add-household-member
/openapi.json post /api/v1/households/{id}/members
Moves the donor from an existing household when necessary and atomically refreshes both households. Cross-organization references are rejected.
# Create household
Source: https://docs.grainledger.com/api-reference/households/create-household
/openapi.json post /api/v1/households
# Delete household
Source: https://docs.grainledger.com/api-reference/households/delete-household
/openapi.json delete /api/v1/households/{id}
# Get household
Source: https://docs.grainledger.com/api-reference/households/get-household
/openapi.json get /api/v1/households/{id}
# List households
Source: https://docs.grainledger.com/api-reference/households/list-households
/openapi.json get /api/v1/households
# Remove household member
Source: https://docs.grainledger.com/api-reference/households/remove-household-member
/openapi.json delete /api/v1/households/{id}/members/{donorId}
Unlinks the donor without deleting the donor and clears primary contact when applicable.
# Update household
Source: https://docs.grainledger.com/api-reference/households/update-household
/openapi.json patch /api/v1/households/{id}
# Update household member
Source: https://docs.grainledger.com/api-reference/households/update-household-member
/openapi.json patch /api/v1/households/{id}/members/{donorId}
# List authorized organizations
Source: https://docs.grainledger.com/api-reference/organizations/list-authorized-organizations
/openapi.json get /api/v1/organizations
Returns organizations the current user has an active Grain-managed OAuth grant for, for this client. Does not require X-Organization-Id. Unmanaged OAuth clients and API keys cannot call this endpoint.
# Import pledge card data for review
Source: https://docs.grainledger.com/api-reference/pledge-card-imports/import-pledge-card-data-for-review
/openapi.json post /api/v1/pledge-card-imports
Creates a pledge card review group from structured data. Rows enter the same donor matching and review workflow as scanned cards; this request does not create pledges.
# List pledge card import reference data
Source: https://docs.grainledger.com/api-reference/pledge-card-imports/list-pledge-card-import-reference-data
/openapi.json get /api/v1/pledge-card-imports/reference-data
Returns valid scan groups, campaigns, active Grain funds, Rock campuses, and the complete mapped and unmapped Rock account catalog. Use exact IDs from this response when routing imports.
# Create pledge
Source: https://docs.grainledger.com/api-reference/pledges/create-pledge
/openapi.json post /api/v1/pledges
# Delete pledge
Source: https://docs.grainledger.com/api-reference/pledges/delete-pledge
/openapi.json delete /api/v1/pledges/{id}
# Get pledge
Source: https://docs.grainledger.com/api-reference/pledges/get-pledge
/openapi.json get /api/v1/pledges/{id}
# List pledges
Source: https://docs.grainledger.com/api-reference/pledges/list-pledges
/openapi.json get /api/v1/pledges
# Update pledge
Source: https://docs.grainledger.com/api-reference/pledges/update-pledge
/openapi.json patch /api/v1/pledges/{id}
# Create settlement
Source: https://docs.grainledger.com/api-reference/settlements/create-settlement
/openapi.json post /api/v1/settlements
Creates a resource record only. It never posts a journal entry, links a bank transaction, or reconciles accounting. contributionIds and givingBatchIds are applied atomically.
# Delete settlement
Source: https://docs.grainledger.com/api-reference/settlements/delete-settlement
/openapi.json delete /api/v1/settlements/{id}
Unlinks and preserves contributions and giving batches. Accounting-frozen resources return 409.
# Get settlement
Source: https://docs.grainledger.com/api-reference/settlements/get-settlement
/openapi.json get /api/v1/settlements/{id}
# List settlements
Source: https://docs.grainledger.com/api-reference/settlements/list-settlements
/openapi.json get /api/v1/settlements
Returns recorded totals and independently calculated totals from linked contributions. dateFrom/dateTo filter the UTC calendar arrival day; dateTo is inclusive to callers.
# Update settlement
Source: https://docs.grainledger.com/api-reference/settlements/update-settlement
/openapi.json patch /api/v1/settlements/{id}
All relationship writes are tenant-scoped and atomic. Accounting-frozen settlements return 409.
# Approve a transaction
Source: https://docs.grainledger.com/api-reference/transactions/approve-a-transaction
/openapi.json post /api/v1/transactions/{id}/approve
Posts the transaction's journal entry to the ledger. Requires the transactions:approve scope. Safe to retry; approving an approved transaction returns it unchanged. Fails when required dimensions are missing or the period is locked.
# Code or split a transaction
Source: https://docs.grainledger.com/api-reference/transactions/code-or-split-a-transaction
/openapi.json put /api/v1/transactions/{id}/coding
Creates or replaces the transaction's draft journal entry. Approved transactions must be unapproved first, and reconciled transactions cannot be recoded. Returns 409 when the transaction is in an open reconciliation.
# Create transaction
Source: https://docs.grainledger.com/api-reference/transactions/create-transaction
/openapi.json post /api/v1/transactions
Creates an uncategorized transaction. Grain queues rule and AI categorization after creation. Use Idempotency-Key for duplicate-safe retries: the same key and body return the existing transaction (201); a different body or a deleted original returns 409. To code the transaction yourself, follow with PUT /transactions/{id}/coding.
# Delete an attachment
Source: https://docs.grainledger.com/api-reference/transactions/delete-an-attachment
/openapi.json delete /api/v1/transactions/{id}/attachments/{fileId}
# Delete transaction
Source: https://docs.grainledger.com/api-reference/transactions/delete-transaction
/openapi.json delete /api/v1/transactions/{id}
Reconciled transactions cannot be deleted.
# Get an attachment download URL
Source: https://docs.grainledger.com/api-reference/transactions/get-an-attachment-download-url
/openapi.json get /api/v1/transactions/{id}/attachments/{fileId}/download
Returns a signed URL that expires after 15 minutes.
# Get transaction by ID
Source: https://docs.grainledger.com/api-reference/transactions/get-transaction-by-id
/openapi.json get /api/v1/transactions/{id}
# List transaction attachments
Source: https://docs.grainledger.com/api-reference/transactions/list-transaction-attachments
/openapi.json get /api/v1/transactions/{id}/attachments
Returns receipts and other documents attached to the transaction, newest first.
# List transactions
Source: https://docs.grainledger.com/api-reference/transactions/list-transactions
/openapi.json get /api/v1/transactions
Returns bank, card, and manual transactions with their coding. Comma-separated ID filters match any listed ID.
# Set transaction dimensions
Source: https://docs.grainledger.com/api-reference/transactions/set-transaction-dimensions
/openapi.json put /api/v1/transactions/{id}/dimensions
Replaces the header dimensions and mirrors them to the category line of a single-account entry. Split lines keep their own dimensions; set those with PUT /transactions/{id}/coding.
# Unapprove a transaction
Source: https://docs.grainledger.com/api-reference/transactions/unapprove-a-transaction
/openapi.json post /api/v1/transactions/{id}/unapprove
Returns a posted journal entry to draft so it can be recoded. Requires the transactions:approve scope. Safe to retry.
# Uncategorize a transaction
Source: https://docs.grainledger.com/api-reference/transactions/uncategorize-a-transaction
/openapi.json delete /api/v1/transactions/{id}/coding
Deletes the transaction's draft journal entry and returns it to review. Approved transactions return 409; unapprove them first. Reconciled transactions cannot be uncategorized.
# Update transaction
Source: https://docs.grainledger.com/api-reference/transactions/update-transaction
/openapi.json patch /api/v1/transactions/{id}
Description, reference number, and date changes are copied to the linked journal entry. Changing the vendor re-attributes the journal entry.
# Upload a receipt
Source: https://docs.grainledger.com/api-reference/transactions/upload-a-receipt
/openapi.json post /api/v1/transactions/{id}/attachments
Attaches a PDF or image (JPEG, PNG, GIF, WebP, or HEIC) of up to 5 MB. Requires transactions:write.
# Authentication
Source: https://docs.grainledger.com/authentication
Organization API keys and OAuth 2.1 for API access.
The Grain API supports two authentication methods:
* **Organization API keys** for server automation owned by one church. This is the fastest way to test the production API.
* **OAuth 2.1 (Sign in with Grain)** for applications that act on behalf of individual users, including Grain-managed OAuth apps that can connect many churches.
MCP access requires Growth or Scale. Organization API keys and unmanaged OAuth sessions require an active Scale plan for the church you are accessing. Grain-managed OAuth apps with an active grant may call `/api/v1` on Starter and Growth; Draft apps are limited to their publisher organization.
Store API keys, access tokens, and refresh tokens in a secrets manager. Never expose credentials in client-side code, logs, or public repositories.
## Organization API keys
An Owner, Admin, or custom role with **Manage API access** can create a key in **Settings → API**. Give the key a descriptive name, choose the smallest required scope set, and select an expiry. The secret is displayed only once.
Production organizations receive keys beginning with `grain_live_`. Sandbox, demo, and test organizations receive `grain_test_` keys.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl "https://api.grainledger.com/api/v1/transactions?page=1&limit=20" \
-H "Authorization: Bearer grain_live_YOUR_KEY"
```
The key determines its organization, so `X-Organization-Id` is optional. If you include the header, it must match the key's organization. API keys work only under `/api/v1`; they cannot sign in to the Grain app, call tRPC or MCP, or authenticate directly with the identity provider.
### API key scopes
| Resource | Read | Write |
| - | - | - |
| Funds | `funds:read` | — |
| Accounts and dimensions | `accounts:read` | — |
| Vendors | `vendors:read` | — |
| Transactions | `transactions:read` | `transactions:write` |
| Transaction approval | — | `transactions:approve` |
| Bills | `bills:read` | `bills:write` |
| Donors | `donors:read` | `donors:write` |
| Contributions | `contributions:read` | `contributions:write` |
| Pledges | `pledges:read` | `pledges:write` |
| Households | `households:read` | `households:write` |
| Pledge card imports | — | `pledge-cards:write` |
Write access includes the corresponding read access. `transactions:write` codes transactions and manages receipts but cannot post to the ledger; approving or unapproving requires `transactions:approve`, so you can let an integration prepare entries for a person to approve. The Read/write preset doesn't include `transactions:approve`; choose **Custom** to add it. Donor and household scopes can expose personal information. Contribution and pledge responses include donor IDs but never embed donor identity; use a donor read scope to retrieve the related donor separately.
### Rotation and revocation
Rotating a key displays a new secret once. The previous secret remains valid for up to 24 hours, or until its original expiry if sooner, so you can update automation without downtime. You can revoke the previous secret immediately after deployment. Full revocation permanently disables both secrets; the named key stays visible for audit history.
Grain-managed OAuth client secrets are different: rotating a confidential app secret replaces it immediately. The previous secret stops working as soon as rotation succeeds.
## OAuth 2.1 flow
Send the user to `https://auth.grainledger.com/auth/v1/oauth/authorize` with your client ID, redirect URI, scopes, and PKCE parameters (`code_challenge` and `code_challenge_method=S256`).
The user signs in (if needed) and approves access at `https://app.grainledger.com/oauth/consent`.
Grain redirects back to your `redirect_uri` with an authorization `code` and `state` parameter.
POST the code to `https://auth.grainledger.com/auth/v1/oauth/token` with your `code_verifier` to receive access and refresh tokens. Confidential clients also authenticate with HTTP Basic using their client ID and secret.
Include `Authorization: Bearer ` and `X-Organization-Id` on resource requests. Grain-managed apps may first call `GET /api/v1/organizations` without that header to discover churches the user authorized for this client.
## Grain-managed OAuth apps
Publisher organizations register apps in **Settings → API → Apps**. Connecting churches complete org and Grain-scope consent at `https://app.grainledger.com/oauth/consent`. Effective permission is the intersection of the app's maximum scopes, the user's consented scopes, and the user's current role.
Use PKCE S256 for both public and confidential clients. A Draft app can connect only its publisher organization, which supports localhost integration testing before publication. Grain checks app status, the installation, and the grant on every `/api/v1` request. Disabling the app or revoking a grant takes effect on the next API call.
If the user has SMS two-factor authentication enrolled, Grain requires a fresh challenge while the connection is authorized. OAuth access tokens returned by both the code exchange and refresh remain truthfully marked `aal1`; Grain records the separate, server-verified MFA result on the managed app grant. Integrators should not reject an otherwise valid token solely because its `aal` is `aal1`.
If Grain returns `Reconnect this application and complete two-factor authentication.`, start a new authorization-code flow so the user can complete the fresh challenge. Grain also requires reconnection if the verified phone factor used to authorize the grant is later removed.
Rate limits are 100 requests per minute per target organization **and** 100 requests per minute per application.
## OAuth endpoints
| Purpose | URL |
| - | - |
| Authorization | `https://auth.grainledger.com/auth/v1/oauth/authorize` |
| Token | `https://auth.grainledger.com/auth/v1/oauth/token` |
| Consent UI | `https://app.grainledger.com/oauth/consent` |
| OAuth discovery | `https://pqnoojlycpbwbatbdgep.supabase.co/.well-known/oauth-authorization-server/auth/v1` |
| OIDC discovery | `https://pqnoojlycpbwbatbdgep.supabase.co/auth/v1/.well-known/openid-configuration` |
| MCP PRM | `https://api.grainledger.com/.well-known/oauth-protected-resource` |
## MCP (AI agents)
Grain exposes a read-only MCP server at `https://api.grainledger.com/mcp` for ChatGPT and other MCP clients. MCP uses the same OAuth identity and organization permissions; org scoping is via `organizationId` in tool arguments instead of `X-Organization-Id`. See [MCP](/mcp-server).
MCP is read-only because it exposes only read tools. OAuth tokens still identify the signed-in user, and Grain checks organization permissions on each tool call.
## Authorization request example
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
https://auth.grainledger.com/auth/v1/oauth/authorize
?response_type=code
&client_id=YOUR_CLIENT_ID
&redirect_uri=https://yourapp.com/oauth/callback
&scope=openid%20email%20profile
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
&state=af0ifjsldkj
```
Generate `code_challenge` as the Base64URL-encoded SHA-256 hash of a random `code_verifier` string. Keep the verifier secret until the token exchange.
The authorization server's `scope` parameter accepts standard OIDC scopes such as `openid email profile`. Do not send Grain resource scopes such as `donors:read` there. Grain resource scopes come from the app registration and the user's Grain consent selection.
## Token exchange
```bash Public client theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST "https://auth.grainledger.com/auth/v1/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "code=AUTHORIZATION_CODE" \
-d "redirect_uri=https://yourapp.com/oauth/callback" \
-d "client_id=YOUR_CLIENT_ID" \
-d "code_verifier=YOUR_CODE_VERIFIER"
```
```bash Confidential client theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST "https://auth.grainledger.com/auth/v1/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET" \
-d "grant_type=authorization_code" \
-d "code=AUTHORIZATION_CODE" \
-d "redirect_uri=https://yourapp.com/oauth/callback" \
-d "code_verifier=YOUR_CODE_VERIFIER"
```
```javascript Node.js public client theme={"theme":{"light":"github-light","dark":"github-dark"}}
const tokenResponse = await fetch("https://auth.grainledger.com/auth/v1/oauth/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code,
redirect_uri: redirectUri,
client_id: clientId,
code_verifier: codeVerifier,
}),
});
```
## X-Organization-Id header with OAuth
Every OAuth API request must include the organization (church) whose data you are accessing:
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
X-Organization-Id: cm123abc456def
```
Users can belong to multiple organizations. Unmanaged OAuth does not scope to a single org; your application specifies the org per request. Grain-managed apps can list authorized organizations first. See [Organizations](/organizations) for how to obtain the ID.
## OAuth scopes
Standard OIDC scopes control user profile data in tokens:
| Scope | Description |
| - | - |
| `openid` | OpenID Connect identity |
| `email` | Email address |
| `profile` | Name and profile information |
| `phone` | Phone number |
API access for unmanaged OAuth follows the signed-in user's role. Grain-managed apps also intersect that role with the app's maximum scopes and the scopes the user consented to.
## Rate limits
`/api/v1` allows 100 requests per minute per target organization. Grain-managed OAuth apps have a second budget of 100 requests per minute per application so one client cannot fan out across installations.
## Diagnose API errors
Every Grain API response includes a server-generated `X-Request-Id` header. Save it with your integration logs and include it in support requests. The same ID links authenticated API activity to any resulting audit records.
Schema validation failures return safe field names and machine-readable validation codes:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"code": "bad_request",
"message": "Request validation failed. Check the listed fields.",
"error": "Request validation failed. Check the listed fields.",
"details": { "fields": [{ "field": "amount", "code": "invalid_type" }] }
}
```
`details.fields` contains up to 20 issues. A field reported as `request` refers to an unlisted or nested field. Submitted values are omitted. Authenticated scope denials and rate-limit responses are recorded in API activity; rejections before authentication are recorded in server diagnostics without trusting a supplied organization ID. Organization discovery is not included in per-organization activity.
For contribution retry behavior, see [Retry contribution creates safely](/giving#retry-contribution-creates-safely).
## Example API request
```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X GET "https://api.grainledger.com/api/v1/donors?page=1&limit=20" \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
-H "X-Organization-Id: cm123abc456def" \
-H "Content-Type: application/json"
```
```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch(
"https://api.grainledger.com/api/v1/donors?page=1&limit=20",
{
headers: {
Authorization: `Bearer ${accessToken}`,
"X-Organization-Id": organizationId,
"Content-Type": "application/json",
},
}
);
```
```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
response = requests.get(
"https://api.grainledger.com/api/v1/donors",
params={"page": 1, "limit": 20},
headers={
"Authorization": f"Bearer {access_token}",
"X-Organization-Id": organization_id,
},
)
```
## Token refresh
Use the refresh token from the token exchange to obtain new access tokens when they expire:
```bash Public client theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST "https://auth.grainledger.com/auth/v1/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "refresh_token=YOUR_REFRESH_TOKEN" \
-d "client_id=YOUR_CLIENT_ID"
```
```bash Confidential client theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST "https://auth.grainledger.com/auth/v1/oauth/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-u "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET" \
-d "grant_type=refresh_token" \
-d "refresh_token=YOUR_REFRESH_TOKEN"
```
Refresh tokens before they expire to avoid interrupting active integrations.
# Errors
Source: https://docs.grainledger.com/errors
HTTP status codes and error response format for the Grain API.
The Grain API uses standard HTTP status codes. Error responses include a JSON body with a `message` field describing what went wrong.
## Error response format
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "You do not have access to this organization."
}
```
Some validation errors may include additional fields depending on the endpoint.
## Common status codes
| Status | Meaning | Typical cause |
| - | - | - |
| `400` | Bad request | Missing OAuth `X-Organization-Id` header or invalid request body |
| `401` | Unauthorized | Missing/expired OAuth token or malformed, unknown, expired, or revoked API key |
| `403` | Forbidden | Missing API-key scope, user permission, matching organization access, or required plan |
| `404` | Not found | Resource ID does not exist in the organization |
| `409` | Conflict | Duplicate record (for example donor with same name and email) |
| `422` | Unprocessable entity | Validation failed on one or more fields |
| `429` | Too many requests | Rate limit exceeded |
| `500` | Server error | Unexpected error; retry with backoff |
## Authentication errors
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "Authentication required. Provide a valid Bearer token."
}
```
Refresh your OAuth access token, re-run OAuth, or rotate the organization API key. API-key failures use one generic response so callers cannot probe key state.
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "X-Organization-Id header is required for all API requests."
}
```
Add the header to OAuth requests. It is optional for organization API keys. See [Organizations](/organizations).
A valid API key does not include the scope required by the endpoint. Create a replacement key with the needed scope; existing key scopes cannot be edited.
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "REST API access is available on the Scale plan."
}
```
Organization API keys and unmanaged OAuth REST requests require an active Scale subscription. Grain-managed OAuth apps with an active grant can call `/api/v1` on Starter and Growth. MCP access is available on Growth and Scale.
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "You do not have access to this organization."
}
```
The authenticated user is not a member of the organization in `X-Organization-Id`.
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"message": "Reconnect this application and complete two-factor authentication."
}
```
Start a new Grain OAuth authorization-code flow. This can occur when an MFA-enrolled user authorized the app before the grant recorded MFA assurance. Grain also requires reconnection if the verified phone factor is removed after authorization.
## Handling errors in your integration
Log the status code and `message` field for debugging. Do not log full Bearer tokens.
```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch(url, { headers });
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(`Grain API ${response.status}: ${error.message ?? response.statusText}`);
}
```
```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
response = requests.get(url, headers=headers)
if not response.ok:
error = response.json() if response.content else {}
raise RuntimeError(
f"Grain API {response.status_code}: {error.get('message', response.reason)}"
)
```
## Rate limiting
When you exceed the per-organization rate limit, the API returns `429` with rate limit headers. Wait until `X-RateLimit-Reset` before retrying. See [Introduction](/intro#rate-limits) for default limits.
# Giving resources
Source: https://docs.grainledger.com/giving
Work safely with donors, households, contributions, giving batches, and settlements.
Grain's giving API is a connected resource graph:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
donor ── member of ──> household
│
└── contribution ──> giving batch ──> settlement
│ │
└── fund └── bank and accounting status (read-only)
```
Lists include compact, one-level summaries. Fetch large related collections through their own paginated endpoints with `donorId`, `householdRef`, `givingBatchId`, or `settlementId` filters instead of expecting nested unbounded data.
## Map your giving funds
Call `GET /api/v1/funds` to populate a fund dropdown. Each result contains the Grain fund `id` and display `name`; store the selected `id` in your integration and send it as `fundId` when creating contributions.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body "https://api.grainledger.com/api/v1/funds" \
-H "Authorization: Bearer $GRAIN_API_KEY"
```
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"funds": [
{ "id": "cm789ghi012jkl", "name": "General Fund" }
]
}
```
The list includes all active, assignable funds in the authenticated church, ordered by name, with no pagination. Inactive funds and summary funds that contain subfunds are excluded. A church with no assignable funds receives `{ "funds": [] }`.
Enable `funds:read` on your organization API key or Grain-managed OAuth app. For OAuth, add this scope to the app's registered scopes and have users consent again; the signed-in user must have **View funds** permission. Send the OAuth access token as the bearer credential and include `X-Organization-Id` on the request. Existing keys and grants do not gain this scope automatically; create a replacement API key with fund access if needed.
## Retry contribution creates safely
Send an `Idempotency-Key` header with `POST /api/v1/contributions`. Choose a stable key for each gift row, such as `og-gift-38217-general`, and reuse it if a request times out or the connection drops.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body "https://api.grainledger.com/api/v1/contributions" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: og-gift-38217-general" \
--data '{"amount":3.33,"date":"2026-09-07","fundId":"YOUR_FUND_ID","method":"ONLINE","externalSource":"OTHER","externalId":"og-gift-38217"}'
```
* The first successful create and subsequent retries return `201` with the same contribution ID. Concurrent retries create one contribution.
* Reusing a key with different validated data returns `409 Conflict`. Use PATCH to edit the original gift, or a new key for a separate gift.
* If the original contribution was deleted, its key returns `409`; a retry cannot recreate it.
* Keys accept 1–200 non-space ASCII characters and remain reserved for the lifetime of the organization. Keep keys free of personal information.
* Keys are scoped to the organization and credential: the OAuth application, organization API key, or unmanaged OAuth user. OAuth token refresh preserves the namespace; replacing an API key starts a separate namespace.
* Authentication, permissions, and input validation apply to retries. A replay returns the contribution's current representation, including subsequent edits, with current identity-masking permissions.
* Validation failures do not reserve the key. Correct the input and retry.
The header is optional for compatibility. An `externalId` alone does not prevent duplicates: split gifts can legitimately share it. Use a different idempotency key for each split row, and reuse that row's key for retries. Before replaying older imports that did not use a key, reconcile your saved Grain contribution IDs; adding a key does not deduplicate an earlier unkeyed request.
## Who owns the totals?
* Contribution amounts, processing fees, and stored net amounts are the source for a giving batch. Grain recalculates batch gross, absolute fees, net, fund splits, and distinct gift count whenever membership or money changes.
* Settlement `recordedTotals` are provider or client-owned values and remain independently editable.
* Settlement `linkedContributionTotals` are calculated from current linked contributions. Compare the two objects to identify import or membership differences.
Dates such as contribution date, batch date, and estimated arrival date are calendar days. Grain returns existing v1 date fields as UTC ISO strings, with calendar days represented at UTC midnight. Audit timestamps such as `createdAt`, `updatedAt`, and `committedAt` are real instants.
## Create a manual batch
If `givingIntegrationId` and `externalBatchId` are omitted, Grain uses its non-syncing manual giving integration and generates an external ID. Empty open batches are valid.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body \
-X POST "https://api.grainledger.com/api/v1/batches" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"externalReference": "Sunday online gifts",
"batchDate": "2026-08-16",
"contributionIds": ["contribution_1", "contribution_2"]
}'
```
`contributionIds` replaces batch membership atomically. A contribution already owned by another batch produces `409 Conflict`; move it explicitly with `PATCH /api/v1/contributions/{id}` before the bulk membership write.
## Link a whole batch to a settlement
Settlement writes accept both individual `contributionIds` and whole `givingBatchIds`. Attaching a batch also attaches all of its contributions in the same transaction.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body \
-X POST "https://api.grainledger.com/api/v1/settlements" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"externalReference": "August online giving",
"estimatedArrivalDate": "2026-08-21",
"totalGross": 1025,
"totalFees": 25,
"totalNet": 1000,
"paymentCount": 8,
"givingBatchIds": ["batch_1"]
}'
```
All donors, funds, merchants, integrations, contributions, batches, and settlements referenced by a write must belong to the authenticated organization. Partial-batch or conflicting settlement ownership returns `409` without applying a partial change.
## Accounting freeze behavior
CRUD never posts a journal entry, links a bank transaction, or reconciles a settlement. `MATCHED`, `RECONCILED`, and batch `SETTLED` are accounting-owned states and cannot be created through ordinary API edits.
Unfrozen contributions, batches, and settlements can be edited, moved, or deleted. Once a resource is posted, cleared, bank-linked, or otherwise accounting-frozen, conflicting writes return `409 Conflict`. Deleting an unfrozen batch or settlement unlinks and preserves its contributions; deleting a contribution recalculates its former batch.
## Household members
Use the member routes to keep current membership, position, and primary contact consistent:
* `POST /api/v1/households/{id}/members`
* `PATCH /api/v1/households/{id}/members/{donorId}`
* `DELETE /api/v1/households/{id}/members/{donorId}`
Moving a donor refreshes both affected household aggregates. Send `null` in donor or household PATCH requests to clear documented nullable fields.
Give integrations separate `contributions`, `batches`, and `settlements`
scopes. Write scopes imply read, but they do not grant journal-posting
permission.
# Introduction
Source: https://docs.grainledger.com/intro
Get started with the Grain API for church accounting and donor management.
The Grain API lets you build integrations that read and write church accounting data: transactions, bills, donors, contributions, pledges, and households.
Use the read-only [fund list](/giving#map-your-giving-funds) to map giving-provider funds to Grain fund IDs.
MCP access is included on Growth and Scale. Organization API keys and unmanaged OAuth require an active Scale subscription. Grain-managed Live OAuth apps with an active grant may call `/api/v1` on Starter and Growth.
## What you can build
Sync bank transactions and vendor bills into your workflows.
Read contributions, pledges, and donor records for reporting or ChMS bridges.
Manage household groupings and primary contacts.
Authenticate users with Sign in with Grain (OAuth 2.1 + PKCE).
## Base URL
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
https://api.grainledger.com
```
For local development, use your server URL (for example `http://localhost:3000`).
## Prerequisites
Use an organization API key for church-owned server automation, or an OAuth 2.1 access token for an application acting on behalf of a user. OAuth requests also need `X-Organization-Id`; API keys infer their organization.
Start with the [API key quickstart](/quickstart), then see [Authentication](/authentication) for OAuth and credential lifecycle details.
## Rate limits
| Scope | Limit |
| - | - |
| Standard | 100 requests per minute per organization |
| Burst | Short bursts above the limit may return `429 Too Many Requests` |
Rate limit headers are included on responses:
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1710000060
```
Contact [Grain Support](https://grainledger.com/support) for higher limits on enterprise integrations.
## Next steps
Make your first authenticated API call in under 10 minutes.
Set up OAuth 2.1 with PKCE and token refresh.
Browse endpoints grouped by resource.
Get help from the Grain team.
# MCP (Model Context Protocol)
Source: https://docs.grainledger.com/mcp-server
Read-only remote MCP for AI agents and ChatGPT connectors.
## Overview
Grain exposes a **read-only** remote MCP server for AI agents and connector platforms, including ChatGPT, Claude, Cursor, and other MCP clients. MCP uses the same Grain OAuth identity and organization permissions as the REST API.
MCP access is included on Growth and Scale. The organization you query must have an active paid subscription.
| Item | Value |
| - | - |
| MCP endpoint | `https://api.grainledger.com/mcp` |
| Transport | Streamable HTTP |
| Auth | OAuth 2.1 (Sign in with Grain) |
| Access mode | Read-only tools only, with structured JSON results |
| Org scoping | Per tool call via `organizationId` |
## Authentication flow
1. MCP client discovers protected resource metadata from Grain.
2. Client completes OAuth 2.1 authorization code + PKCE with the Grain authorization server.
3. Grain issues a Supabase OAuth access token for the signed-in user.
4. Client calls MCP tools with `Authorization: Bearer `.
5. For data tools, pass `organizationId` from `list_organizations`.
### Protected resource metadata
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
GET https://api.grainledger.com/.well-known/oauth-protected-resource
```
Returns OAuth Protected Resource Metadata (RFC 9728) with:
* `resource`: `https://api.grainledger.com/mcp`
* `authorization_servers`: Grain OAuth issuer
Unauthenticated MCP requests receive `401` with:
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
WWW-Authenticate: Bearer resource_metadata="https://api.grainledger.com/.well-known/oauth-protected-resource"
```
See [Authentication](/authentication) for OAuth endpoints and consent.
## Organization scoping
MCP access tokens identify the signed-in user. Every data tool also requires `organizationId` so Grain knows which church's data to read:
1. Call `list_organizations` to get church IDs the user belongs to.
2. Pass `organizationId` on subsequent tool calls.
3. Permissions follow the user's role in that organization (same as the REST API).
Optional: call `get_my_permissions` to inspect allowed actions before querying data.
## Available tools (read-only)
| Tool | Description |
| - | - |
| `list_organizations` | Churches the user can access |
| `get_my_permissions` | User permissions in one organization |
| `list_transactions` / `get_transaction` | Minimized bank transaction data |
| `list_bills` / `get_bill` | Minimized vendor bills and payment summaries |
| `list_donors` / `get_donor` | Donors; contact PII is opt-in on detail calls |
| `list_contributions` / `get_contribution` | Contributions without processor metadata |
| `list_pledges` / `get_pledge` | Pledges and progress |
| `list_households` / `get_household` | Households; member contact PII is opt-in |
| `list_accounts` | Chart of accounts |
| `list_funds` | Fund summaries |
| `list_vendors` | Vendors without contact, bank, or tax identifiers |
| `list_journal_entries` | Journal entry summaries and posting status |
| `list_budgets` | Accessible budgets and IDs for budget reporting |
| `get_financial_overview` | Customer-ready period summary with comparison, transfers, balance sheet, funds, budget, reconciliation, and warnings |
| `get_statement_of_activities` | Statement of Activities for a period |
| `get_balance_sheet` | Balance Sheet with validation warnings |
| `get_fund_balance_report` | Fund balances, including cash-only view |
| `get_trial_balance` | Trial balance and balance validation |
| `get_general_ledger` | Account-scoped general ledger activity |
| `get_budget_vs_actual` | Budget-versus-actual reporting |
| `get_reconciliation_status` | Reconcilable accounts and in-progress work |
All tools are annotated `readOnlyHint: true` and return `structuredContent` validated against an output schema. JSON text is included for compatibility. Write operations are not exposed through MCP.
For broad prompts such as “Give me last month’s financial picture,” start with `get_financial_overview`. It separates interfund transfers from operating results, compares with the previous period or prior year, rounds currency amounts to cents, and surfaces accounting-quality warnings. Use the detailed report tools for follow-up questions.
List tools intentionally return summary DTOs rather than Grain's internal database or UI models. Billing identifiers, integration metadata, provider payloads, and unrelated PII are excluded. Organization permissions still apply on every tool call.
## Connect in Cursor
Install Grain in Cursor with one click, or add the configuration manually.
Install Grain's remote MCP server in Cursor.
Manual configuration:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"mcpServers": {
"grain": {
"url": "https://api.grainledger.com/mcp"
}
}
}
```
Cursor will prompt you to complete Sign in with Grain when it connects to the production MCP endpoint.
## Connect in ChatGPT
In ChatGPT, add Grain as a connector when it is available to your workspace. Use the MCP URL `https://api.grainledger.com/mcp` and complete the Sign in with Grain flow when prompted.
## Revoking access
Users approve access on the Grain OAuth consent screen. To revoke:
1. Sign in to Grain at `https://app.grainledger.com`
2. Remove the connected application from your account (OAuth connected apps)
3. Or deny future authorization requests from that client
## Example prompts
After connecting an MCP client, these prompts are useful smoke tests:
1. "List my Grain organizations"
2. "What permissions do I have in organization `{orgId}`?"
3. "Show the 10 most recent transactions for organization `{orgId}`"
4. "List open bills for organization `{orgId}`"
Expected behavior: read-only structured JSON results. If the user's role lacks the required permission, Grain returns a stable permission error. Invalid dates should be corrected to `YYYY-MM-DD`.
## Related
* [Authentication](/authentication) — OAuth 2.1 and Bearer tokens
* [Organizations](/organizations) — Organization IDs and membership
# Organizations
Source: https://docs.grainledger.com/organizations
How organization selection works for API keys and OAuth.
Grain is multi-tenant: each church is an **organization**. Most OAuth access tokens require `X-Organization-Id` so Grain knows which church's data to return. Organization API keys already identify one organization, making the header optional. Grain-managed OAuth apps may omit the header only on `GET /api/v1/organizations`.
## Header format
```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
X-Organization-Id: cm123abc456def
```
The value is a UUID-style organization ID (CUID in Grain's database).
With an API key, including a different organization ID returns `403`; a key can never be used to switch organizations.
## How users get an organization ID
When a user signs in to Grain, they may belong to one or more churches. Your OAuth flow authorizes the **user**, not a specific organization. Your application chooses which organization to access per request.
## Organization discovery for Grain-managed apps
Grain-managed OAuth apps can list churches the current user has an active grant for:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl "https://api.grainledger.com/api/v1/organizations" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```
The response includes only organizations with an active grant for this `client_id` and user. It does not list every membership. Unmanaged OAuth clients and API keys cannot call this endpoint.
If your integration serves a single church, store the organization ID after the user selects their church in your onboarding flow.
## Finding the ID in the Grain app
1. Sign in at [app.grainledger.com](https://app.grainledger.com)
2. Open the organization switcher (top of the sidebar)
3. The organization ID is available in organization settings or from your Grain contact during API onboarding
If you are building a partner integration, the Grain team provides the organization ID when API access is approved. [Request API access](https://grainledger.com/demo).
## Multi-organization OAuth users
A single user can be a member of multiple churches (for example a bookkeeper serving several clients). Your application should:
1. Let the user pick which church to work with
2. Send that organization's ID in `X-Organization-Id` on every request
3. Switch the header when the user changes churches
Permissions are evaluated per organization. A user with admin access at Church A may have read-only access at Church B.
## Example
```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X GET "https://api.grainledger.com/api/v1/transactions?page=1&limit=20" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "X-Organization-Id: cm123abc456def"
```
```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const organizationId = userSelectedOrgId; // from your app's org picker
const response = await fetch(
"https://api.grainledger.com/api/v1/transactions?page=1&limit=20",
{
headers: {
Authorization: `Bearer ${accessToken}`,
"X-Organization-Id": organizationId,
},
}
);
```
## Related
* [Authentication](/authentication) for OAuth setup
* [Errors](/errors) for `400` and `403` responses when the header is missing or invalid
# Pagination
Source: https://docs.grainledger.com/pagination
Page through list endpoints with page and limit query parameters.
List endpoints return paginated results. Use `page` and `limit` query parameters to control how many records you fetch per request.
## Query parameters
| Parameter | Type | Default | Description |
| - | - | - | - |
| `page` | integer | `1` | Page number (1-based) |
| `limit` | integer | `20` | Records per page |
Use `limit=100` or lower for most integrations. Some endpoints allow higher limits; check the API reference for per-endpoint maximums.
## Response shape
List endpoints return the resource array plus a `pagination` object:
```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
"donors": [ ... ],
"pagination": {
"page": 1,
"limit": 20,
"total": 142,
"totalPages": 8
}
}
```
| Field | Description |
| - | - |
| `page` | Current page number |
| `limit` | Page size used for this request |
| `total` | Total matching records |
| `totalPages` | Total pages at the current limit |
## Iterate through all pages
```javascript Node.js theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function fetchAllDonors(accessToken, organizationId) {
const donors = [];
let page = 1;
let totalPages = 1;
while (page <= totalPages) {
const response = await fetch(
`https://api.grainledger.com/api/v1/donors?page=${page}&limit=100`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
"X-Organization-Id": organizationId,
},
}
);
const data = await response.json();
donors.push(...data.donors);
totalPages = data.pagination.totalPages;
page += 1;
}
return donors;
}
```
```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import requests
def fetch_all_donors(access_token, organization_id):
donors = []
page = 1
total_pages = 1
while page <= total_pages:
response = requests.get(
"https://api.grainledger.com/api/v1/donors",
params={"page": page, "limit": 100},
headers={
"Authorization": f"Bearer {access_token}",
"X-Organization-Id": organization_id,
},
)
data = response.json()
donors.extend(data["donors"])
total_pages = data["pagination"]["totalPages"]
page += 1
return donors
```
## Endpoints that support pagination
All list endpoints use the same pagination pattern:
* [List transactions](/api-reference/transactions/list-transactions)
* [List bills](/api-reference/bills/list-bills)
* [List donors](/api-reference/donors/list-donors)
* [List contributions](/api-reference/contributions/list-contributions)
* [List pledges](/api-reference/pledges/list-pledges)
* [List households](/api-reference/households/list-households)
# Pledge card imports
Source: https://docs.grainledger.com/pledge-card-imports
Submit structured pledge card data and review it in Grain before creating pledges.
Use the pledge card import API when your church already has structured pledge data and does not need Grain to read scanned images. Each request creates a review batch, runs donor matching and duplicate checks, and returns a link where finance staff can review the rows.
The import does not create pledges automatically. Users with contribution management access review and confirm the submitted records in Grain just as they do with scanned pledge cards.
## Before importing from Rock
For exact person and fund routing, complete these steps first:
1. Install the current Grain plugin in Rock and let its scheduled job sync the financial account, campus, and person catalogs.
2. In Grain, map every Rock financial account that the workflow can submit. Map campus-specific child accounts as well as the parent fallback account.
3. Enable **Full directory** for the Rock integration and wait for the initial person sync to finish. This lets Grain resolve people who are in Rock but have never given.
4. Create a dedicated Digital Cards scan group in Grain if digital and scanned cards should be reviewed separately.
A Rock campus ID does not choose a financial account. The Rock workflow must
map each campus to the intended child `FinancialAccount.Id` and send it as
`rockAccountId`. Use `defaultRockAccountId` for the parent or other fallback
account when a card has no campus-specific account.
## Get valid routing IDs
Call the reference-data endpoint during setup and whenever the Rock account mappings change:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --request GET \
--url https://api.grainledger.com/api/v1/pledge-card-imports/reference-data \
--header "Authorization: Bearer $GRAIN_ACCESS_TOKEN" \
--header "X-Organization-Id: $GRAIN_ORGANIZATION_ID"
```
The response includes:
* `scanGroups`: Grain scan group IDs and their current campaign and default fund routing.
* `campaigns`: Active and draft Grain pledge campaign IDs.
* `funds`: Active Grain fund IDs for non-Rock integrations.
* `rockCampuses`: Exact Rock `Campus.Id` values recognized by Grain.
* `rockAccounts`: The complete Rock parent and child account catalog, including each account's path and mapping state.
Only submit a `rockAccountId` whose `mappingState` is `MAPPED` and `isActive` is `true`. `UNMAPPED`, `INACTIVE_FUND`, `AMBIGUOUS`, and `NOT_CATALOGED` accounts must be corrected in Grain first.
## Recommended Rock workflow payload
Send `POST /api/v1/pledge-card-imports` with your access token, organization ID, and a unique `Idempotency-Key`.
For a Rock digital pledge card workflow, send:
* `externalId`: The Rock workflow ID. Grain displays it during review and returns it in the item result.
* `rockPersonId`: The current Rock `Person.Id`. Grain uses it for exact identity routing instead of fuzzy donor matching.
* `rockAccountId`: The Rock `FinancialAccount.Id` selected by the workflow's campus-to-account mapping.
* `rockCampusId`: The Rock `Campus.Id`, when known. This provides campus context but does not select the account.
* `donorAddress2`: The second street-address line, when present.
* `scanGroupId`: The Grain ID for an existing Digital Cards scan group.
* `defaultRockAccountId`: The mapped parent or fallback Rock account for cards that do not include `rockAccountId`.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --request POST \
--url https://api.grainledger.com/api/v1/pledge-card-imports \
--header "Authorization: Bearer $GRAIN_ACCESS_TOKEN" \
--header "X-Organization-Id: $GRAIN_ORGANIZATION_ID" \
--header "Idempotency-Key: rock-workflow-run-882145" \
--header "Content-Type: application/json" \
--data '{
"scanGroupId": "CMRC90",
"defaultRockAccountId": "101",
"cards": [
{
"externalId": "882145",
"rockPersonId": "34567",
"rockAccountId": "204",
"rockCampusId": "3",
"donorFirstName": "Sarah",
"donorLastName": "Johnson",
"donorEmail": "sarah@example.org",
"donorAddress": "100 Church Street",
"donorAddress2": "Apartment 4",
"donorCity": "Nashville",
"donorState": "TN",
"donorZip": "37201",
"amount": 12000,
"frequency": "MONTHLY",
"startDate": "2027-01-01",
"endDate": "2027-12-31"
}
]
}'
```
When `scanGroupId` is supplied, Grain inherits the group's campaign. Do not
send `campaignId`. A supplied `defaultRockAccountId` overrides the group's
default fund for that batch, and a card-level `rockAccountId` overrides the
request default for that card.
## Create a new scan group
Omit `scanGroupId` and provide `name`, either `defaultRockAccountId` or `defaultFundId`, and your `cards`. Grain creates a new scan group and its first batch.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --request POST \
--url https://api.grainledger.com/api/v1/pledge-card-imports \
--header "Authorization: Bearer $GRAIN_ACCESS_TOKEN" \
--header "X-Organization-Id: $GRAIN_ORGANIZATION_ID" \
--header "Idempotency-Key: pledge-import-2027-digital-001" \
--header "Content-Type: application/json" \
--data '{
"name": "2027 digital pledge cards",
"defaultRockAccountId": "101",
"campaignId": "cm890jkl123mno",
"cards": [
{
"externalId": "882146",
"rockPersonId": "34568",
"donorFirstName": "Alex",
"donorLastName": "Rivera",
"amount": 6000,
"frequency": "MONTHLY"
}
]
}'
```
Use `defaultFundId` and card-level `fundId` only when the caller already has Grain fund IDs. Do not send `defaultFundId` with `defaultRockAccountId`, or `fundId` with `rockAccountId`.
## Add to an existing scan group
Pass `scanGroupId` to append cards as a new batch inside a group created in Grain or from a prior import.
Use the ID at the end of the scan group review URL, not the display name. For
example, if the URL ends in `/revenue/pledge-card-scan-groups/CMRC90`, send
`"scanGroupId": "CMRC90"`.
A request can contain between 1 and 500 cards and must be 2 MB or smaller.
## Retry safely
Use a new `Idempotency-Key` for each logical import. A Rock workflow run ID is a good basis for this value. If a request times out or its result is unclear, retry the exact request body with the same key. Grain returns the existing import instead of creating duplicate review rows.
Reusing a key with a different request body returns `409 Conflict`. If the original request is still processing, wait briefly and retry with the same key.
## Review import results
The response contains:
* `reviewUrl`: Opens the review group in Grain.
* `cardsImported`: Rows added to the review workflow.
* `cardsSkipped`: Exact duplicates retained as skipped audit rows.
* `cardsWithIssues`: Rows with missing, invalid, or unresolved business data that need attention.
* `items`: Per-card results mapped back through `externalId` when supplied, including Rock identity and account status.
An exact repeated `externalId` or card body is retained as a `SKIPPED` audit row instead of rejecting the entire request. Missing donor names, amounts, or dates do not discard an otherwise valid row. Grain imports the row with an issue so finance staff can correct it during review.
When `rockPersonId` is present, Grain does not fall back to fuzzy matching. The row reports `MATCHED`, `PENDING`, `NOT_FOUND`, or `CONFLICT` so staff can resolve the exact Rock identity without creating an accidental duplicate person.
The secured JSON audit artifact is retained by Grain, but it is not presented or synchronized as a scanned pledge card document. The visible `externalId` is the link back to the originating Rock workflow.
# Quickstart
Source: https://docs.grainledger.com/quickstart
Make your first production Grain API call with an organization API key.
Use a short-lived, read-only organization API key to verify the production API without involving customer records.
## 1. Choose a safe organization
Use a designated test, demo, or sandbox organization in production. Do not smoke-test against a real customer's records.
## 2. Create an API key
In Grain, open **Settings → API → Create key**.
1. Name it for the test, such as `Production API smoke test`.
2. Choose **Read only**.
3. Choose a short expiry.
4. Create the key and copy the secret immediately. Grain will not show it again.
Keep the key in a secrets manager or an ephemeral shell variable. Do not paste it into source code, screenshots, logs, or support messages.
## 3. Call the production API
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export GRAIN_API_KEY="grain_test_YOUR_KEY"
curl --fail-with-body \
"https://api.grainledger.com/api/v1/transactions?page=1&limit=20" \
-H "Authorization: Bearer $GRAIN_API_KEY"
```
The API key identifies its organization, so no organization header is needed. If you send `X-Organization-Id`, it must match the key.
A `200` response containing transaction data and pagination means authentication, organization inference, and read scope enforcement are working.
## 4. Verify lifecycle controls
For a complete smoke test:
1. Rotate the key and save the new secret.
2. Confirm both secrets work during the rotation window.
3. Revoke the previous secret and confirm it returns `401`.
4. Revoke the named key and confirm the new secret also returns `401`.
Invalid, expired, and revoked keys intentionally return the same generic `401` response. A valid key missing the required resource scope returns `403`.
## Building an app for users?
Use [OAuth 2.1](/authentication#oauth-21-flow) when an application acts on behalf of a Grain user or needs to serve multiple organizations. Grain-managed apps can discover authorized churches with `GET /api/v1/organizations`, then send `X-Organization-Id` on resource requests.
## Next steps
* [Authentication](/authentication) for scopes, rotation, OAuth, and token refresh
* [Organizations](/organizations) for organization-header behavior
* [Pagination](/pagination) for large result sets
* [Errors](/errors) for failed requests
# Transactions
Source: https://docs.grainledger.com/transactions
Create bank and card transactions, code them to accounts, funds, and dimensions, attach receipts, and approve them.
A transaction moves through three coding states, shown in `coding.status`:
```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
UNCATEGORIZED ──PUT /coding──> CATEGORIZED ──POST /approve──> APPROVED
^ │ ^ │
└────── DELETE /coding ──────┘ └──── POST /unapprove ─────┘
```
* **UNCATEGORIZED**: no journal entry. Grain's rules and AI may add a `suggestion`.
* **CATEGORIZED**: a draft journal entry exists. It does not affect reports until approved.
* **APPROVED**: the journal entry is posted to the ledger.
## Look up coding IDs
| Need | Endpoint | Scope |
| - | - | - |
| Account IDs | `GET /api/v1/accounts?accountType=EXPENSE` | `accounts:read` |
| Fund IDs | `GET /api/v1/funds` | `funds:read` |
| Dimension and value IDs | `GET /api/v1/dimensions` | `accounts:read` |
| Vendor IDs | `GET /api/v1/vendors` | `vendors:read` |
Only dimension values with `isAssignable: true` can be assigned. Parent values roll up for reporting. Dimensions with `isRequired: true` must be set before a transaction can be approved.
## Create a transaction without duplicates
Send your system's ID as `externalId` and a stable `Idempotency-Key` header. Reuse the same key if a request times out.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body "https://api.grainledger.com/api/v1/transactions" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: card-txn-8812" \
--data '{"description":"Office Depot","amount":184.32,"date":"2026-07-01","transactionType":"WITHDRAWAL","accountId":"YOUR_CARD_ACCOUNT_ID","externalId":"card-txn-8812"}'
```
* A retry with the same key and body returns `201` with the original transaction. A different body returns `409`.
* A second transaction with the same `externalId` returns `409`, even with a new key. Find the existing one with `GET /api/v1/transactions?externalId=card-txn-8812`.
* `amount` is always positive. `DEPOSIT` records money in; `WITHDRAWAL`, `TRANSFER`, and `ADJUSTMENT` record money out. The response's `direction` is `INFLOW` or `OUTFLOW`.
* `accountId` is the ledger cash, bank, or card account the transaction clears through. Transactions from a connected feed use `bankAccountId` instead.
Unknown fields are rejected with `400`.
## Code or split a transaction
`PUT /api/v1/transactions/{id}/coding` replaces the coding. Line amounts must add up to the transaction amount.
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body -X PUT "https://api.grainledger.com/api/v1/transactions/TXN_ID/coding" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-H "Content-Type: application/json" \
--data '{
"defaultFundId": "GENERAL_FUND_ID",
"lines": [
{ "accountId": "SUPPLIES_ID", "amount": 120, "dimensions": [{ "dimensionId": "DEPT_ID", "dimensionValueId": "ADMIN_ID" }] },
{ "accountId": "HOSPITALITY_ID", "fundId": "YOUTH_FUND_ID", "amount": 64.32, "memo": "Volunteer lunch" }
]
}'
```
* One line codes the transaction to a single account. Several lines split it across accounts, funds, or dimensions.
* A line's fund falls back to `defaultFundId`, then to the transaction's fund, then to the organization's default fund.
* A line without `dimensions` inherits the transaction's dimensions.
* Positive amounts allocate the transaction. A negative amount offsets another line, for example a refund inside a split. Response `coding.lines` use the same convention.
* Recoding is allowed until the transaction is approved. Unapprove first to change approved coding. Reconciled transactions cannot be recoded, and transactions in an open reconciliation return `409`.
Because `PUT` replaces the coding, retrying it is safe.
`DELETE /api/v1/transactions/{id}/coding` removes the draft journal entry and returns the transaction to `UNCATEGORIZED`. An approved transaction returns `409`; unapprove it first.
## Set dimensions
`PUT /api/v1/transactions/{id}/dimensions` replaces the transaction's dimensions. On a single-account transaction they are copied to the coded line. Split lines keep their own dimensions; set those in the coding request. Send `{"dimensions": []}` to clear them.
## Approve
`POST /api/v1/transactions/{id}/approve` posts the journal entry. It needs the `transactions:approve` scope. With OAuth, the signed-in user must also be allowed to post journal entries.
* Approval fails if `coding.missingRequiredDimensions` is not empty (`400`) or the accounting period is locked.
* Approving an approved transaction returns it unchanged, so retries are safe. `POST /unapprove` works the same way in reverse.
## Receipts
Upload a PDF or image (JPEG, PNG, GIF, WebP, or HEIC) of up to 5 MB as `multipart/form-data`:
```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl --fail-with-body "https://api.grainledger.com/api/v1/transactions/TXN_ID/attachments" \
-H "Authorization: Bearer $GRAIN_API_KEY" \
-F "file=@receipt.pdf;type=application/pdf"
```
* `GET /transactions/{id}/attachments` lists attachments, including receipts synced from card platforms.
* `GET /transactions/{id}/attachments/{fileId}/download` returns a signed URL that expires in 15 minutes. Request a new one each time you need the file; don't store it.
* `DELETE /transactions/{id}/attachments/{fileId}` removes an attachment.
## Changes in API version 1.3.0
Transaction responses now use a documented, stable shape. Internal fields that earlier responses passed through, such as model reasoning, audit logs, and bank-feed metadata, are no longer returned. The `fundId` and `vendorId` fields are replaced by `fund` and `vendor` summaries, and the new `coding` object carries the journal entry and its lines.