# USAspending — Federal Contracts & Grants Search (`dromb/usaspending-us-federal-awards`) Actor

USAspending official federal contract/grant search, award detail, award counts and source filters — NONPROD R11.

- **URL**: https://apify.com/dromb/usaspending-us-federal-awards.md
- **Developed by:** [Dmitriy Gyrbu](https://apify.com/dromb) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.60 / 1,000 results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## USAspending — Federal Contracts & Grants Search (NONPROD R11)

> **R10 NONPROD.** Official USAspending endpoints have been tested live on 22 November 2026, but this specific Actor has **not yet been built or accepted in Apify**. This source-only validation does not imply cloud operation, approved billing, or Store publication.

Find **US federal contracts and grants already awarded**, using USAspending.gov as the source. Search by date, recipient name, keyword, top-level awarding agency, and (for contracts) NAICS. Obtain a specific award's official details using the `award_internal_id` returned by search. Results are flat, CSV-friendly, and carry official IDs, amount in USD, agency and source URL.

An additional `award_counts` operation uses the official count endpoint to return one aggregate row (six category counters), optionally narrowed by source category; it does **not** fetch award records from categories outside contracts/grants.

This Actor does **not** find open requests for proposals on SAM.gov, verify awardee eligibility, or provide real-time transaction feeds. It covers contract codes A–D and grant codes 02–05 plus F001/F002 only. IDVs, loans, direct payments, other federal assistance, subawards, bulk downloads, recipient dossiers and historical delta monitoring are **not** implemented.

### Quick start (small default)

```json
{"operation":"search_awards","awardType":"contracts","maxItems":8}
```

Defaults to a rolling 365-day source-search period ending on the current UTC date, sorted by `Award Amount` descending. The source search period is **not** a filter on the original award start date: a contract begun in 1993 appeared in a live search covering 2024–2026. The source reports supported time-period searches beginning 2007-10-01; earlier dates are rejected by R10 and require official bulk download. A successful request may return fewer than 8 results. The example is syntactically valid but is **not** an accepted live cloud example until its actual Dataset is independently inspected.

#### Search grants (not direct payments)

```json
{"operation":"search_awards","awardType":"grants","maxItems":8}
```

#### Find contracts in one NAICS group

```json
{"operation":"search_awards","awardType":"contracts","naics":"541330","startDate":"2025-01-01","endDate":"2025-12-31","maxItems":20,"pageSize":20}
```

#### Search a recipient (source-controlled name matching)

```json
{"operation":"search_awards","recipient":"LOCKHEED MARTIN","maxItems":8}
```

This query returned records in a live source-only test on 22 November 2026. It is **not** exact UEI screening, and the search results may change.

#### Retrieve one award

After a real search result supplies `award_internal_id`, pass that **integer** as `awardId`:

```json
{"operation":"award_detail","awardId":307885715}
```

`307885715` was returned by a real source search and its detail endpoint returned HTTP 200 with matching ID, generated ID, category and amount on 22 November 2026. This does not claim the Apify Actor has run. Source records may change.

#### Count matching awards (new in R8)

```json
{"operation":"award_counts","countScope":"all_award_categories","startDate":"2024-01-01","endDate":"2026-11-22"}
```

One Dataset row gives `total_awards_count` and six count fields for `contracts`, `grants`, `idvs`, `loans`, `direct_payments`, `other`. This is a source-reported aggregate, **not** an award export; `OUTPUT.complete=true` refers only to the aggregate response. Search `awardType` is separate from count `countScope`. Optional `keyword`, `recipient`, `agency`, and contracts-only `naics` filters are supported. Pagination, `pageSize`, `maxItems`, and `sortBy` are irrelevant to this operation.

Live source-only verification returned HTTP 200 for four count scopes; counts and source SHA are captured in `G1_REAL_SOURCE_EVIDENCE_R8.json`. The actual R10 cloud Actor remains unbuilt and untested.

### Operations and limits

| Operation | Parameters | Result |
|---|---|---|
| `search_awards` | `awardType`, `keyword`, `recipient`, `agency`, `naics`, date range, sort, `maxItems`, `pageSize`, `startPage` | Up to `maxItems` unique rows from the selected source interval |
| `award_detail` | numeric `awardId` from search, optional `includeRaw` | Exactly one award detail; mismatched internal ID is an error |
| `award_counts` | `countScope`, dates and optional matching filters | One count row across six official award groups, or a selected subset |

`awardType=contracts_and_grants` performs two separate source queries (contracts, grants), then merges a bounded global top-N by award amount or last-modified date. It does not expose a native combined page and does not support `startPage > 1`, recipient-name sorting or award-ID sorting. It may use up to twice as many source requests. The component searches and split-source ranking were checked against live HTTP responses, while the exact combined Actor still awaits cloud acceptance. This option means exactly those two classes. For backward compatibility, the R1 JSON alias `all` is normalized to `contracts_and_grants`; it does **not** mean all USAspending award types.

Only source-confirmed values are returned. Each row from the split mixed search is explicitly associated with the matching single-category query; cross-category identity collisions fail rather than silently merging records. `award_type` is the source type description, not an inferred legal classification.

`maxItems` is a **cap**, not a full-source count or upstream page size. All run pages use the same source `limit`; duplicate rows are skipped by internal ID. Runs are bounded to 40 pages and the API's first 10,000 indexed results. Changing upstream data may affect later pages. No snapshot or incremental cursor guarantee is offered.

### What is in the Dataset?

Primary fields are `award_internal_id`, `award_id` (source-facing ID, e.g. PIID/FAIN), `generated_award_id`, `award_category`, `award_type`, `recipient_name`, `recipient_uei`, `award_amount`, `currency=USD`, `awarding_agency`, `awarding_sub_agency`, `funding_agency`, `naics`, `naics_description`, `psc`, `psc_description`, dates, `description`, `award_page_url`, `source_api_url`, `retrieved_at`. Also provides validated agency codes when present.

`award_amount` is a source obligation/award metric and **not cash actually paid**. `start_date` and `end_date` are supplied by USAspending; search and detail endpoints can use different underlying reporting fields. Compare values only after source identity and semantic parity checks, not simply because column labels match.

The Dataset supports five views: **Awards overview**, **Integration IDs**, **Agencies & funding**, **Place of performance**, and **Award counts by type**. Location codes originate from the source; city is only populated when available from award detail. `raw_payload` is opt-in (`includeRaw=true`), for debugging/source reconciliation; avoid relying on raw fields as stable public schema.

A successful run also sets default KVS record `OUTPUT`:

- `success`, `operation`, `item_count`, `api_requests`, `retrieved_at`.
- `complete` — for search, true only when the source claims exhaustion from page 1 without a local merge cap or per-page cap. For detail, it means one verified item. For `award_counts`, it means the **single aggregate row was returned**, not that the matching awards were downloaded. This is not independent evidence of database completeness.
- `source_exhausted`, `has_next` (upstream continuation only), `more_results_not_returned` (includes local truncation), `omitted_by_merge_cap`, `omitted_by_page_cap`, `coverage_basis`, `stop_reason` (`source_exhausted`, `selected_page_exhausted`, `max_items`, `max_pages`, `indexed_window`, or `award_detail`).
- `pages_fetched`, `requested_start_page`, `last_page_fetched`, `api_page_size`, `raw_rows_seen`, `duplicate_rows_skipped`.
- `source_messages` — bounded verbatim warnings/diagnostics returned by the upstream search API. The request explicitly specifies prime awards. A contradictory response `spending_level` is an error; the echo may be absent in the currently published server serializer and is counted separately in OUTPUT.

Legitimate no-match returns success with `item_count=0` and a note; HTTP/schema failures produce `success=false` and a failed Actor run. The source may be temporarily unavailable, in which case data should not be interpreted as an authoritative absence of awards.

### Reliability, pricing and provenance

Source only: [USAspending API v2 endpoint index](https://api.usaspending.gov/docs/endpoints) — no API key currently required. Source contracts: [search](https://github.com/fedspendingtransparency/usaspending-api/blob/master/usaspending_api/api_contracts/contracts/v2/search/spending_by_award.md) and [award details](https://github.com/fedspendingtransparency/usaspending-api/blob/master/usaspending_api/api_contracts/contracts/v2/awards/award_id.md). The source data's publication lag is controlled by USAspending; `retrieved_at` means retrieval time, not award issuance or live freshness.

One HTTP request at a time; 22-second per-request timeout, 240-second bounded source-run budget (an in-flight call may finish later); response cap 6 MB; at most three attempts for transient network/HTTP 408, 429 and 5xx; nonretryable source-contract errors do not spin. Does not use proxies or a browser. Pricing and PAY_PER_EVENT billing **are not configured or verified** in this NONPROD package. No provider-side budget guarantee is claimed.

### Development and release boundary

```bash
PYTHONPATH=src python -m unittest discover -s tests -v
```

The regression suite includes synthetic source-contract fixtures, five full/projection captured source response replays from 22 November 2026 (contract and grant search, count, two details), and negative tests. Live HTTP probing was conducted separately; `unittest` execution alone does not repeat live source requests.

This package is not a published Actor. Cloud build, run billing and public Store pricing remain unverified; they are not quoted as established customer costs.

#### Evidence status (22 November 2026)

The official endpoint has returned HTTP 200 for contracts, grants, native page 2, six filter/sort cases, five paired award-detail lookups, and four count scopes. A nonexistent award ID returned the expected HTTP 404. Split-source top-N was checked against two live source pages. Exact HTTP body hashes, case IDs, limitations and reproducibility scripts are in `G1_REAL_SOURCE_EVIDENCE_R8.json`.

**Not yet accepted:** the exact Actor running in Apify, independently verified cloud Dataset/`OUTPUT`, actual PAY_PER_EVENT billing, QA42, actor-specific R72 private CREATE, `latest` and public Store publication.

The source's report-date filter is **not** the date on which a contract originally began. The search API reports an earliest supported period of 2007-10-01; historical bulk data requires the official download endpoints. For definitions of the upstream data, see [USAspending documentation](https://api.usaspending.gov/docs/endpoints).

#### Mixed-search ranking reliability (R9)

`global_top_n_verified=true` means both source category scans either reached their natural end or supplied at least the requested number of distinct, source-sorted awards. It **does not** mean full source coverage. `complete=true` remains stricter: both categories exhausted and no candidates omitted by the local merge cap. When `global_top_n_verified=false`, rows represent a partial candidate ranking; do not present them as proven global leaders.

The official synchronous HTTP client runs in a worker thread, keeping the Apify SDK event loop free for storage and lifecycle operations. HTTP and whole-run timeouts remain bounded. Real cloud resource/lifecycle QA is still required before release.

#### Strict page-cap truthfulness (R10)

A final upstream page can contain more distinct awards than the remaining `maxItems` slots even when `hasNext=false`. R10 records such unused awards in `omitted_by_page_cap`, marks `more_results_not_returned=true` and `complete=false`, and propagates the omission through mixed group merges. `source_exhausted=true` may coexist with `complete=false`: exhausting the upstream pagination does not mean every record was emitted. `omitted_by_merge_cap` counts *different* candidates dropped only by the cross-category merge. Duplicate source IDs are counted separately. A locally capped, source-sorted top-N can still be ranking-valid without being a complete export.

Five captured source projections are under `tests/fixtures/`: three original source JSON search/count responses (raw SHA256 pinned in evidence) and two detail responses projected to the fields used by the Actor (their projection SHA256 and original full GET SHA256 are recorded). Replay tests run without network, preserving a real source example while not misrepresenting a cloud run.

#### R11 correction: mixed Last Modified Date ordering

Mixed contract/grant top-N sorts date-only timestamps as midnight UTC and accepts
validated ISO datetimes with a time component and optional UTC offset. Missing
values remain last for both directions. Invalid source timestamps fail closed.
This changes internal ranking only; no input/output field names changed.

# Actor input Schema

## `operation` (type: `string`):

Search matching federal awards; retrieve a single award profile by numeric ID; or count awards by type without exporting individual awards.

## `awardType` (type: `string`):

Restricted source award-code groups. Mixed results use two separate source searches and merge a top-N ranking; not a native merged page. This can use up to twice the requests. Grants include source codes 02–05 and F001/F002. No IDVs, loans or other assistance. Legacy alias all maps to this subset.

## `keyword` (type: `string`):

Search terms present in award data. Leave blank for date-based discovery.

## `recipient` (type: `string`):

Filter by recipient_search_text; partial name matching is source-controlled.

## `agency` (type: `string`):

Official top-level awarding agency name, e.g. Department of Defense.

## `naics` (type: `string`):

2–6 digit NAICS prefix/code. Contracts only.

## `startDate` (type: `string`):

UTC source-search period start YYYY-MM-DD (min 2007-10-01). This filters spending/award activity, not necessarily the contract start date; historical data requires official bulk download.

## `endDate` (type: `string`):

UTC source-search period end YYYY-MM-DD; defaults to current UTC day. Search period is not a filter on the original contract start date.

## `sortBy` (type: `string`):

Source sort field. Mixed contracts+grants supports only Award Amount and Last Modified Date. Source results may change during paging.

## `sortOrder` (type: `string`):

Choose descending or ascending order. Mixed contracts and grants use the same order.

## `maxItems` (type: `integer`):

Maximum distinct awards to return, NOT the total source count. Capped searches explicitly report incomplete coverage.

## `pageSize` (type: `integer`):

Upstream page size (1–100); may be reduced once to maxItems to avoid overfetch. Fixed across all pages of a run.

## `startPage` (type: `integer`):

Source page (1-based) for a single award group; mixed contracts+grants only supports startPage=1 as a merged top-N.

## `awardId` (type: `integer`):

Numeric internal ID returned as award_internal_id by search. Do not supply the contract PIID, award string, UEI or a generated hash.

## `includeRaw` (type: `boolean`):

Append raw_payload to each row for advanced integration and debugging.

## `countScope` (type: `string`):

For award_counts only; all categories provides six official totals. Search_awards still supports only contracts and grants.

## Actor input object example

```json
{
  "operation": "search_awards",
  "awardType": "contracts",
  "sortBy": "Award Amount",
  "sortOrder": "desc",
  "maxItems": 8,
  "pageSize": 50,
  "startPage": 1,
  "includeRaw": false,
  "countScope": "all_award_categories"
}
```

# Actor output Schema

## `results` (type: `string`):

Search/detail: one normalized award per row; award_counts: one source-reported aggregate row. Check OUTPUT and record_type.

## `run_summary` (type: `string`):

Completion flag, pagination coverage, request count and source provenance.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "operation": "search_awards",
    "awardType": "contracts",
    "sortBy": "Award Amount",
    "sortOrder": "desc",
    "maxItems": 8,
    "pageSize": 50,
    "startPage": 1,
    "includeRaw": false,
    "countScope": "all_award_categories"
};

// Run the Actor and wait for it to finish
const run = await client.actor("dromb/usaspending-us-federal-awards").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "operation": "search_awards",
    "awardType": "contracts",
    "sortBy": "Award Amount",
    "sortOrder": "desc",
    "maxItems": 8,
    "pageSize": 50,
    "startPage": 1,
    "includeRaw": False,
    "countScope": "all_award_categories",
}

# Run the Actor and wait for it to finish
run = client.actor("dromb/usaspending-us-federal-awards").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "operation": "search_awards",
  "awardType": "contracts",
  "sortBy": "Award Amount",
  "sortOrder": "desc",
  "maxItems": 8,
  "pageSize": 50,
  "startPage": 1,
  "includeRaw": false,
  "countScope": "all_award_categories"
}' |
apify call dromb/usaspending-us-federal-awards --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,dromb/usaspending-us-federal-awards"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/19wnrmfatfkQXNuQX/builds/bEpHeGaG6Jh8pCVQF/openapi.json
