-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
4013 lines (3698 loc) · 145 KB
/
Copy pathclient.py
File metadata and controls
4013 lines (3698 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tango API Client"""
import os
import warnings
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Literal, cast
from urllib.parse import urljoin
import httpx
from tango.exceptions import (
TangoAPIError,
TangoAuthError,
TangoNotFoundError,
TangoRateLimitError,
TangoValidationError,
)
from tango.models import (
IDV,
OTA,
OTIDV,
Agency,
BudgetAccount,
BusinessType,
Contract,
Entity,
Forecast,
Grant,
GsaElibraryContract,
ITDashboardInvestment,
Location,
Notice,
Opportunity,
Organization,
PaginatedResponse,
Protest,
RateLimitInfo,
ResolveCandidate,
ResolveResult,
SearchFilters,
ShapeConfig,
Subaward,
ValidateResult,
Vehicle,
WebhookAlert,
WebhookEndpoint,
WebhookEventType,
WebhookEventTypesResponse,
WebhookSamplePayloadResponse,
WebhookTestDeliveryResult,
)
from tango.shapes import (
ModelFactory,
ShapeParser,
TypeGenerator,
build_parser_registry_from_client,
)
class TangoClient:
"""Tango API Client"""
def __init__(
self,
api_key: str | None = None,
base_url: str = "https://tango.makegov.com",
user_agent: str | None = None,
extra_headers: dict[str, str] | None = None,
):
"""
Initialize the Tango API client
Args:
api_key: API key for authentication. If not provided, will attempt to load from
TANGO_API_KEY environment variable.
base_url: Base URL for the API
user_agent: Custom User-Agent header value.
extra_headers: Additional headers to include in every request.
"""
# Load API key from environment if not provided
self.api_key = api_key or os.getenv("TANGO_API_KEY")
self.base_url = base_url.rstrip("/")
# Build headers
headers = {}
if self.api_key:
headers["X-API-KEY"] = self.api_key
if user_agent:
headers["User-Agent"] = user_agent
if extra_headers:
headers.update(extra_headers)
self.client = httpx.Client(headers=headers, timeout=30.0)
self._last_rate_limit_info: RateLimitInfo | None = None
self._last_response_headers: httpx.Headers | None = None
# Use hardcoded sensible defaults
cache_size = 100
# Initialize components
self._shape_parser = ShapeParser(cache_enabled=True)
self._type_generator = TypeGenerator(cache_enabled=True, cache_size=cache_size)
# Build parser registry from client methods
parser_registry = build_parser_registry_from_client(self)
# Initialize model factory
self._model_factory = ModelFactory(
type_generator=self._type_generator,
parsers=parser_registry,
)
# ============================================================================
# Core HTTP Request Utilities
# ============================================================================
@property
def rate_limit_info(self) -> RateLimitInfo | None:
"""Rate limit info from the most recent API response."""
return self._last_rate_limit_info
@property
def last_response_headers(self) -> httpx.Headers | None:
"""Full HTTP headers from the most recent API response."""
return self._last_response_headers
@staticmethod
def _parse_rate_limit_headers(headers: httpx.Headers) -> RateLimitInfo:
"""Extract rate limit info from response headers."""
def _int_or_none(val: str | None) -> int | None:
if val is None:
return None
try:
return int(val)
except (ValueError, TypeError):
return None
return RateLimitInfo(
limit=_int_or_none(headers.get("X-RateLimit-Limit")),
remaining=_int_or_none(headers.get("X-RateLimit-Remaining")),
reset=_int_or_none(headers.get("X-RateLimit-Reset")),
daily_limit=_int_or_none(headers.get("X-RateLimit-Daily-Limit")),
daily_remaining=_int_or_none(headers.get("X-RateLimit-Daily-Remaining")),
daily_reset=_int_or_none(headers.get("X-RateLimit-Daily-Reset")),
burst_limit=_int_or_none(headers.get("X-RateLimit-Burst-Limit")),
burst_remaining=_int_or_none(headers.get("X-RateLimit-Burst-Remaining")),
burst_reset=_int_or_none(headers.get("X-RateLimit-Burst-Reset")),
)
def _request(
self,
method: str,
endpoint: str,
params: dict[str, Any] | None = None,
json_data: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Make an API request"""
url = urljoin(f"{self.base_url}/", endpoint.lstrip("/"))
try:
response = self.client.request(method=method, url=url, params=params, json=json_data)
self._last_response_headers = response.headers
self._last_rate_limit_info = self._parse_rate_limit_headers(response.headers)
if response.status_code == 401:
raise TangoAuthError(
"Invalid API key or authentication required", response.status_code
)
elif response.status_code == 404:
raise TangoNotFoundError("Resource not found", response.status_code)
elif response.status_code == 400:
error_data = response.json() if response.content else {}
error_msg = "Invalid request parameters"
if error_data:
# Try to extract a more specific error message
if isinstance(error_data, dict):
detail = (
error_data.get("detail")
or error_data.get("message")
or error_data.get("error")
)
if detail:
error_msg = f"Invalid request parameters: {detail}"
raise TangoValidationError(
error_msg,
response.status_code,
error_data,
)
elif response.status_code == 429:
error_data = response.json() if response.content else {}
detail = error_data.get("detail", "Rate limit exceeded")
raise TangoRateLimitError(detail, response.status_code, error_data)
elif not response.is_success:
raise TangoAPIError(
f"API request failed with status {response.status_code}", response.status_code
)
return response.json() if response.content else {}
except httpx.HTTPError as e:
raise TangoAPIError(f"Request failed: {str(e)}") from e
def _get(self, endpoint: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
"""Make a GET request"""
return self._request("GET", endpoint, params=params)
def _post(
self,
endpoint: str,
json_data: dict[str, Any] | None = None,
*,
json: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Make a POST request.
Accepts either ``json_data`` (positional) or ``json=`` (keyword) for
backward compatibility with internal callers and docs examples.
Passing both raises ``TangoValidationError`` rather than silently
picking one — that ambiguity would hide caller bugs.
"""
if json_data is not None and json is not None:
raise TangoValidationError("_post: pass `json_data` or `json`, not both.")
body = json_data if json_data is not None else json
if body is None:
body = {}
return self._request("POST", endpoint, json_data=body)
def _patch(
self,
endpoint: str,
json_data: dict[str, Any] | None = None,
*,
json: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Make a PATCH request.
Accepts either ``json_data`` (positional) or ``json=`` (keyword) for
backward compatibility with internal callers and docs examples.
Passing both raises ``TangoValidationError`` rather than silently
picking one — that ambiguity would hide caller bugs.
"""
if json_data is not None and json is not None:
raise TangoValidationError("_patch: pass `json_data` or `json`, not both.")
body = json_data if json_data is not None else json
if body is None:
body = {}
return self._request("PATCH", endpoint, json_data=body)
def _delete(self, endpoint: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
"""Make a DELETE request"""
return self._request("DELETE", endpoint, params=params)
# ============================================================================
# Shape Parsing Utilities
# ============================================================================
def _parse_response_with_shape(
self,
data: dict[str, Any],
shape: str,
base_model: type,
flat: bool = False,
flat_lists: bool = False,
joiner: str = ".",
) -> Any:
"""
Parse API response using dynamic model generation
Args:
data: Raw API response data (dictionary)
shape: Shape string specifying fields to include
base_model: Base static model class (e.g., Contract, Agency)
flat: Whether the response is flattened with dot notation
flat_lists: Whether arrays are flattened with indexed keys
Returns:
Instance of dynamically generated type with parsed data
Raises:
ShapeError: If shape parsing or validation fails
TypeGenerationError: If type generation fails
ModelInstantiationError: If instance creation fails
"""
# Parse shape string
shape_spec = self._shape_parser.parse(shape)
shape_spec.is_flat = flat
shape_spec.is_flat_lists = flat_lists
# Validate shape against model
self._shape_parser.validate(shape_spec, base_model)
# Generate dynamic type
dynamic_type = self._type_generator.generate_type(
shape_spec=shape_spec,
base_model=base_model,
type_name=f"{base_model.__name__}Shaped",
)
# Unflatten if necessary
if flat:
data = self._unflatten_response(data, joiner=joiner)
# Create typed instance
return self._model_factory.create_instance(
data=data,
shape_spec=shape_spec,
base_model=base_model,
dynamic_type=dynamic_type,
)
def _unflatten_response(self, data: dict[str, Any], joiner: str = ".") -> dict[str, Any]:
"""
Unflatten a flat response into nested structure.
When flat=True is used with response shaping, the API returns dot-notation keys
like "recipient.display_name" instead of nested {"recipient": {"display_name": "..."}}.
This utility converts flat responses back to nested format for existing parsers.
Args:
data: Flattened response data
joiner: Character used to join nested keys (default: ".")
Returns:
Nested dictionary structure
"""
# Check if response is actually flat (has dot-notation keys)
has_flat_keys = any(joiner in str(key) for key in data.keys())
if not has_flat_keys:
return data # Already nested, return as-is
result: dict[str, Any] = {}
for flat_key, value in data.items():
# Split the key by joiner
parts = str(flat_key).split(joiner)
# Navigate/create nested structure
current = result
for part in parts[:-1]:
if part not in current:
current[part] = {}
elif not isinstance(current[part], dict):
# Key collision - flat key overwrites existing value
current[part] = {}
current = current[part]
# Set the final value
current[parts[-1]] = value
return result
# ============================================================================
# Data Parsing Utilities
# ============================================================================
def _parse_date(self, date_string: str | None) -> date | None:
"""Parse date string to date object"""
if not date_string:
return None
try:
# Handle various date formats
if "T" in date_string:
return datetime.fromisoformat(date_string.replace("Z", "+00:00")).date()
else:
return datetime.strptime(date_string, "%Y-%m-%d").date()
except (ValueError, TypeError):
return None
def _parse_datetime(self, datetime_string: str | None) -> datetime | None:
"""Parse datetime string to datetime object"""
if not datetime_string:
return None
try:
return datetime.fromisoformat(datetime_string.replace("Z", "+00:00"))
except (ValueError, TypeError):
return None
def _parse_decimal(self, value: Any) -> Decimal | None:
"""Parse numeric value to Decimal"""
if value is None:
return None
try:
return Decimal(str(value))
except (ValueError, TypeError, Exception):
# Catch InvalidOperation and other decimal exceptions
return None
def _parse_agency(self, data: dict[str, Any]) -> Agency | None:
"""Parse agency data (for endpoints without shape support)
Returns an Agency object.
Handles both standard agency fields and office fields (office_code/office_name).
"""
if not data:
return None
try:
department = None
if data.get("department"):
dept_data = data["department"]
if isinstance(dept_data, dict):
from .models import Department
department = Department(
name=dept_data.get("name", ""), code=str(dept_data.get("code", ""))
)
# Handle office fields (office_code/office_name) when standard fields aren't present
code = data.get("code") or data.get("office_code") or data.get("agency_code", "")
name = data.get("name") or data.get("office_name") or data.get("agency_name", "")
return Agency(
code=code,
name=name,
abbreviation=data.get("abbreviation"),
department=department,
)
except (KeyError, TypeError):
return None
def _parse_location(self, data: dict[str, Any] | None) -> Location | None:
"""Parse location data
Returns a Location object.
"""
if not data:
return None
try:
from .models import Location
# Map zip to zip_code if zip_code is not present
zip_code = data.get("zip_code") or data.get("zip")
return Location(
address_line1=data.get("address_line_1") or data.get("address_line1"),
address_line2=data.get("address_line_2") or data.get("address_line2"),
city=data.get("city"),
state=data.get("state"),
state_code=data.get("state_code"),
zip_code=zip_code,
zip=data.get("zip"),
zip4=data.get("zip4"),
country=data.get("country"),
country_code=data.get("country_code"),
county=data.get("county"),
congressional_district=data.get("congressional_district"),
latitude=data.get("latitude"),
longitude=data.get("longitude"),
)
except (KeyError, TypeError):
return None
# ============================================================================
# API Endpoints
# ============================================================================
# Agency endpoints
def list_agencies(
self, page: int = 1, limit: int = 25, search: str | None = None
) -> PaginatedResponse:
"""List all agencies"""
params: dict[str, Any] = {"page": page, "limit": min(limit, 100)}
if search:
params["search"] = search
data = self._get("/api/agencies/", params)
return PaginatedResponse(
count=data["count"],
next=data.get("next"),
previous=data.get("previous"),
results=[
ag
for ag in (self._parse_agency(agency) for agency in data["results"])
if ag is not None
],
)
def get_agency(self, code: str) -> Agency:
"""Get agency by code
Returns:
Agency object
"""
data = self._get(f"/api/agencies/{code}/")
agency = self._parse_agency(data)
if agency is None:
raise TangoNotFoundError(f"Agency '{code}' not found", 404)
return agency
def list_offices(
self,
page: int = 1,
limit: int = 25,
search: str | None = None,
) -> PaginatedResponse:
"""List offices (`/api/offices/`)."""
params: dict[str, Any] = {"page": page, "limit": min(limit, 100)}
if search is not None:
params["search"] = search
data = self._get("/api/offices/", params)
return PaginatedResponse(
count=data.get("count", 0),
next=data.get("next"),
previous=data.get("previous"),
results=data.get("results", []),
)
def get_office(self, code: str) -> dict[str, Any]:
"""Get a single office by code (`/api/offices/{code}/`)."""
return self._get(f"/api/offices/{code}/")
def list_organizations(
self,
page: int = 1,
limit: int = 25,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
cgac: str | None = None,
include_inactive: bool | None = None,
level: int | None = None,
parent: str | None = None,
search: str | None = None,
type: str | None = None,
) -> PaginatedResponse:
"""List organizations (`/api/organizations/`)."""
params: dict[str, Any] = {"page": page, "limit": min(limit, 100)}
if shape is None:
shape = ShapeConfig.ORGANIZATIONS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if flat_lists:
params["flat_lists"] = "true"
if cgac is not None:
params["cgac"] = cgac
if include_inactive is not None:
params["include_inactive"] = include_inactive
if level is not None:
params["level"] = level
if parent is not None:
params["parent"] = parent
if search is not None:
params["search"] = search
if type is not None:
params["type"] = type
data = self._get("/api/organizations/", params)
results = [
self._parse_response_with_shape(obj, shape, Organization, flat, flat_lists)
for obj in data.get("results", [])
]
return PaginatedResponse(
count=data.get("count", 0),
next=data.get("next"),
previous=data.get("previous"),
results=results,
)
def get_organization(
self,
fh_key: str,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
) -> Any:
"""Get a single organization by fh_key (`/api/organizations/{fh_key}/`)."""
params: dict[str, Any] = {}
if shape is None:
shape = ShapeConfig.ORGANIZATIONS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if flat_lists:
params["flat_lists"] = "true"
data = self._get(f"/api/organizations/{fh_key}/", params)
return self._parse_response_with_shape(data, shape, Organization, flat, flat_lists)
# Contract endpoints
def list_contracts(
self,
cursor: str | None = None,
limit: int = 25,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
filters: SearchFilters | dict[str, Any] | None = None,
award_date: str | None = None,
award_date_gte: str | None = None,
award_date_lte: str | None = None,
award_type: str | None = None,
awarding_agency: str | None = None,
expiring_gte: str | None = None,
expiring_lte: str | None = None,
fiscal_year: int | None = None,
fiscal_year_gte: int | None = None,
fiscal_year_lte: int | None = None,
funding_agency: str | None = None,
obligated_gte: str | None = None,
obligated_lte: str | None = None,
ordering: str | None = None,
piid: str | None = None,
pop_end_date_gte: str | None = None,
pop_end_date_lte: str | None = None,
pop_start_date_gte: str | None = None,
pop_start_date_lte: str | None = None,
solicitation_identifier: str | None = None,
keyword: str | None = None,
naics_code: str | None = None,
psc_code: str | None = None,
recipient_name: str | None = None,
recipient_uei: str | None = None,
set_aside_type: str | None = None,
sort: str | None = None,
order: str | None = None,
) -> PaginatedResponse:
"""
List contracts with optional filtering
Args:
cursor: Cursor token for pagination (from previous response.cursor).
If not provided, starts from the beginning.
limit: Results per page (max 100)
shape: Response shape string (defaults to minimal shape).
Use None to disable shaping, ShapeConfig.CONTRACTS_MINIMAL for minimal,
or provide custom shape string
flat: If True, flatten nested objects in shaped response using dot notation
flat_lists: If True, flatten arrays using indexed keys (e.g., items.0.field)
filters: Optional SearchFilters object or dict for backward compatibility.
award_date: Award date (exact match, YYYY-MM-DD)
award_date_gte: Award date >= (YYYY-MM-DD)
award_date_lte: Award date <= (YYYY-MM-DD)
award_type: Award type code
awarding_agency: Awarding agency code (e.g., "4700" for GSA)
expiring_gte: Expiring on or after date
expiring_lte: Expiring on or before date
fiscal_year: Fiscal year (exact match)
fiscal_year_gte: Fiscal year >=
fiscal_year_lte: Fiscal year <=
funding_agency: Funding agency code
obligated_gte: Obligated amount >=
obligated_lte: Obligated amount <=
ordering: Sort ordering (prefix with '-' for descending)
piid: Procurement Instrument Identifier
pop_end_date_gte: Period of performance end date >=
pop_end_date_lte: Period of performance end date <=
pop_start_date_gte: Period of performance start date >=
pop_start_date_lte: Period of performance start date <=
solicitation_identifier: Solicitation ID
keyword: Search contract descriptions (mapped to 'search' API param)
naics_code: NAICS code (mapped to 'naics' API param)
psc_code: PSC code (mapped to 'psc' API param)
recipient_name: Vendor/recipient name (mapped to 'recipient' API param)
recipient_uei: Vendor UEI (mapped to 'uei' API param)
set_aside_type: Set-aside type (mapped to 'set_aside' API param)
sort: Field to sort by (combined with 'order' to produce 'ordering')
order: Sort order ('asc' or 'desc', default 'asc')
Examples:
>>> contracts = client.list_contracts(limit=10)
>>> contracts = client.list_contracts(
... awarding_agency="4700",
... award_date_gte="2023-01-01",
... limit=25,
... )
>>> contracts = client.list_contracts(keyword="software development")
"""
params: dict[str, Any] = {"limit": min(limit, 100)}
if cursor:
params["cursor"] = cursor
# /api/contracts/ is cursor-only (KeysetPagination). When no cursor is
# supplied, send neither page nor cursor — the API returns the first
# page by default. (Previously sent page=1, which the endpoint ignores.)
# Handle legacy filters parameter (backward compatibility)
filter_dict: dict[str, Any] = {}
if filters is not None:
if hasattr(filters, "to_dict"):
filter_dict = filters.to_dict()
else:
filter_dict = dict(filters)
if limit == 25 and "limit" in filter_dict:
params["limit"] = min(filter_dict.pop("limit", 25), 100)
if shape is None:
shape = ShapeConfig.CONTRACTS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if flat_lists:
params["flat_lists"] = "true"
api_param_mapping = {
"naics_code": "naics",
"keyword": "search",
"psc_code": "psc",
"recipient_name": "recipient",
"recipient_uei": "uei",
"set_aside_type": "set_aside",
}
# Collect explicit filter params; legacy filter_dict values are used as fallback
filter_params: dict[str, Any] = {}
for key, val in (
("award_date", award_date),
("award_date_gte", award_date_gte),
("award_date_lte", award_date_lte),
("award_type", award_type),
("awarding_agency", awarding_agency),
("expiring_gte", expiring_gte),
("expiring_lte", expiring_lte),
("fiscal_year", fiscal_year),
("fiscal_year_gte", fiscal_year_gte),
("fiscal_year_lte", fiscal_year_lte),
("funding_agency", funding_agency),
("obligated_gte", obligated_gte),
("obligated_lte", obligated_lte),
("ordering", ordering),
("piid", piid),
("pop_end_date_gte", pop_end_date_gte),
("pop_end_date_lte", pop_end_date_lte),
("pop_start_date_gte", pop_start_date_gte),
("pop_start_date_lte", pop_start_date_lte),
("solicitation_identifier", solicitation_identifier),
("keyword", keyword),
("naics_code", naics_code),
("psc_code", psc_code),
("recipient_name", recipient_name),
("recipient_uei", recipient_uei),
("set_aside_type", set_aside_type),
):
if val is not None:
filter_params[key] = val
# Merge: explicit params take precedence over legacy filter_dict
excluded = {"shape", "flat", "flat_lists", "cursor", "page", "limit"}
for k, v in filter_dict.items():
if k not in excluded and k not in filter_params and v is not None:
filter_params[k] = v
# Handle sort + order → ordering conversion
sort_field = sort or filter_dict.get("sort")
sort_order = order or filter_dict.get("order")
if sort_field and "ordering" not in filter_params:
prefix = "-" if sort_order == "desc" else ""
filter_params["ordering"] = f"{prefix}{sort_field}"
# Apply parameter name mapping and add to params
for key, value in filter_params.items():
api_key = api_param_mapping.get(key, key)
params[api_key] = value
data = self._get("/api/contracts/", params)
# Always use dynamic parsing
results = [
self._parse_response_with_shape(contract, shape, Contract, flat, flat_lists)
for contract in data["results"]
]
return PaginatedResponse(
count=data["count"],
next=data.get("next"),
previous=data.get("previous"),
results=results,
cursor=data.get("cursor"),
)
def get_contract(
self,
key: str,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
joiner: str = ".",
) -> Any:
"""Get a single contract by key (`/api/contracts/{key}/`)."""
params: dict[str, Any] = {}
if shape is None:
shape = ShapeConfig.CONTRACTS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if joiner:
params["joiner"] = joiner
if flat_lists:
params["flat_lists"] = "true"
data = self._get(f"/api/contracts/{key}/", params)
return self._parse_response_with_shape(
data, shape, Contract, flat, flat_lists, joiner=joiner
)
def get_contract_subawards(
self,
key: str,
page: int = 1,
limit: int = 25,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
ordering: str | None = None,
) -> PaginatedResponse:
"""List subawards under a contract (`/api/contracts/{key}/subawards/`)."""
params: dict[str, Any] = {"page": page, "limit": min(limit, 100)}
if shape is None:
shape = ShapeConfig.SUBAWARDS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if flat_lists:
params["flat_lists"] = "true"
if ordering:
params["ordering"] = ordering
data = self._get(f"/api/contracts/{key}/subawards/", params)
raw_results = data.get("results") or []
results = [
self._parse_response_with_shape(obj, shape, Subaward, flat, flat_lists)
for obj in raw_results
]
return PaginatedResponse(
count=int(data.get("count") or len(results)),
next=data.get("next"),
previous=data.get("previous"),
results=results,
cursor=data.get("cursor"),
)
def get_contract_transactions(
self,
key: str,
limit: int = 100,
cursor: str | None = None,
ordering: str | None = None,
) -> PaginatedResponse:
"""List transactions under a contract (`/api/contracts/{key}/transactions/`)."""
params: dict[str, Any] = {"limit": min(limit, 500)}
if cursor:
params["cursor"] = cursor
if ordering:
params["ordering"] = ordering
data = self._get(f"/api/contracts/{key}/transactions/", params)
return PaginatedResponse(
count=int(data.get("count") or len(data.get("results") or [])),
next=data.get("next"),
previous=data.get("previous"),
results=data.get("results") or [],
cursor=data.get("cursor"),
)
# ============================================================================
# IDVs (Awards)
# ============================================================================
def list_idvs(
self,
limit: int = 25,
cursor: str | None = None,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
joiner: str = ".",
award_date: str | None = None,
award_date_gte: str | None = None,
award_date_lte: str | None = None,
awarding_agency: str | None = None,
expiring_gte: str | None = None,
expiring_lte: str | None = None,
fiscal_year: int | None = None,
fiscal_year_gte: int | None = None,
fiscal_year_lte: int | None = None,
funding_agency: str | None = None,
idv_type: str | None = None,
last_date_to_order_gte: str | None = None,
last_date_to_order_lte: str | None = None,
naics: str | None = None,
ordering: str | None = None,
piid: str | None = None,
pop_start_date_gte: str | None = None,
pop_start_date_lte: str | None = None,
psc: str | None = None,
recipient: str | None = None,
search: str | None = None,
set_aside: str | None = None,
solicitation_identifier: str | None = None,
uei: str | None = None,
) -> PaginatedResponse:
"""
List IDVs (indefinite delivery vehicles) with keyset pagination.
This mirrors `/api/idvs/` and supports the same filter parameters as the API,
plus shaping via `shape`.
"""
params: dict[str, Any] = {"limit": min(limit, 100)}
if cursor:
params["cursor"] = cursor
if shape is None:
shape = ShapeConfig.IDVS_MINIMAL
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if joiner:
params["joiner"] = joiner
if flat_lists:
params["flat_lists"] = "true"
for key, val in (
("award_date", award_date),
("award_date_gte", award_date_gte),
("award_date_lte", award_date_lte),
("awarding_agency", awarding_agency),
("expiring_gte", expiring_gte),
("expiring_lte", expiring_lte),
("fiscal_year", fiscal_year),
("fiscal_year_gte", fiscal_year_gte),
("fiscal_year_lte", fiscal_year_lte),
("funding_agency", funding_agency),
("idv_type", idv_type),
("last_date_to_order_gte", last_date_to_order_gte),
("last_date_to_order_lte", last_date_to_order_lte),
("naics", naics),
("ordering", ordering),
("piid", piid),
("pop_start_date_gte", pop_start_date_gte),
("pop_start_date_lte", pop_start_date_lte),
("psc", psc),
("recipient", recipient),
("search", search),
("set_aside", set_aside),
("solicitation_identifier", solicitation_identifier),
("uei", uei),
):
if val is not None:
params[key] = val
data = self._get("/api/idvs/", params)
raw_results = data.get("results") or []
results = [
self._parse_response_with_shape(obj, shape, IDV, flat, flat_lists, joiner=joiner)
for obj in raw_results
]
return PaginatedResponse(
count=int(data.get("count") or len(results)),
next=data.get("next"),
previous=data.get("previous"),
results=results,
page_metadata=data.get("page_metadata"),
)
def get_idv(
self,
key: str,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
joiner: str = ".",
) -> Any:
"""Get a single IDV by award key (`/api/idvs/{key}/`)."""
params: dict[str, Any] = {}
if shape is None:
shape = ShapeConfig.IDVS_COMPREHENSIVE
if shape:
params["shape"] = shape
if flat:
params["flat"] = "true"
if joiner:
params["joiner"] = joiner
if flat_lists:
params["flat_lists"] = "true"
data = self._get(f"/api/idvs/{key}/", params)
return self._parse_response_with_shape(data, shape, IDV, flat, flat_lists, joiner=joiner)
def list_idv_awards(
self,
key: str,
limit: int = 25,
cursor: str | None = None,
shape: str | None = None,
flat: bool = False,
flat_lists: bool = False,
joiner: str = ".",
filters: SearchFilters | dict[str, Any] | None = None,
**kwargs: Any,
) -> PaginatedResponse:
"""
List child awards (contracts) under an IDV (`/api/idvs/{key}/awards/`).
This endpoint behaves like `/api/contracts/`, but scoped to a specific IDV.
"""
# Reuse list_contracts mapping and behavior by calling the endpoint directly.