1"""Federal Register Search — Apify Actor.
2
3Searches the official US Federal Register API (federalregister.gov) for
4documents: rules, proposed rules, notices, and presidential documents
5(executive orders, proclamations). Returns clean, structured JSON.
6
7The Federal Register API is well-documented and uses a `conditions[...]`
8query-parameter style. We use only documented parameters and the documented
9`fields[]` selector so the response is predictable.
10
11API docs: https://www.federalregister.gov/developers/documentation/api/v1
12"""
13
14from __future__ import annotations
15
16import asyncio
17from urllib.parse import urlencode
18
19import httpx
20try:
21 from . import _tier_prices
22except ImportError:
23 import _tier_prices
24from apify import Actor
25
26API = "https://www.federalregister.gov/api/v1/documents.json"
27
28
29DOC_TYPES = {"RULE", "PRORULE", "NOTICE", "PRESDOCU"}
30DOC_TYPE_LABELS = {
31 "RULE": "Final Rule",
32 "PRORULE": "Proposed Rule",
33 "NOTICE": "Notice",
34 "PRESDOCU": "Presidential Document",
35}
36
37
38def transform(doc: dict) -> dict:
39 """Normalize a Federal Register document into a clean record."""
40 agencies = doc.get("agencies") or []
41 agency_names = [a.get("name") for a in agencies if isinstance(a, dict) and a.get("name")]
42
43 doc_type = doc.get("type")
44 return {
45 "documentNumber": doc.get("document_number"),
46 "title": doc.get("title"),
47 "type": doc_type,
48 "typeLabel": DOC_TYPE_LABELS.get(doc_type, doc_type),
49 "abstract": doc.get("abstract"),
50 "action": doc.get("action"),
51 "agencies": agency_names,
52 "publicationDate": doc.get("publication_date"),
53 "effectiveDate": doc.get("effective_on"),
54 "commentsCloseDate": doc.get("comments_close_on"),
55 "citation": doc.get("citation"),
56
57 "president": doc.get("president"),
58 "presidentialDocumentType": doc.get("presidential_document_type"),
59 "executiveOrderNumber": doc.get("executive_order_number"),
60 "signingDate": doc.get("signing_date"),
61 "url": doc.get("html_url"),
62 "pdfUrl": doc.get("pdf_url"),
63 }
64
65
66def build_url(actor_input: dict) -> str:
67 """Build a Federal Register API query using only core documented parameters.
68
69 Deliberately minimal: we do NOT use a custom `fields[]` selector (the API
70 returns a rich default field set that already includes everything we read in
71 transform()). Sending unknown/over-specified params is the main cause of a
72 400 from this API, so we keep the request conservative.
73 """
74 params: list[tuple[str, str]] = []
75
76 term = (actor_input.get("searchTerm") or "").strip()
77 if term:
78 params.append(("conditions[term]", term))
79
80
81 for t in (actor_input.get("documentTypes") or []):
82 t = str(t).strip().upper()
83 if t in DOC_TYPES:
84 params.append(("conditions[type][]", t))
85
86
87 agency = (actor_input.get("agency") or "").strip()
88 if agency:
89 params.append(("conditions[agencies][]", agency))
90
91
92 start = (actor_input.get("publishedAfter") or "").strip()
93 if start:
94 params.append(("conditions[publication_date][gte]", start))
95 end = (actor_input.get("publishedBefore") or "").strip()
96 if end:
97 params.append(("conditions[publication_date][lte]", end))
98
99
100 order = actor_input.get("order", "newest")
101 if order not in ("newest", "oldest", "relevance"):
102 order = "newest"
103 params.append(("order", order))
104
105
106 params.append(("per_page", "100"))
107
108 return f"{API}?{urlencode(params)}"
109
110
111async def main() -> None:
112 async with Actor:
113 actor_input = await Actor.get_input() or {}
114 max_items = int(actor_input.get("maxItems", 100))
115
116 base_url = build_url(actor_input)
117 Actor.log.info(f"Federal Register search: {base_url}")
118
119 pushed = 0
120 page = 1
121 total = None
122
123 async with httpx.AsyncClient(
124 timeout=40.0,
125 headers={"User-Agent": "scrapeworks-federal-register/0.1", "Accept": "application/json"},
126 ) as client:
127 while pushed < max_items and page <= 100:
128
129 sep = "&" if "?" in base_url else "?"
130 url = f"{base_url}{sep}page={page}"
131
132 data = None
133 for attempt in range(1, 4):
134 try:
135 resp = await client.get(url)
136 resp.raise_for_status()
137 data = resp.json()
138 break
139 except (httpx.HTTPError, ValueError) as exc:
140 Actor.log.warning(f"Attempt {attempt} failed: {exc}")
141 if attempt < 3:
142 await asyncio.sleep(attempt * 2)
143
144 if data is None:
145 Actor.log.error("Failed to fetch Federal Register data.")
146 break
147
148 if total is None:
149 total = data.get("count")
150 Actor.log.info(f"Federal Register reports {total} matching documents.")
151
152 results = data.get("results") or []
153 if not results:
154 break
155
156 batch = [transform(d) for d in results[: max_items - pushed]]
157 if batch:
158 await Actor.push_data(batch)
159 pushed += len(batch)
160 Actor.log.info(f"Pushed {pushed}/{max_items} documents.")
161
162
163 if total is not None and pushed >= min(total, max_items):
164 break
165 if len(results) < 100:
166 break
167 page += 1
168 await asyncio.sleep(1)
169
170 Actor.log.info(f"Done. Returned {pushed} documents.")