Skip to content

PixelClientAsync

pixel_client

PixelClientAsync

Asynchronous client for interacting with the Pixel API.

This client provides methods for working with projects, data collections, images, rasters, and other resources in the Pixel system. It handles authentication, request management, and provides high-level operations for common tasks.

Source code in src/pixel_client/_base.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
class PixelClientAsync:
    """Asynchronous client for interacting with the Pixel API.

    This client provides methods for working with projects, data collections, images,
    rasters, and other resources in the Pixel system. It handles authentication,
    request management, and provides high-level operations for common tasks.
    """

    def __init__(
        self,
        url: str,
        keycloak_server_url: str,
        realm: str,
        client_id: str,
        username: str,
        password: str,
        timeout_pixel: httpx.Timeout = DEFAULT_PIXEL_TIMEOUT,
        timeout_upload: httpx.Timeout = DEFAULT_UPLOAD_TIMEOUT,
        upload_num_retries: int = DEFAULT_UPLOAD_RETRIES,
        upload_max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
    ):
        """Initialize a new Pixel API client.

        Args:
            url: Base URL of the Pixel API.
            keycloak_server_url: URL of the Keycloak authentication server.
            realm: Keycloak realm name.
            client_id: Keycloak client ID.
            username: Username for authentication.
            password: Password for authentication.
            timeout_pixel: Optional timeout configuration for Pixel API requests.
            timeout_upload: Optional timeout configuration for file uploads. If not provided, defaults to the same as `timeout_pixel`.
        """
        self.url: str = url
        self._timeout_pixel = timeout_pixel
        self._timeout_upload = timeout_upload
        self.auth = KeyCloakAuth(
            keycloak_server_url, realm, client_id, username, password
        )
        self.pixel_client = httpx.AsyncClient(
            base_url=self.url, auth=self.auth, timeout=self._timeout_pixel
        )
        self._internal_client = httpx.AsyncClient(
            timeout=self._timeout_upload,  # Use a separate client for uploads
        )  # For s3 uploads
        self._semaphore: asyncio.Semaphore = asyncio.Semaphore(upload_max_concurrency)

        self._retry_policy = tenacity.AsyncRetrying(
            stop=tenacity.stop_after_attempt(upload_num_retries),
            wait=tenacity.wait_random_exponential(),
            before=tenacity.before_log(logger, logging.DEBUG),
            after=tenacity.after_log(logger, logging.DEBUG),
        )
        self._internal_client.request = self._retry_policy.wraps(
            self._internal_client.request
        )

    @classmethod
    def from_settings(
        cls, settings: PixelApiSettings, **kwargs: Unpack[PixelClientKwargs]
    ) -> Self:
        """Instantiate the client from settings.

        Args:
            settings: PixelApiSettings object containing API configuration.
            **kwargs: Additional keyword arguments to pass to the client constructor.

        Returns:
            PixelClientAsync: A new client instance configured with the provided settings.
        """
        return cls(
            url=settings.PIXEL_API_URL,
            keycloak_server_url=settings.PIXEL_SERVER_URL,
            client_id=settings.PIXEL_CLIENT_ID,
            username=settings.PIXEL_USERNAME,
            password=settings.PIXEL_PASSWORD.get_secret_value(),
            realm=settings.PIXEL_REALM,
            **kwargs,
        )

    async def __aenter__(self):
        await self.pixel_client.__aenter__()
        await self._internal_client.__aenter__()
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        await self.pixel_client.__aexit__(exc_type, exc_value, traceback)
        await self._internal_client.__aexit__(exc_type, exc_value, traceback)

    async def _make_request(self, method: str, url: str, **kwargs) -> httpx.Response:
        """Make an HTTP request to the Pixel API with error handling.

        Args:
            method: The HTTP method to use (GET, POST, PUT, DELETE).
            url: The URL to request, relative to the base URL.
            **kwargs: Additional arguments to pass to the request method.

        Returns:
            httpx.Response: The HTTP response object.

        Raises:
            PixelBadRequestError: If the server returns a 4xx client error with JSON response.
            httpx.HTTPStatusError: For other HTTP errors.
        """
        sensitive_content = kwargs.pop("sensitive_content", False)
        headers = kwargs.pop("headers", {})
        if "X-Request-ID" not in headers:
            headers["X-Request-ID"] = str(uuid4())
        kwargs["headers"] = headers
        response = await self.pixel_client.request(method, url, **kwargs)
        try:
            response.raise_for_status()
        except httpx.HTTPStatusError as e:
            logger.error(f"Error in request {method} {url}: {e}")
            if e.response.is_client_error:
                try:
                    response_json = e.response.json()
                except json.JSONDecodeError:
                    raise e  # If the response is not JSON, raise the original exception
                raise PixelBadRequestError(
                    response_json=response_json,
                    status_code=e.response.status_code,
                    method=method,
                    url=str(e.request.url),
                    request_id=e.response.headers.get("X-Request-ID"),
                    body=e.request.content.decode() if not sensitive_content else None,
                ) from e
            raise e
        return response

    async def _get(self, url: str, **kwargs) -> httpx.Response:
        """Make a GET request to the Pixel API.

        Args:
            url: The URL to request, relative to the base URL.
            **kwargs: Additional arguments to pass to the request method.

        Returns:
            httpx.Response: The HTTP response object.
        """
        return await self._make_request("GET", url, **kwargs)

    async def _post(self, url: str, **kwargs) -> httpx.Response:
        """Make a POST request to the Pixel API.

        Args:
            url: The URL to request, relative to the base URL.
            **kwargs: Additional arguments to pass to the request method.

        Returns:
            httpx.Response: The HTTP response object.
        """
        return await self._make_request("POST", url, **kwargs)

    async def _put(self, url: str, **kwargs) -> httpx.Response:
        """Make a PUT request to the Pixel API.

        Args:
            url: The URL to request, relative to the base URL.
            **kwargs: Additional arguments to pass to the request method.

        Returns:
            httpx.Response: The HTTP response object.
        """
        return await self._make_request("PUT", url, **kwargs)

    async def _delete(self, url: str, **kwargs) -> httpx.Response:
        """Make a DELETE request to the Pixel API.

        Args:
            url: The URL to request, relative to the base URL.
            **kwargs: Additional arguments to pass to the request method.

        Returns:
            httpx.Response: The HTTP response object.
        """
        return await self._make_request("DELETE", url, **kwargs)

    async def _paginate(
        self,
        url: str,
        page_size: int,
        method: str = "GET",
        use_body: bool = False,
        results_parser: Callable[[dict], list[dict]] | None = None,
        **kwargs,
    ) -> AsyncGenerator[dict, None]:
        """Internal helper function for paginating through API results.

        Args:
            url: The API endpoint URL to paginate through.
            page_size: Number of items to fetch per page.
            method: HTTP method to use for the request (default is "GET").
            use_body: Whether to use the request body for pagination parameters instead of query parameters.
            **kwargs: Additional parameters to pass to the _make_request method.
        Yields:
            dict: Individual items from the paginated results, one at a time.
        """
        params: dict = kwargs.pop("params", {})
        body: dict = kwargs.pop("json", {})
        offset: int = params.get("offset", 0) if not use_body else body.get("offset", 0)
        limit = page_size
        while True:
            new_body = {**body, "offset": offset, "limit": limit} if use_body else body
            new_params = (
                {**params, "offset": offset, "limit": limit} if not use_body else params
            )
            response = await self._make_request(
                method, url, params=new_params, json=new_body, **kwargs
            )
            data = response.json()
            if results_parser and isinstance(data, dict):
                data = results_parser(data)
            for item in data:
                yield item
            if (
                len(data) < page_size
            ):  # If the number of items is less than the page size, we are done
                break
            offset += limit

    async def me(self, extended: bool = False) -> dict:
        """Get information about the authenticated user.

        Args:
            extended: If True, returns extended user information including projects user is a member of

        Returns:
            dict: User information including username, email, and other profile details.
        """
        response = await self._get("/users/me", params={"extended": extended})
        return response.json()

    async def get_plugins(self) -> list[dict]:
        """Retrieve a list of available plugins for the pixel tenant.
        Possible plugins include:
        * 'optimized_raster' - Optimize Raster capability
        * 'image_service' - Image Service capability, dependent on the 'optimize_raster' plugin.

        Returns:
            list[dict]: A list of plugin objects with their details.
        """
        response = await self._get("/plugins/")
        return response.json()

    async def create_project(
        self,
        name: str,
        description: str,
        area_of_interest: Polygon,
        parent_project_id: int | None = None,
        tags: list[str] | None = None,
    ) -> dict:
        """Create a new project in the Pixel system.

        Args:
            name: The name of the project.
            description: A description of the project.
            area_of_interest: A GeoJSON polygon defining the project's geographic area of interest.
            parent_project_id: Optional ID of a parent project. If provided, this project will be created as a child of that project.
            tags: Optional list of tags to associate with the project.

        Returns:
            dict: The created project object.
        """
        body = {
            "name": name,
            "description": description,
            "area_of_interest": area_of_interest.__geo_interface__,
        }
        if parent_project_id:
            body["parent_project_id"] = parent_project_id
        if tags:
            body["tags"] = tags
        response = await self._post("/projects/", json=body)
        return response.json()

    async def list_projects(
        self, params: ListParams | None = None, **kwargs
    ) -> list[dict]:
        """List projects with optional filtering.

        Args:
            params: Optional ListParams object containing filtering parameters such as offset, limit, search, etc.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of project objects matching the filter criteria.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get("/projects/", params=params_dict)
        return response.json()

    async def list_deleted_projects(
        self, params: ListParams | None = None, **kwargs
    ) -> list[dict]:
        """List deleted projects in the Pixel system.

        Args:
            params: Optional ListParams object containing filtering parameters such as offset, limit, search, etc.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of deleted project objects.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get("/projects/deleted", params=params_dict)
        return response.json()

    async def get_project(self, project_id: int, extended: bool = False) -> dict:
        """Retrieve a project by its ID.

        Args:
            project_id: The ID of the project to retrieve.
            extended: If True, returns extended project information including child projects and data collections.

        Returns:
            dict: The project object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}", params={"extended": extended}
        )
        return response.json()

    async def update_project(
        self,
        project_id: int,
        name: str | None = None,
        description: str | None = None,
        area_of_interest: Polygon | None = None,
        add_tags: list[str] | None = None,
        remove_tags: list[str] | None = None,
    ) -> dict:
        """Update an existing project with new values.

        Args:
            project_id: The ID of the project to update.
            name: Optional new name for the project.
            description: Optional new description for the project.
            area_of_interest: Optional new GeoJSON polygon defining the project's geographic area of interest.
            add_tags: Optional list of tags to add to the project.
            remove_tags: Optional list of tags to remove from the project.

        Returns:
            dict: The updated project object.

        Raises:
            ValueError: If no update parameters are provided.
        """
        body = {}
        for param_name, value in {
            "name": name,
            "description": description,
            "area_of_interest": area_of_interest.__geo_interface__
            if area_of_interest
            else None,
            "add_tags": add_tags,
            "remove_tags": remove_tags,
        }.items():
            if value is not None:
                body[param_name] = value
        if not body:
            raise ValueError("No update parameters provided")
        response = await self._put(f"/projects/{project_id}", json=body)
        return response.json()

    async def delete_project(self, project_id: int) -> dict:
        """Delete a project by its ID.

        Args:
            project_id: The ID of the project to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(f"/projects/{project_id}")
        return response.json()

    async def restore_project(self, project_id: int) -> dict:
        """Restore a deleted project by its ID.

        Args:
            project_id: The ID of the project to restore.

        Returns:
            dict: The restored project object.
        """
        response = await self._post(f"/projects/{project_id}/restore")
        return response.json()

    async def move_project(
        self, project_id: int, new_parent_project_id: int | None = None
    ) -> dict:
        """Move a project to a new parent project or to the root level.

        Args:
            project_id: The ID of the project to move.
            new_parent_project_id: Optional ID of the new parent project. If None, the project will be moved to the root level.

        Returns:
            dict: The updated project object.
        """
        # If None is provided, set to -1 to move to root
        new_parent_project_id = new_parent_project_id or -1
        response = await self._put(
            f"/projects/{project_id}",
            params={"new_parent_id": new_parent_project_id},
        )
        return response.json()

    async def create_data_collection(
        self,
        project_id: int,
        name: str,
        description: str,
        data_collection_type: DataCollectionType,
        tags: list[str] | None = None,
        raster_info: RasterInfo | None = None,
    ) -> dict:
        """Create a new data collection within a project.

        Args:
            project_id: The ID of the project to create the data collection in.
            name: The name of the data collection.
            description: A description of the data collection.
            data_collection_type: The type of data collection (e.g., "image", "raster", "RGB", "DTM", "DSM").
            tags: Optional list of tags to associate with the data collection.
            raster_info: Optional RasterInfo object containing raster-specific configuration.

        Returns:
            dict: The created data collection object.
        """
        body: dict[str, Any] = {
            "name": name,
            "description": description,
            "data_collection_type": data_collection_type,
        }
        if tags:
            body["tags"] = tags
        if raster_info:
            body["raster_info"] = raster_info.model_dump(exclude_none=True, mode="json")
        response = await self._post(
            f"/projects/{project_id}/data_collections/", json=body
        )
        return response.json()

    async def list_data_collections(
        self, project_id: int, params: DataCollectionListParams | None = None, **kwargs
    ) -> list[dict]:
        """List data collections within a project with optional filtering.

        Args:
            project_id: The ID of the project to list data collections from.
            params: Optional DataCollectionListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of data collection objects matching the filter criteria.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else DataCollectionListParams.model_validate(kwargs).model_dump(
                exclude_none=True
            )
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/", params=params_dict
        )
        return response.json()

    async def list_deleted_data_collections(
        self, project_id: int, params: DataCollectionListParams | None = None, **kwargs
    ) -> list[dict]:
        """List deleted data collections within a project.

        Args:
            project_id: The ID of the project to list deleted data collections from.

        Returns:
            list[dict]: A list of deleted data collection objects.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else DataCollectionListParams.model_validate(kwargs).model_dump(
                exclude_none=True
            )
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/deleted", params=params_dict
        )
        return response.json()

    async def get_data_collection(
        self, project_id: int, data_collection_id: int
    ) -> dict:
        """Retrieve a data collection by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to retrieve.

        Returns:
            dict: The data collection object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}"
        )
        return response.json()

    async def update_data_collection(
        self,
        project_id: int,
        data_collection_id: int,
        name: str | None = None,
        description: str | None = None,
        add_tags: list[str] | None = None,
        remove_tags: list[str] | None = None,
    ) -> dict:
        """Update an existing data collection with new values.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to update.
            name: Optional new name for the data collection.
            description: Optional new description for the data collection.
            add_tags: Optional list of tags to add to the data collection.
            remove_tags: Optional list of tags to remove from the data collection.

        Returns:
            dict: The updated data collection object.

        Raises:
            ValueError: If no update parameters are provided.
        """
        body = {}
        for param_name, value in {
            "name": name,
            "description": description,
            "add_tags": add_tags,
            "remove_tags": remove_tags,
        }.items():
            if value is not None:
                body[param_name] = value
        if not body:
            raise ValueError("No update parameters provided")
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}", json=body
        )
        return response.json()

    async def move_data_collection(
        self, project_id: int, data_collection_id: int, new_project_id: int
    ) -> dict:
        """Move a data collection to a different project.

        Args:
            project_id: The ID of the project currently containing the data collection.
            data_collection_id: The ID of the data collection to move.
            new_project_id: The ID of the project to move the data collection to.

        Returns:
            dict: The updated data collection object.
        """
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}",
            params={"new_project_id": new_project_id},
        )
        return response.json()

    async def delete_data_collection(
        self, project_id: int, data_collection_id: int
    ) -> dict:
        """Delete a data collection by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(
            f"/projects/{project_id}/data_collections/{data_collection_id}"
        )
        return response.json()

    async def restore_data_collection(
        self, project_id: int, data_collection_id: int
    ) -> dict:
        """Restore a deleted data collection by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to restore.

        Returns:
            dict: The restored data collection object.
        """
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/restore"
        )
        return response.json()

    async def get_images(
        self,
        project_id: int,
        data_collection_id: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> dict:
        """Retrieve images from a data collection with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the images.
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters.

        Returns:
            dict: A list of image objects matching the filter criteria.
        """
        params_dict = params.model_dump(exclude_none=True) if params else {}
        params_dict.update(kwargs)
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/images/",
            params=params_dict,
        )
        return response.json()

    async def paginate_images(
        self,
        project_id: int,
        data_collection_id: int,
        page_size: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> AsyncGenerator[dict, None]:
        """Paginate through images in a data collection with optional filtering.

        This method returns an async generator that yields images one at a time,
        automatically handling pagination in the background.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the images.
            page_size: The number of images to fetch per page.
            params: Optional ListParams object containing filtering parameters (excluding offset and limit).
            **kwargs: Alternative way to provide filtering parameters.

        Yields:
            dict: Image objects matching the filter criteria, one at a time.
        """
        params_dict = (
            params.model_dump(exclude_none=True, exclude={"offset", "limit"})
            if params
            else {}
        )
        params_dict.update(kwargs)
        url = f"/projects/{project_id}/data_collections/{data_collection_id}/images/"
        async for item in self._paginate(url, page_size, params=params_dict):
            yield item

    async def get_image(
        self,
        project_id: int,
        data_collection_id: int,
        image_id: int,
    ) -> dict:
        """Retrieve a specific image by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the image.
            image_id: The ID of the image to retrieve.

        Returns:
            dict: The image object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
        )
        return response.json()

    async def get_image_metadata(
        self, project_id: int, data_collection_id: int, image_id: int
    ) -> dict:
        """
        Retrieve metadata for a specific image by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the image.
            image_id: The ID of the image to retrieve metadata for.

        Returns:
            dict: The image metadata object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}/metadata"
        )
        return response.json()

    async def update_image(
        self,
        project_id: int,
        data_collection_id: int,
        image_id: int,
        update_input: ImageUpdateInput,
    ) -> dict:
        """Update an existing image with new values.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the image.
            image_id: The ID of the image to update.
            update_input: ImageUpdateInput object containing the fields to update.

        Returns:
            dict: The updated image object.
        """

        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}",
            json=update_input.model_dump(mode="json", exclude_none=True),
        )
        return response.json()

    async def delete_image(
        self,
        project_id: int,
        data_collection_id: int,
        image_id: int,
    ) -> dict:
        """Delete a specific image by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the image.
            image_id: The ID of the image to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(
            f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
        )
        return response.json()

    async def get_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> dict:
        """Retrieve rasters from a data collection with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the rasters.
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters.

        Returns:
            dict: A list of raster objects matching the filter criteria.
        """
        params_dict = params.model_dump(exclude_none=True) if params else {}
        params_dict.update(kwargs)
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/",
            params=params_dict,
        )
        return response.json()

    async def paginate_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        page_size: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> AsyncGenerator[dict, None]:
        """Paginate through rasters in a data collection with optional filtering.

        This method returns an async generator that yields rasters one at a time,
        automatically handling pagination in the background.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the rasters.
            page_size: The number of rasters to fetch per page.
            params: Optional ListParams object containing filtering parameters (excluding offset and limit).
            **kwargs: Alternative way to provide filtering parameters.

        Yields:
            dict: Raster objects matching the filter criteria, one at a time.
        """
        params_dict = (
            params.model_dump(exclude_none=True, exclude={"offset", "limit"})
            if params
            else {}
        )
        params_dict.update(kwargs)
        url = f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/"
        async for item in self._paginate(url, page_size, params=params_dict):
            yield item

    async def get_raster(
        self,
        project_id: int,
        data_collection_id: int,
        raster_id: int,
    ) -> dict:
        """Retrieve a specific raster by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the raster.
            raster_id: The ID of the raster to retrieve.

        Returns:
            dict: The raster object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
        )
        return response.json()

    async def update_raster(
        self,
        project_id: int,
        data_collection_id: int,
        raster_id: int,
        update_input: RasterUpdateInput,
    ) -> dict:
        """Update an existing raster with new values.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the raster.
            raster_id: The ID of the raster to update.
            update_input: RasterUpdateInput object containing the fields to update.

        Returns:
            dict: The updated raster object.

        """
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}",
            json=update_input.model_dump(mode="json", exclude_none=True),
        )
        return response.json()

    async def delete_raster(
        self,
        project_id: int,
        data_collection_id: int,
        raster_id: int,
    ) -> dict:
        """Delete a specific raster by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the raster.
            raster_id: The ID of the raster to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
        )
        return response.json()

    async def get_upload_jobs(
        self,
        project_id: int,
        data_collection_id: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> list[dict]:
        """Retrieve upload jobs for a data collection with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to list upload jobs for.
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of upload job objects matching the filter criteria.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/",
            params=params_dict,
        )
        return response.json()

    async def _create_upload_jobs(
        self,
        project_id: int,
        data_collection_id: int,
        multipart: bool,
        files: list[dict],
    ) -> list[dict]:
        """Internal helper to create upload job objects in the API.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to create upload jobs for.
            multipart: If True, create multipart upload jobs for large files.
            files: List of file objects containing metadata for the upload jobs.

        Returns:
            list[dict]: The created upload job objects.
        """
        url = (
            f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/"
        )
        if multipart:
            url += "multipart"
        body = {"files": files}
        response = await self._post(url, json=body)
        return response.json()

    def _create_support_file_file(
        self,
        file_path: Path,
    ) -> dict:
        """Create a file object for a support file to be included in an upload job.

        Args:
            file_path: Path to the support file.

        Returns:
            dict: A file object containing the file name and MD5 hash.

        Raises:
            FileNotFoundError: If the file does not exist.
        """
        if not file_path.exists():
            raise FileNotFoundError(f"File {file_path} not found")
        return {
            "name": file_path.name,
            "md5": calculate_md5_base64_from_file(file_path),
        }

    def _create_single_part_upload_job_from_file(
        self,
        file_path: Path,
        support_files: list[Path] | None = None,
        metadata: dict | None = None,
    ) -> dict:
        """Create a file object for a single-part upload job.

        Args:
            file_path: Path to the file to upload.
            support_files: Optional list of support file paths to include with the upload.
            metadata: Optional metadata to associate with the file.

        Returns:
            dict: A file object containing the file name, MD5 hash, and optional metadata and support files.
        """
        body: dict[str, Any] = {
            "name": file_path.name,
            "md5": calculate_md5_base64_from_file(file_path),
        }
        if metadata:
            body["metadata"] = metadata
        if support_files:
            body["support_files"] = [
                self._create_support_file_file(f) for f in support_files
            ]
        return body

    def _create_multipart_upload_job_from_file(
        self,
        file_path: Path,
        part_size: int,
        support_files: list[Path] | None = None,
        metadata: dict | None = None,
    ) -> dict:
        """Create a file object for a multipart upload job.

        Args:
            file_path: Path to the file to upload.
            part_size: Size of each part in bytes.
            support_files: Optional list of support file paths to include with the upload.
            metadata: Optional metadata to associate with the file.

        Returns:
            dict: A file object containing the file name, parts information, and optional metadata and support files.
        """
        parts = []
        for part_number, (content_length, md5, _) in enumerate(
            iter_file_parts(file_path, part_size), start=1
        ):
            parts.append(
                {
                    "part_number": part_number,
                    "md5": md5,
                    "content_length": content_length,
                }
            )
        file_body = {
            "name": file_path.name,
            "parts": parts,
        }
        if metadata:
            file_body["metadata"] = metadata
        if support_files:
            file_body["support_files"] = [
                self._create_support_file_file(f) for f in support_files
            ]
        return file_body

    async def _upload_singlepart_to_s3(
        self,
        upload_job: dict,
        file_path: Path,
    ):
        """Upload a file to S3 using a single part upload.

        Args:
            upload_job: Upload job object containing the S3 URL and upload fields.
            file_path: Path to the file to upload.

        Returns:
            None: This method returns None on success.

        Raises:
            httpx.HTTPStatusError: If the upload fails.
        """
        async with self._semaphore:
            response = await self._internal_client.post(
                upload_job["url"],
                files={"file": file_path.read_bytes()},
                data=upload_job["upload_fields"],
            )
            response.raise_for_status()
        return None

    async def _upload_multipart_to_s3(
        self, upload_job: dict, file_path: Path, multipart_part_size: int
    ):
        parts = sorted(upload_job["upload_parts"], key=lambda p: p["part_number"])

        async def read_and_upload_single_part(part_index, part):
            async with self._semaphore:
                with open(file_path, "rb") as f:
                    f.seek(part_index * multipart_part_size)
                    part_data = f.read(multipart_part_size)

                response = await self._internal_client.put(
                    part["url"], content=part_data, headers=part["headers"]
                )
                response.raise_for_status()

        tasks = [read_and_upload_single_part(i, part) for i, part in enumerate(parts)]

        with silence_logger(logging.getLogger("httpx")):
            await tqdm_asyncio.gather(
                *tasks, total=len(tasks), desc=f"Uploading {file_path.name} to Pixel"
            )

        return None

    async def _upload_to_s3(
        self,
        file: Path,
        support_files: list[Path] | None,
        upload_job: dict,
        multipart: bool,
        multipart_part_size: int | None,
    ):
        """Upload a file and its support files to S3.

        Args:
            file: Path to the main file to upload.
            support_files: Optional list of support file paths to upload with the main file.
            upload_job: Upload job object containing the upload information.
            multipart: If True, use multipart upload for the main file.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            None: This method returns None on success.

        Raises:
            AssertionError: If multipart is True but multipart_part_size is not provided,
                           or if support_files are required but not provided.
        """
        logger.info(f"Uploading {file} to S3 with upload job {upload_job['id']}")
        if multipart:
            assert multipart_part_size, (
                "multipart_part_size must be provided for multipart upload"
            )
            await self._upload_multipart_to_s3(upload_job, file, multipart_part_size)
        else:
            await self._upload_singlepart_to_s3(upload_job, file)
        if upload_job.get("support_files"):
            assert support_files, "Support files must be provided for upload job"
            # Sort the support file by name
            support_files = sorted(support_files, key=lambda f: f.name)
            upload_job_support_files = sorted(
                upload_job["support_files"], key=lambda f: f["name"]
            )
            await asyncio.gather(
                *[
                    self._upload_singlepart_to_s3(uj_sp, sp_path)
                    for uj_sp, sp_path in zip(upload_job_support_files, support_files)
                ]
            )
        logger.info(f"Upload job {upload_job['id']} with {file} completed upload")
        return None

    async def _upload_file_finished(
        self,
        project_id: int,
        data_collection_id: int,
        upload_job_id: int,
    ) -> dict:
        """Signal to the API that a file upload has completed.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the upload job.
            upload_job_id: The ID of the upload job to mark as finished.

        Returns:
            dict: The response containing job information for the validation process.
        """
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/{upload_job_id}/uploadFinished"
        )
        return response.json()

    async def _multiple_upload_file_finished(
        self,
        project_id: int,
        data_collection_id: int,
        upload_job_ids: list[int],
    ) -> dict:
        """Signal to the API that multiple file uploads have completed.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the upload jobs.
            upload_job_ids: List of upload job IDs to mark as finished.

        Returns:
            dict: The response containing group job information and updated upload jobs.
        """
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/multiple_uploadFinished",
            json={"job_ids": upload_job_ids},
        )
        return response.json()

    async def _wait_for_multiple_upload_jobs(
        self,
        project_id: int,
        data_collection_id: int,
        group_job_id: int,
        upload_job_ids: list[int],
    ) -> tuple[list[dict], list[PixelUploadJobError]]:
        """Wait for multiple upload jobs to complete validation and processing.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the upload jobs.
            group_job_id: The ID of the group job managing the upload jobs.
            upload_job_ids: List of upload job IDs to wait for.

        Returns:
            tuple: A tuple containing:
                - list[dict]: List of successfully completed upload jobs.
                - list[PixelUploadJobError]: List of errors for failed upload jobs.
        """
        _ = await self.wait_for_group_job(group_job_id=group_job_id)
        upload_jobs = await self.get_upload_jobs(
            project_id,
            data_collection_id,
            ids=upload_job_ids,
            limit=len(upload_job_ids),
        )
        while any(
            uj["status"] in ("lobby", "validating", "submitted", "validated")
            for uj in upload_jobs
        ):
            upload_jobs = await self.get_upload_jobs(
                project_id,
                data_collection_id,
                ids=upload_job_ids,
                limit=len(upload_job_ids),
            )
            await asyncio.sleep(1)
        # Collect any errors
        errors = []
        finished_upload_jobs = []
        for uj in upload_jobs:
            try:
                if uj["status"] != "validated_and_moved":
                    raise PixelUploadJobError(
                        job_id=uj["id"], status=uj["status"], detail=uj["detail"]
                    )
            except PixelUploadJobError as e:
                errors.append(e)
            else:
                finished_upload_jobs.append(uj)
        return finished_upload_jobs, errors

    async def _wait_for_upload_job(
        self, project_id: int, data_collection_id: int, upload_job_id: int, job_id: int
    ) -> dict:
        """Wait for a single upload job to complete validation and processing.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the upload job.
            upload_job_id: The ID of the upload job to wait for.
            job_id: The ID of the job managing the upload job validation.

        Returns:
            dict: The completed upload job object.

        Raises:
            PixelUploadJobError: If the upload job fails validation or processing.
        """
        await self.wait_for_job(job_id)
        upload_jobs = await self.get_upload_jobs(
            project_id, data_collection_id, ids=[upload_job_id], limit=1
        )
        upload_job = upload_jobs[0]
        if upload_job["status"] == "validated_and_moved":
            return upload_job
        if upload_job["status"] != "validated_and_moved":
            raise PixelUploadJobError(
                job_id=upload_job_id,
                status=upload_job["status"],
                detail=upload_job["detail"],
            )
        return upload_job

    async def _resources_from_upload_jobs(
        self, project_id: int, data_collection_id: int, upload_jobs: list[dict]
    ) -> list[dict]:
        """Retrieve the created resources (images or rasters) from completed upload jobs.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the resources.
            upload_jobs: List of completed upload job objects.

        Returns:
            list[dict]: List of resource objects (images or rasters) created from the upload jobs.
        """
        # Chunk up the resources ids
        chunk_size = 50
        image_resource_ids: list[int] = []
        raster_resource_ids: list[int] = []
        image_resources: list[dict] = []
        raster_resources: list[dict] = []
        for upload_job in upload_jobs:
            if upload_job["result"]["resource_name"] == "image":
                image_resource_ids.append(upload_job["result"]["resource_id"])
            if upload_job["result"]["resource_name"] == "raster":
                raster_resource_ids.append(upload_job["result"]["resource_id"])
        for chunk in chunks(image_resource_ids, chunk_size):
            image_resources.extend(
                await self.get_images(
                    project_id,
                    data_collection_id,
                    params=ListParams(ids=chunk, limit=len(chunk)),
                )
            )
        for chunk in chunks(raster_resource_ids, chunk_size):
            raster_resources.extend(
                await self.get_rasters(
                    project_id,
                    data_collection_id,
                    params=ListParams(ids=chunk, limit=len(chunk)),
                )
            )
        resources = image_resources + raster_resources
        return resources

    async def _resource_from_upload_job(
        self, project_id: int, data_collection_id: int, upload_job: dict
    ) -> dict:
        """Retrieve the created resource (image or raster) from a completed upload job.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the resource.
            upload_job: The completed upload job object.

        Returns:
            dict: The resource object (image or raster) created from the upload job.

        Raises:
            ValueError: If the resource type in the upload job result is unknown.
        """
        if upload_job["result"]["resource_name"] == "image":
            return await self.get_image(
                project_id, data_collection_id, upload_job["result"]["resource_id"]
            )
        if upload_job["result"]["resource_name"] == "raster":
            return await self.get_raster(
                project_id, data_collection_id, upload_job["result"]["resource_id"]
            )
        raise ValueError(
            f"Unknown resource name in upload job result: {upload_job['result']}"
        )

    async def _upload_multiple_files(
        self,
        project_id: int,
        data_collection_id: int,
        files: list[PixelUploadFile],
        multipart: bool,
        multipart_part_size: int | None,
        raise_on_error: bool = False,
    ) -> tuple[list[dict], list[PixelUploadJobError]]:
        """Upload multiple files to a data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to upload to.
            files: List of PixelUploadFile objects containing the files to upload.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.
            raise_on_error: If True, raise a PixelMultipleUploadJobError if any uploads fail.

        Returns:
            tuple: A tuple containing:
                - list[dict]: List of created resource objects (images or rasters).
                - list[PixelUploadJobError]: List of errors for failed uploads.

        Raises:
            ValueError: If any files have duplicate names.
            PixelMultipleUploadJobError: If raise_on_error is True and any uploads fail.
        """

        # Chunk the operation into 200 files at a time (maximum for API)
        all_resources: list[dict] = []
        all_errors: list[PixelUploadJobError] = []

        create_body_func = (
            partial(
                self._create_multipart_upload_job_from_file,
                part_size=multipart_part_size,  # type: ignore
            )
            if multipart
            else self._create_single_part_upload_job_from_file
        )
        # Assert unique file names
        file_names = [f.file.name for f in files]
        if len(file_names) != len(set(file_names)):
            raise ValueError("All files must have unique names")
        for files_chunk in chunks(files, 200):
            logger.info("Uploading chunk of %d files", len(files_chunk))
            file_bodies = [
                create_body_func(
                    file.file,
                    support_files=file.support_files,
                    metadata=file.metadata.model_dump(mode="json", exclude_none=True)
                    if file.metadata
                    else None,
                )
                for file in files_chunk
            ]
            upload_jobs = await self._create_upload_jobs(
                project_id, data_collection_id, multipart, file_bodies
            )
            # sort the upload jobs by the file name
            upload_jobs = sorted(upload_jobs, key=lambda uj: uj["name"])
            files = sorted(files, key=lambda f: f.file.name)
            await asyncio.gather(
                *[
                    self._upload_to_s3(
                        file.file,
                        file.support_files,
                        upload_job,
                        multipart,
                        multipart_part_size,
                    )
                    for upload_job, file in zip(upload_jobs, files)
                ]
            )
            upload_finished = await self._multiple_upload_file_finished(
                project_id, data_collection_id, [uj["id"] for uj in upload_jobs]
            )
            group_job = upload_finished["group_job"]
            upload_jobs = upload_finished["upload_jobs"]
            upload_jobs, errors = await self._wait_for_multiple_upload_jobs(
                project_id,
                data_collection_id,
                group_job["group_id"],
                [uj["id"] for uj in upload_jobs],
            )
            resources = await self._resources_from_upload_jobs(
                project_id, data_collection_id, upload_jobs
            )
            all_resources.extend(resources)
            all_errors.extend(errors)

        if raise_on_error and all_errors:
            raise PixelMultipleUploadJobError(errors)
        return all_resources, all_errors

    async def _upload_file(
        self,
        project_id: int,
        data_collection_id: int,
        file_path: Path,
        support_files: list[Path] | None = None,
        metadata: dict | None = None,
        multipart: bool = False,
        multipart_part_size: int | None = None,
    ) -> dict:
        """Upload a single file to a data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to upload to.
            file_path: Path to the file to upload.
            support_files: Optional list of support file paths to upload with the file.
            metadata: Optional dictionary of metadata to associate with the file.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            dict: The created resource object (image or raster).

        Raises:
            FileNotFoundError: If the file does not exist.
            ValueError: If multipart is True but multipart_part_size is not provided.
            PixelUploadJobError: If the upload job fails validation or processing.
        """
        if not file_path.exists():
            raise FileNotFoundError(f"File {file_path} not found")
        if multipart and not multipart_part_size:
            raise ValueError(
                "multipart_part_size must be provided for multipart upload"
            )
        if multipart:
            assert multipart_part_size
            file_body = self._create_multipart_upload_job_from_file(
                file_path,
                multipart_part_size,
                support_files=support_files,
                metadata=metadata,
            )
        else:
            file_body = self._create_single_part_upload_job_from_file(
                file_path,
                support_files=support_files,
                metadata=metadata,
            )
        upload_jobs = await self._create_upload_jobs(
            project_id, data_collection_id, multipart, [file_body]
        )
        upload_job = upload_jobs[0]
        await self._upload_to_s3(
            file_path,
            support_files,
            upload_job,
            multipart,
            multipart_part_size,
        )
        upload_job_finished = await self._upload_file_finished(
            project_id, data_collection_id, upload_job["id"]
        )
        job = upload_job_finished["job"]
        upload_job = await self._wait_for_upload_job(
            project_id, data_collection_id, upload_job["id"], job["job_id"]
        )
        return await self._resource_from_upload_job(
            project_id, data_collection_id, upload_job
        )

    async def upload_image(
        self,
        project_id: int,
        data_collection_id: int,
        file_path: Path,
        metadata: dict | None = None,
        support_files: list[Path] | None = None,
        multipart: bool = False,
        multipart_part_size: int | None = None,
    ) -> dict:
        """Upload an image file to an image data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the image data collection to upload to.
            file_path: Path to the image file to upload.
            metadata: Optional dictionary of metadata to associate with the image.
            support_files: Optional list of support file paths to upload with the image.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            dict: The created image object.

        Raises:
            ValueError: If the data collection is not an image data collection.
            FileNotFoundError: If the file does not exist.
            ValueError: If multipart is True but multipart_part_size is not provided.
        """
        dc = await self.get_data_collection(project_id, data_collection_id)
        if dc["data_collection_type"] != "image":
            raise ValueError("Data collection is not an image data collection")
        return await self._upload_file(
            project_id,
            data_collection_id,
            file_path,
            support_files=support_files,
            metadata=metadata,
            multipart=multipart,
            multipart_part_size=multipart_part_size,
        )

    async def upload_multiple_images(
        self,
        project_id: int,
        data_collection_id: int,
        files: list[PixelUploadFile],
        multipart: bool = False,
        multipart_part_size: int | None = None,
    ) -> tuple[list[dict], list[PixelUploadJobError]]:
        """Upload multiple image files to an image data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the image data collection to upload to.
            files: List of PixelUploadFile objects containing the files to upload.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            tuple: A tuple containing:
                - list[dict]: List of created image objects.
                - list[PixelUploadJobError]: List of errors that occurred during upload.

        Raises:
            ValueError: If the data collection is not an image data collection.
            ValueError: If any files have duplicate names.
            ValueError: If multipart is True but multipart_part_size is not provided.
        """
        dc = await self.get_data_collection(project_id, data_collection_id)
        if dc["data_collection_type"] != "image":
            raise ValueError("Data collection is not an image data collection")
        return await self._upload_multiple_files(
            project_id,
            data_collection_id,
            files,
            multipart,
            multipart_part_size,
        )

    async def upload_multiple_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        files: list[PixelUploadFile],
        multipart: bool = False,
        multipart_part_size: int | None = None,
    ) -> tuple[list[dict], list[PixelUploadJobError]]:
        """Upload multiple raster files to a raster data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the raster data collection to upload to.
            files: List of PixelUploadFile objects containing the files to upload.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            tuple: A tuple containing:
                - list[dict]: List of created raster objects.
                - list[PixelUploadJobError]: List of errors that occurred during upload.

        Raises:
            ValueError: If the data collection is not a raster data collection.
            ValueError: If any files have duplicate names.
            ValueError: If multipart is True but multipart_part_size is not provided.
        """
        dc = await self.get_data_collection(project_id, data_collection_id)
        if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
            raise ValueError("Data collection is not a raster data collection")
        return await self._upload_multiple_files(
            project_id,
            data_collection_id,
            files,
            multipart,
            multipart_part_size,
        )

    async def upload_raster(
        self,
        project_id: int,
        data_collection_id: int,
        file_path: Path,
        support_files: list[Path] | None = None,
        multipart: bool = False,
        multipart_part_size: int | None = None,
    ) -> dict:
        """Upload a raster file to a raster data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the raster data collection to upload to.
            file_path: Path to the raster file to upload.
            support_files: Optional list of support file paths to upload with the raster.
            multipart: If True, use multipart upload for large files.
            multipart_part_size: Required size of each part in bytes when using multipart upload.

        Returns:
            dict: The created raster object.

        Raises:
            ValueError: If the data collection is not a raster data collection.
            FileNotFoundError: If the file does not exist.
            ValueError: If multipart is True but multipart_part_size is not provided.
        """
        dc = await self.get_data_collection(project_id, data_collection_id)
        if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
            raise ValueError("Data collection is not a raster data collection")
        return await self._upload_file(
            project_id,
            data_collection_id,
            file_path,
            support_files=support_files,
            multipart=multipart,
            multipart_part_size=multipart_part_size,
        )

    async def create_optimized_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        raster_ids: list[int] | None,
        profile: str | None = None,
        nearblack: NearblackOptions | None = None,
        overview_resampling: OverviewResampling = "average",
    ) -> list[dict]:
        """Create optimized raster objects in the database.

        This function creates optimized raster objects but does not run the actual optimization process.
        To run the optimization, use the run_optimize_rasters function with the returned optimized raster IDs.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the rasters.
            raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
            profile: Optional profile name to use for optimization.
            nearblack: Optional NearblackOptions object for configuring the nearblack process.
            overview_resampling: The resampling method to use for creating overviews. Default is "average".

        Returns:
            list[dict]: List of created optimized raster objects.
        """
        body: dict = {
            "creation_options": {
                "nearblack_options": nearblack.model_dump(
                    exclude_none=True, mode="json"
                )
                if nearblack
                else NearblackOptions(enabled=False).model_dump(
                    exclude_none=True, mode="json"
                ),
                "overview_resampling": overview_resampling,
            }
        }
        if raster_ids:
            body["raster_ids"] = raster_ids
        if profile:
            body["profile"] = profile
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
            json=body,
        )
        return response.json()

    async def run_optimize_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        optimize_raster_ids: list[int] | None,
        retry_failed: bool = False,
    ) -> dict:
        """Run the optimization process on optimized raster objects.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the optimized rasters.
            optimize_raster_ids: Optional list of optimized raster IDs to process. If None, all optimized rasters in the collection will be processed.
            retry_failed: If True, retry previously failed optimization jobs.

        Returns:
            dict: The group job object representing the optimization process.
        """
        body: dict = {"retry_failed": retry_failed}
        if optimize_raster_ids:
            body["optimized_raster_ids"] = optimize_raster_ids
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/run",
            json=body,
        )
        response_json = response.json()

        job = await self.wait_for_group_job(response_json["group_job"]["group_id"])
        return job

    async def get_job(
        self,
        job_id: int,
    ) -> dict:
        """Retrieve information about a specific job.

        Args:
            job_id: The ID of the job to retrieve.

        Returns:
            dict: The job object with its details.
        """
        response = await self._get(f"/jobs/{job_id}")
        return response.json()

    async def get_job_group(
        self,
        job_id: int,
    ) -> dict:
        """Retrieve information about a specific job group.

        Args:
            job_id: The ID of the job group to retrieve.

        Returns:
            dict: The job group object with its details.
        """
        response = await self._get(f"/jobs/groups/{job_id}")
        return response.json()

    async def wait_for_job(
        self,
        job_id: int,
        timeout: int = 600,
    ) -> dict:
        """Wait for a job to complete, polling its status at regular intervals.

        Args:
            job_id: The ID of the job to wait for.
            timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 600 seconds (10 minutes).

        Returns:
            dict: The completed job object.

        Raises:
            TimeoutError: If the job does not complete within the specified timeout period.
        """
        job = await self.get_job(job_id)
        with silence_logger(logging.getLogger("httpx")):
            while not job["completed"]:
                job = await self.get_job(job_id)
                job_name = job["name"] or "unnamed"
                logger.info(f"Job {job_name} {job_id} status: {job['status']}")
                await asyncio.sleep(3)
                timeout -= 5
                if timeout <= 0:
                    raise TimeoutError("Timed out waiting for job")
        logger.info(f"Job {job_id} finished with status {job['status']}")
        return job

    async def wait_for_group_job(
        self,
        group_job_id: int,
        timeout: int = 1200,
    ) -> dict:
        """Wait for a group job to complete, polling its status at regular intervals.

        A group job consists of multiple individual jobs. This method displays a progress bar
        showing the completion status of all jobs in the group.

        Args:
            group_job_id: The ID of the group job to wait for.
            timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 1200 seconds (20 minutes).

        Returns:
            dict: The completed group job object.

        Raises:
            TimeoutError: If the group job does not complete within the specified timeout period.
        """
        job = await self.get_job_group(group_job_id)
        num_jobs = job["total_jobs"]
        with (
            silence_logger(logging.getLogger("httpx")),
            tqdm.tqdm(total=num_jobs, desc=f"Running group job {group_job_id}") as pbar,
        ):
            while not job["completed"]:
                job = await self.get_job_group(group_job_id)
                num_failed = job["failed_count"]
                num_success = job["success_count"]
                num_finished = num_failed + num_success
                pbar.n = num_finished
                pbar.refresh()
                await asyncio.sleep(3)
                timeout -= 5
                if timeout <= 0:
                    raise TimeoutError("Timed out waiting for optimize rasters job")
        logger.info(
            f"Group job {group_job_id} finished {job['total_jobs']} jobs, with {num_failed} failures and {num_success} successes"
        )
        return job

    async def get_optimized_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> list[dict]:
        """Retrieve optimized rasters from a data collection with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the optimized rasters.
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters.

        Returns:
            list[dict]: A list of optimized raster objects matching the filter criteria.
        """
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
            params=params_dict,
        )
        return response.json()

    async def delete_optimized_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        raster_id: int,
        profile: str | None = None,
    ) -> list[dict]:
        """Delete optimized rasters associated with a specific raster.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the raster.
            raster_id: The ID of the raster whose optimized versions should be deleted.
            profile: Optional profile name to filter which optimized rasters to delete.
                    If None, all optimized versions of the raster will be deleted.

        Returns:
            list[dict]: A list of the deleted optimized raster objects.
        """
        params = {}
        if profile:
            params["profile"] = profile
        response = await self._delete(
            f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}/optimized",
            params=params,
        )
        return response.json()

    async def optimize_rasters(
        self,
        project_id: int,
        data_collection_id: int,
        raster_ids: list[int] | None = None,
        profile: str | None = None,
        nearblack: NearblackOptions | None = None,
        overview_resampling: OverviewResampling = "average",
    ) -> list[dict]:
        """Create and run optimization on rasters in a data collection.

        This is a convenience method that combines create_optimized_rasters and run_optimize_rasters
        into a single operation.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the rasters.
            raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
            profile: Optional profile name to use for optimization.
            nearblack: Optional NearblackOptions object for configuring the nearblack process.
            overview_resampling: The resampling method to use for creating overviews. Default is "average".

        Returns:
            list[dict]: List of optimized raster objects after the optimization process has completed.
        """
        optimized_rasters = await self.create_optimized_rasters(
            project_id,
            data_collection_id,
            raster_ids,
            profile,
            nearblack=nearblack,
            overview_resampling=overview_resampling,
        )
        await self.run_optimize_rasters(
            project_id, data_collection_id, [r["id"] for r in optimized_rasters]
        )
        optimized_rasters = await self.get_optimized_rasters(
            project_id,
            data_collection_id,
            params=ListParams(
                ids=[r["id"] for r in optimized_rasters], limit=len(optimized_rasters)
            ),
        )
        return optimized_rasters

    async def list_gdo_users(self) -> list[str]:
        """Retrieve a list of GDO (GeoData Online) users.

        Returns:
            list[dict]: A list of GDO user names.
        """
        response = await self._get("/arcgis_services/gdo-users")
        return response.json()

    async def create_arcgis_service(
        self,
        service_type: Literal["Feature", "Image"],
        create_input: ArcgisServiceCreateInput,
    ) -> dict:
        """Create a new ArcGIS service.

        Args:
            service_type: The type of service to create, either "Feature" or "Image".
            create_input: ArcgisServiceCreateInput object containing the service configuration.

        Returns:
            dict: The created ArcGIS service object.

        Raises:
            AssertionError: If the create_input does not contain the appropriate service options for the specified service_type.
        """
        assert (
            getattr(
                create_input.options, f"{service_type.lower()}_service_options", None
            )
            is not None
        ), (
            f"Service options for {service_type} service must be provided in the create input"
        )
        response = await self._post(
            f"/arcgis_services/{service_type}/",
            json=create_input.model_dump(mode="json"),
        )
        return response.json()

    async def list_arcgis_services(
        self,
        service_type: Literal["Feature", "Image"],
        params: ListParams | None = None,
        **kwargs,
    ) -> list[dict]:
        """List ArcGIS services of a specific type with optional filtering.

        Args:
            service_type: The type of services to list, either "Feature" or "Image".
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters.

        Returns:
            list[dict]: A list of ArcGIS service objects matching the filter criteria.
        """
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get(
            f"/arcgis_services/{service_type}/", params=params_dict
        )
        return response.json()

    async def get_arcgis_service(
        self, service_type: Literal["Feature", "Image"], service_id: int
    ) -> dict:
        """Retrieve a specific ArcGIS service by its ID.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to retrieve.

        Returns:
            dict: The ArcGIS service object with its details.
        """
        response = await self._get(f"/arcgis_services/{service_type}/{service_id}")
        return response.json()

    async def delete_arcgis_service(
        self, service_type: Literal["Feature", "Image"], service_id: int
    ) -> dict:
        """Delete a specific ArcGIS service by its ID.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(f"/arcgis_services/{service_type}/{service_id}")
        return response.json()

    async def update_arcgis_service(
        self,
        service_type: Literal["Feature", "Image"],
        service_id: int,
        update_input: ArcgisServiceUpdateInput,
    ) -> dict:
        """Update an existing ArcGIS service with new values.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to update.
            update_input: ArcgisServiceUpdateInput object containing the fields to update.

        Returns:
            dict: The updated ArcGIS service object.
        """
        response = await self._put(
            f"/arcgis_services/{service_type}/{service_id}",
            json=update_input.model_dump(mode="json"),
        )
        return response.json()

    async def start_arcgis_service(
        self,
        service_type: Literal["Feature", "Image"],
        service_id: int,
        wait: bool = True,
    ) -> dict:
        """Start a specific ArcGIS service.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to start.
            wait: If True, wait for the start operation to complete before returning.
                 If False, return immediately after initiating the start operation.

        Returns:
            dict: A response object containing job information and, if wait is True,
                 the updated service object after starting.
        """
        response = await self._put(
            f"/arcgis_services/{service_type}/{service_id}/start"
        )
        resp = response.json()
        job = resp["job"]
        if wait and job:
            job = await self.wait_for_job(job["job_id"], timeout=1000)
            resp["job"] = job
            resp["arcgis_service"] = await self.get_arcgis_service(
                service_type, service_id
            )
        return resp

    async def stop_arcgis_service(
        self,
        service_type: Literal["Feature", "Image"],
        service_id: int,
        wait: bool = True,
    ) -> dict:
        """Stop a specific ArcGIS service.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to stop.
            wait: If True, wait for the stop operation to complete before returning.
                 If False, return immediately after initiating the stop operation.

        Returns:
            dict: A response object containing job information and, if wait is True,
                 the updated service object after stopping.
        """
        response = await self._put(f"/arcgis_services/{service_type}/{service_id}/stop")
        resp = response.json()
        job = resp["job"]
        if wait and job:
            job = await self.wait_for_job(job["job_id"], timeout=1000)
            resp["job"] = job
            resp["arcgis_service"] = await self.get_arcgis_service(
                service_type, service_id
            )
        return resp

    async def refresh_arcgis_service(
        self,
        service_type: Literal["Feature", "Image"],
        service_id: int,
        refresh_data: bool = False,
        wait: bool = True,
    ) -> dict:
        """Refresh a specific ArcGIS service, optionally refreshing its data.

        Args:
            service_type: The type of service, either "Feature" or "Image".
            service_id: The ID of the service to refresh.
            refresh_data: If True, also refresh the data used by the service.
            wait: If True, wait for the refresh operation to complete before returning.
                 If False, return immediately after initiating the refresh operation.

        Returns:
            dict: A response object containing job information and, if wait is True,
                 the updated service object after refreshing.
        """
        response = await self._put(
            f"/arcgis_services/{service_type}/{service_id}/refresh",
            params={"refresh_data": refresh_data},
        )
        resp = response.json()
        job = resp["job"]
        if wait and job:
            job = await self.wait_for_job(job["job_id"], timeout=1000)
            resp["job"] = job
            resp["arcgis_service"] = await self.get_arcgis_service(
                service_type, service_id
            )
        return resp

    async def create_harvest_service(
        self,
        project_id: int,
        data_collection_id: int,
        create_input: HarvestServiceCreateInput,
    ) -> dict:
        """Create a new harvest service for a data collection.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to create the harvest service for.
            create_input: HarvestServiceCreateInput object containing the service configuration.

        Returns:
            dict: The created harvest service object.
        """
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
            json=create_input.model_dump(mode="json"),
            sensitive_content=True,
        )
        return response.json()

    async def list_harvest_services(
        self,
        project_id: int,
        data_collection_id: int,
        params: ListParams | None = None,
        **kwargs,
    ) -> list[dict]:
        """List harvest services for a data collection with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection to list harvest services for.
            params: Optional ListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of harvest service objects matching the filter criteria.
        """
        if params and kwargs:
            logger.warning("Ignoring kwargs when params is provided")
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
            params=params_dict,
        )
        return response.json()

    async def get_harvest_service(
        self, project_id: int, data_collection_id: int, service_id: int
    ) -> dict:
        """Retrieve a specific harvest service by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to retrieve.

        Returns:
            dict: The harvest service object with its details.
        """
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
        )
        return response.json()

    async def update_harvest_service(
        self,
        project_id: int,
        data_collection_id: int,
        service_id: int,
        update_input: HarvestServiceUpdateInput,
    ) -> dict:
        """Update an existing harvest service with new values.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to update.
            update_input: HarvestServiceUpdateInput object containing the fields to update.

        Returns:
            dict: The updated harvest service object.
        """
        response = await self._put(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}",
            json=update_input.model_dump(mode="json", exclude_none=True),
            sensitive_content=True,
        )
        return response.json()

    async def delete_harvest_service(
        self, project_id: int, data_collection_id: int, service_id: int
    ) -> dict:
        """Delete a specific harvest service by its ID.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to delete.

        Returns:
            dict: The response confirming deletion.
        """
        response = await self._delete(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
        )
        return response.json()

    async def get_harvest_service_tasks(
        self,
        project_id: int,
        data_collection_id: int,
        service_id: int,
        params: HarvestTaskListParams,
        **kwargs,
    ) -> list[dict]:
        """Retrieve tasks for a specific harvest service with optional filtering.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to retrieve tasks for.
            params: HarvestTaskListParams object containing filtering parameters.
            **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

        Returns:
            list[dict]: A list of harvest task objects matching the filter criteria.
        """
        params_dict = (
            params.model_dump(exclude_none=True)
            if params
            else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
        )
        response = await self._get(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/",
            params=params_dict,
        )
        return response.json()

    async def start_harvest_service(
        self, project_id: int, data_collection_id: int, service_id: int
    ) -> dict:
        """Start a specific harvest service.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to start.

        Returns:
            dict: The response confirming the service has been started.
        """
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/start"
        )
        return response.json()

    async def stop_harvest_service(
        self, project_id: int, data_collection_id: int, service_id: int
    ) -> dict:
        """Stop a specific harvest service.

        Args:
            project_id: The ID of the project containing the data collection.
            data_collection_id: The ID of the data collection containing the harvest service.
            service_id: The ID of the harvest service to stop.

        Returns:
            dict: The response confirming the service has been stopped.
        """
        response = await self._post(
            f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/stop"
        )
        return response.json()

    async def create_oidc_user(self, create_input: OIDCUserCreateInput) -> dict:
        """Create a new OIDC user in the system.

        Args:
            create_input: OIDCUserCreateInput object containing the user information.

        Returns:
            dict: The created user object.

        Note:
            This method handles the extraction of the password from the SecretStr field
            in the create_input object.
        """
        model_dump = create_input.model_dump(mode="json")
        response = await self._post(
            "/users/oidc/", json=model_dump, sensitive_content=True
        )
        return response.json()

    async def update_oidc_user(
        self, user_id: int, update_input: OIDCUserUpdateInput
    ) -> dict:
        """Update an existing OIDC user with new values.

        Args:
            user_id: The ID of the user to update.
            update_input: OIDCUserUpdateInput object containing the fields to update.

        Returns:
            dict: The updated user object.

        Note:
            This method handles the extraction of the password from the SecretStr field
            in the update_input object if provided.
        """
        model_dump = update_input.model_dump(mode="json")
        response = await self._put(
            f"/users/oidc/{user_id}/", json=model_dump, sensitive_content=True
        )
        return response.json()

    async def _upload_attachment_to_s3(
        self,
        resource_type: AttachmentResourceType,
        resource_id: int,
        attachment: dict,
        file_path: Path,
    ) -> dict:
        """Upload an attachment file to S3 and mark it as completed.

        Args:
            resource_type: The type of resource the attachment belongs to.
            resource_id: The ID of the resource the attachment belongs to.
            attachment: The attachment object containing upload parameters.
            file_path: Path to the attachment file to upload.

        Returns:
            dict: The updated attachment object.

        Raises:
            AssertionError: If the attachment status is not "Pending".
            httpx.HTTPStatusError: If the upload fails.
        """
        assert attachment["status"] == "Pending", "Attachment status must be pending"
        response = await self._internal_client.post(
            attachment["upload_file_params"]["url"],
            files={"file": file_path.read_bytes()},
            data=attachment["upload_file_params"]["fields"],
        )
        response.raise_for_status()
        # Update the status to completed
        resp = await self._put(
            "/attachments/update",
            params={
                "resource_type": resource_type,
                "resource_id": resource_id,
                "attachment_id": attachment["id"],
                "status": "Completed",
            },
        )
        return resp.json()

    async def list_attachments(
        self,
        resource_type: AttachmentResourceType,
        resource_id: int,
        status: Literal["Pending", "Completed"] | None = None,
    ) -> list[dict]:
        """List attachments for a specific resource with optional status filtering.

        Args:
            resource_type: The type of resource the attachments belong to.
            resource_id: The ID of the resource to list attachments for.
            status: Optional filter for attachment status, either "Pending" or "Completed".

        Returns:
            list[dict]: A list of attachment objects matching the filter criteria.
        """
        params = {"resource_type": resource_type, "resource_id": resource_id}
        if status:
            params["status"] = status
        response = await self._get(
            "/attachments/",
            params=params,
        )
        return response.json()

    async def add_attachments(
        self,
        resource_type: AttachmentResourceType,
        resource_id: int,
        files: list[PixelAttachmentUpload | Path]
        | list[Path]
        | list[PixelAttachmentUpload],
    ) -> list[dict]:
        """Add one or more file attachments to a resource.

        Args:
            resource_type: The type of resource to attach files to.
            resource_id: The ID of the resource to attach files to.
            files: List of files to attach, which can be Path objects or PixelAttachmentUpload objects.

        Returns:
            list[dict]: A list of the created attachment objects.

        Raises:
            AssertionError: If any attachment names are not unique.
        """
        pixel_attachments = [
            PixelAttachmentUpload(
                file=f,
            )
            if isinstance(f, Path)
            else f
            for f in files
        ]
        assert len(set(pa.name for pa in pixel_attachments)) == len(
            pixel_attachments
        ), "Attachment names must be unique"
        response = await self._post(
            "/attachments/",
            params={"resource_type": resource_type, "resource_id": resource_id},
            json={"files": [pa.model_dump(mode="json") for pa in pixel_attachments]},
        )
        attachments = response.json()
        sorted_attachments = sorted(attachments, key=lambda a: a["name"])
        sorted_files = sorted(pixel_attachments, key=lambda f: f.name)
        attachments = await asyncio.gather(
            *[
                self._upload_attachment_to_s3(resource_type, resource_id, a, pa.file)
                for a, pa in zip(sorted_attachments, sorted_files)
            ]
        )
        return attachments

    async def move_attachment(
        self,
        resource_type: AttachmentResourceType,
        resource_id: int,
        attachment_id: int,
        new_resource_type: AttachmentResourceType,
        new_resource_id: int,
    ) -> dict:
        """Move an attachment from one resource to another.

        Args:
            resource_type: The current resource type of the attachment.
            resource_id: The current resource ID the attachment belongs to.
            attachment_id: The ID of the attachment to move.
            new_resource_type: The target resource type to move the attachment to.
            new_resource_id: The target resource ID to move the attachment to.

        Returns:
            dict: The updated attachment object.
        """
        resp = await self._put(
            "/attachments/move",
            params={
                "resource_type": resource_type,
                "resource_id": resource_id,
                "attachment_id": attachment_id,
                "new_resource_type": new_resource_type,
                "new_resource_id": new_resource_id,
            },
        )
        return resp.json()

    async def delete_attachment(
        self,
        resource_type: AttachmentResourceType,
        resource_id: int,
        attachment_id: int,
    ) -> dict:
        """Delete a specific attachment from a resource.

        Args:
            resource_type: The resource type the attachment belongs to.
            resource_id: The resource ID the attachment belongs to.
            attachment_id: The ID of the attachment to delete.

        Returns:
            dict: The response confirming deletion.
        """
        resp = await self._delete(
            "/attachments/",
            params={
                "resource_type": resource_type,
                "resource_id": resource_id,
                "attachment_id": attachment_id,
            },
        )
        return resp.json()

    async def search_info(self, on: SearchOn):
        """
        Retrieve search metadata for a specific resource type.

        Args:
            on: The resource type to retrieve search metadata for.
        Returns:
            dict: A dictionary containing output fields, filterable fields and search capabilities.
        """
        response = await self._get(
            "/search/info",
            params={"on": on},
        )
        return response.json()

    async def search(
        self,
        search_query: dict | SearchQuery,
    ) -> SearchResults:
        """
        Perform a search across various resources.

        Args:
            search_query: SearchQuery object or dict containing the search parameters.
        Returns:
            SearchResults: The search results dictionary.
        """
        search_model = (
            SearchQuery.model_validate(search_query)
            if isinstance(search_query, dict)
            else search_query
        )
        response = await self._post(
            "/search/",
            json=search_model.model_dump(mode="json", exclude_none=True),
        )
        return response.json()

    async def paginate_search(
        self, search_query: dict | SearchQuery, page_size: int
    ) -> AsyncGenerator[dict, None]:
        """
        Perform a paginated search across various resources.

        Args:
            search_query: SearchQuery object or dict containing the search parameters.
            page_size: Number of results to retrieve per page.

        Yields:
            dict: Individual search result items.
        """
        search_model = (
            SearchQuery.model_validate(search_query)
            if isinstance(search_query, dict)
            else search_query
        )
        search_query_body = search_model.model_dump(mode="json", exclude_none=True)
        async for item in self._paginate(
            "/search/",
            method="POST",
            page_size=page_size,
            use_body=True,
            # The return of the search endpoint is in the "results" field
            results_parser=lambda resp: resp.get("results", []),
            json=search_query_body,
        ):
            yield item

url instance-attribute

url: str = url

auth instance-attribute

auth = KeyCloakAuth(
    keycloak_server_url,
    realm,
    client_id,
    username,
    password,
)

pixel_client instance-attribute

pixel_client = httpx.AsyncClient(
    base_url=self.url,
    auth=self.auth,
    timeout=self._timeout_pixel,
)

__init__

__init__(
    url: str,
    keycloak_server_url: str,
    realm: str,
    client_id: str,
    username: str,
    password: str,
    timeout_pixel: httpx.Timeout = DEFAULT_PIXEL_TIMEOUT,
    timeout_upload: httpx.Timeout = DEFAULT_UPLOAD_TIMEOUT,
    upload_num_retries: int = DEFAULT_UPLOAD_RETRIES,
    upload_max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
)

Parameters:

Name Type Description Default
url str

Base URL of the Pixel API.

required
keycloak_server_url str

URL of the Keycloak authentication server.

required
realm str

Keycloak realm name.

required
client_id str

Keycloak client ID.

required
username str

Username for authentication.

required
password str

Password for authentication.

required
timeout_pixel httpx.Timeout

Optional timeout configuration for Pixel API requests.

DEFAULT_PIXEL_TIMEOUT
timeout_upload httpx.Timeout

Optional timeout configuration for file uploads. If not provided, defaults to the same as timeout_pixel.

DEFAULT_UPLOAD_TIMEOUT
Source code in src/pixel_client/_base.py
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
def __init__(
    self,
    url: str,
    keycloak_server_url: str,
    realm: str,
    client_id: str,
    username: str,
    password: str,
    timeout_pixel: httpx.Timeout = DEFAULT_PIXEL_TIMEOUT,
    timeout_upload: httpx.Timeout = DEFAULT_UPLOAD_TIMEOUT,
    upload_num_retries: int = DEFAULT_UPLOAD_RETRIES,
    upload_max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
):
    """Initialize a new Pixel API client.

    Args:
        url: Base URL of the Pixel API.
        keycloak_server_url: URL of the Keycloak authentication server.
        realm: Keycloak realm name.
        client_id: Keycloak client ID.
        username: Username for authentication.
        password: Password for authentication.
        timeout_pixel: Optional timeout configuration for Pixel API requests.
        timeout_upload: Optional timeout configuration for file uploads. If not provided, defaults to the same as `timeout_pixel`.
    """
    self.url: str = url
    self._timeout_pixel = timeout_pixel
    self._timeout_upload = timeout_upload
    self.auth = KeyCloakAuth(
        keycloak_server_url, realm, client_id, username, password
    )
    self.pixel_client = httpx.AsyncClient(
        base_url=self.url, auth=self.auth, timeout=self._timeout_pixel
    )
    self._internal_client = httpx.AsyncClient(
        timeout=self._timeout_upload,  # Use a separate client for uploads
    )  # For s3 uploads
    self._semaphore: asyncio.Semaphore = asyncio.Semaphore(upload_max_concurrency)

    self._retry_policy = tenacity.AsyncRetrying(
        stop=tenacity.stop_after_attempt(upload_num_retries),
        wait=tenacity.wait_random_exponential(),
        before=tenacity.before_log(logger, logging.DEBUG),
        after=tenacity.after_log(logger, logging.DEBUG),
    )
    self._internal_client.request = self._retry_policy.wraps(
        self._internal_client.request
    )

from_settings classmethod

from_settings(
    settings: PixelApiSettings,
    **kwargs: Unpack[PixelClientKwargs],
) -> Self

Instantiate the client from settings.

Parameters:

Name Type Description Default
settings PixelApiSettings

PixelApiSettings object containing API configuration.

required
**kwargs Unpack[PixelClientKwargs]

Additional keyword arguments to pass to the client constructor.

{}

Returns:

Name Type Description
PixelClientAsync Self

A new client instance configured with the provided settings.

Source code in src/pixel_client/_base.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
@classmethod
def from_settings(
    cls, settings: PixelApiSettings, **kwargs: Unpack[PixelClientKwargs]
) -> Self:
    """Instantiate the client from settings.

    Args:
        settings: PixelApiSettings object containing API configuration.
        **kwargs: Additional keyword arguments to pass to the client constructor.

    Returns:
        PixelClientAsync: A new client instance configured with the provided settings.
    """
    return cls(
        url=settings.PIXEL_API_URL,
        keycloak_server_url=settings.PIXEL_SERVER_URL,
        client_id=settings.PIXEL_CLIENT_ID,
        username=settings.PIXEL_USERNAME,
        password=settings.PIXEL_PASSWORD.get_secret_value(),
        realm=settings.PIXEL_REALM,
        **kwargs,
    )

me async

me(extended: bool = False) -> dict

Get information about the authenticated user.

Parameters:

Name Type Description Default
extended bool

If True, returns extended user information including projects user is a member of

False

Returns:

Name Type Description
dict dict

User information including username, email, and other profile details.

Source code in src/pixel_client/_base.py
315
316
317
318
319
320
321
322
323
324
325
async def me(self, extended: bool = False) -> dict:
    """Get information about the authenticated user.

    Args:
        extended: If True, returns extended user information including projects user is a member of

    Returns:
        dict: User information including username, email, and other profile details.
    """
    response = await self._get("/users/me", params={"extended": extended})
    return response.json()

get_plugins async

get_plugins() -> list[dict]

Retrieve a list of available plugins for the pixel tenant. Possible plugins include: * 'optimized_raster' - Optimize Raster capability * 'image_service' - Image Service capability, dependent on the 'optimize_raster' plugin.

Returns:

Type Description
list[dict]

list[dict]: A list of plugin objects with their details.

Source code in src/pixel_client/_base.py
327
328
329
330
331
332
333
334
335
336
337
async def get_plugins(self) -> list[dict]:
    """Retrieve a list of available plugins for the pixel tenant.
    Possible plugins include:
    * 'optimized_raster' - Optimize Raster capability
    * 'image_service' - Image Service capability, dependent on the 'optimize_raster' plugin.

    Returns:
        list[dict]: A list of plugin objects with their details.
    """
    response = await self._get("/plugins/")
    return response.json()

create_project async

create_project(
    name: str,
    description: str,
    area_of_interest: Polygon,
    parent_project_id: int | None = None,
    tags: list[str] | None = None,
) -> dict

Create a new project in the Pixel system.

Parameters:

Name Type Description Default
name str

The name of the project.

required
description str

A description of the project.

required
area_of_interest Polygon

A GeoJSON polygon defining the project's geographic area of interest.

required
parent_project_id int | None

Optional ID of a parent project. If provided, this project will be created as a child of that project.

None
tags list[str] | None

Optional list of tags to associate with the project.

None

Returns:

Name Type Description
dict dict

The created project object.

Source code in src/pixel_client/_base.py
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
async def create_project(
    self,
    name: str,
    description: str,
    area_of_interest: Polygon,
    parent_project_id: int | None = None,
    tags: list[str] | None = None,
) -> dict:
    """Create a new project in the Pixel system.

    Args:
        name: The name of the project.
        description: A description of the project.
        area_of_interest: A GeoJSON polygon defining the project's geographic area of interest.
        parent_project_id: Optional ID of a parent project. If provided, this project will be created as a child of that project.
        tags: Optional list of tags to associate with the project.

    Returns:
        dict: The created project object.
    """
    body = {
        "name": name,
        "description": description,
        "area_of_interest": area_of_interest.__geo_interface__,
    }
    if parent_project_id:
        body["parent_project_id"] = parent_project_id
    if tags:
        body["tags"] = tags
    response = await self._post("/projects/", json=body)
    return response.json()

list_projects async

list_projects(
    params: ListParams | None = None, **kwargs
) -> list[dict]

List projects with optional filtering.

Parameters:

Name Type Description Default
params ListParams | None

Optional ListParams object containing filtering parameters such as offset, limit, search, etc.

None
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of project objects matching the filter criteria.

Source code in src/pixel_client/_base.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
async def list_projects(
    self, params: ListParams | None = None, **kwargs
) -> list[dict]:
    """List projects with optional filtering.

    Args:
        params: Optional ListParams object containing filtering parameters such as offset, limit, search, etc.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of project objects matching the filter criteria.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get("/projects/", params=params_dict)
    return response.json()

list_deleted_projects async

list_deleted_projects(
    params: ListParams | None = None, **kwargs
) -> list[dict]

List deleted projects in the Pixel system.

Parameters:

Name Type Description Default
params ListParams | None

Optional ListParams object containing filtering parameters such as offset, limit, search, etc.

None
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of deleted project objects.

Source code in src/pixel_client/_base.py
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
async def list_deleted_projects(
    self, params: ListParams | None = None, **kwargs
) -> list[dict]:
    """List deleted projects in the Pixel system.

    Args:
        params: Optional ListParams object containing filtering parameters such as offset, limit, search, etc.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of deleted project objects.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get("/projects/deleted", params=params_dict)
    return response.json()

get_project async

get_project(
    project_id: int, extended: bool = False
) -> dict

Retrieve a project by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project to retrieve.

required
extended bool

If True, returns extended project information including child projects and data collections.

False

Returns:

Name Type Description
dict dict

The project object with its details.

Source code in src/pixel_client/_base.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
async def get_project(self, project_id: int, extended: bool = False) -> dict:
    """Retrieve a project by its ID.

    Args:
        project_id: The ID of the project to retrieve.
        extended: If True, returns extended project information including child projects and data collections.

    Returns:
        dict: The project object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}", params={"extended": extended}
    )
    return response.json()

update_project async

update_project(
    project_id: int,
    name: str | None = None,
    description: str | None = None,
    area_of_interest: Polygon | None = None,
    add_tags: list[str] | None = None,
    remove_tags: list[str] | None = None,
) -> dict

Update an existing project with new values.

Parameters:

Name Type Description Default
project_id int

The ID of the project to update.

required
name str | None

Optional new name for the project.

None
description str | None

Optional new description for the project.

None
area_of_interest Polygon | None

Optional new GeoJSON polygon defining the project's geographic area of interest.

None
add_tags list[str] | None

Optional list of tags to add to the project.

None
remove_tags list[str] | None

Optional list of tags to remove from the project.

None

Returns:

Name Type Description
dict dict

The updated project object.

Raises:

Type Description
ValueError

If no update parameters are provided.

Source code in src/pixel_client/_base.py
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
async def update_project(
    self,
    project_id: int,
    name: str | None = None,
    description: str | None = None,
    area_of_interest: Polygon | None = None,
    add_tags: list[str] | None = None,
    remove_tags: list[str] | None = None,
) -> dict:
    """Update an existing project with new values.

    Args:
        project_id: The ID of the project to update.
        name: Optional new name for the project.
        description: Optional new description for the project.
        area_of_interest: Optional new GeoJSON polygon defining the project's geographic area of interest.
        add_tags: Optional list of tags to add to the project.
        remove_tags: Optional list of tags to remove from the project.

    Returns:
        dict: The updated project object.

    Raises:
        ValueError: If no update parameters are provided.
    """
    body = {}
    for param_name, value in {
        "name": name,
        "description": description,
        "area_of_interest": area_of_interest.__geo_interface__
        if area_of_interest
        else None,
        "add_tags": add_tags,
        "remove_tags": remove_tags,
    }.items():
        if value is not None:
            body[param_name] = value
    if not body:
        raise ValueError("No update parameters provided")
    response = await self._put(f"/projects/{project_id}", json=body)
    return response.json()

delete_project async

delete_project(project_id: int) -> dict

Delete a project by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
472
473
474
475
476
477
478
479
480
481
482
async def delete_project(self, project_id: int) -> dict:
    """Delete a project by its ID.

    Args:
        project_id: The ID of the project to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(f"/projects/{project_id}")
    return response.json()

restore_project async

restore_project(project_id: int) -> dict

Restore a deleted project by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project to restore.

required

Returns:

Name Type Description
dict dict

The restored project object.

Source code in src/pixel_client/_base.py
484
485
486
487
488
489
490
491
492
493
494
async def restore_project(self, project_id: int) -> dict:
    """Restore a deleted project by its ID.

    Args:
        project_id: The ID of the project to restore.

    Returns:
        dict: The restored project object.
    """
    response = await self._post(f"/projects/{project_id}/restore")
    return response.json()

move_project async

move_project(
    project_id: int,
    new_parent_project_id: int | None = None,
) -> dict

Move a project to a new parent project or to the root level.

Parameters:

Name Type Description Default
project_id int

The ID of the project to move.

required
new_parent_project_id int | None

Optional ID of the new parent project. If None, the project will be moved to the root level.

None

Returns:

Name Type Description
dict dict

The updated project object.

Source code in src/pixel_client/_base.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
async def move_project(
    self, project_id: int, new_parent_project_id: int | None = None
) -> dict:
    """Move a project to a new parent project or to the root level.

    Args:
        project_id: The ID of the project to move.
        new_parent_project_id: Optional ID of the new parent project. If None, the project will be moved to the root level.

    Returns:
        dict: The updated project object.
    """
    # If None is provided, set to -1 to move to root
    new_parent_project_id = new_parent_project_id or -1
    response = await self._put(
        f"/projects/{project_id}",
        params={"new_parent_id": new_parent_project_id},
    )
    return response.json()

create_data_collection async

create_data_collection(
    project_id: int,
    name: str,
    description: str,
    data_collection_type: DataCollectionType,
    tags: list[str] | None = None,
    raster_info: RasterInfo | None = None,
) -> dict

Create a new data collection within a project.

Parameters:

Name Type Description Default
project_id int

The ID of the project to create the data collection in.

required
name str

The name of the data collection.

required
description str

A description of the data collection.

required
data_collection_type DataCollectionType

The type of data collection (e.g., "image", "raster", "RGB", "DTM", "DSM").

required
tags list[str] | None

Optional list of tags to associate with the data collection.

None
raster_info RasterInfo | None

Optional RasterInfo object containing raster-specific configuration.

None

Returns:

Name Type Description
dict dict

The created data collection object.

Source code in src/pixel_client/_base.py
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
async def create_data_collection(
    self,
    project_id: int,
    name: str,
    description: str,
    data_collection_type: DataCollectionType,
    tags: list[str] | None = None,
    raster_info: RasterInfo | None = None,
) -> dict:
    """Create a new data collection within a project.

    Args:
        project_id: The ID of the project to create the data collection in.
        name: The name of the data collection.
        description: A description of the data collection.
        data_collection_type: The type of data collection (e.g., "image", "raster", "RGB", "DTM", "DSM").
        tags: Optional list of tags to associate with the data collection.
        raster_info: Optional RasterInfo object containing raster-specific configuration.

    Returns:
        dict: The created data collection object.
    """
    body: dict[str, Any] = {
        "name": name,
        "description": description,
        "data_collection_type": data_collection_type,
    }
    if tags:
        body["tags"] = tags
    if raster_info:
        body["raster_info"] = raster_info.model_dump(exclude_none=True, mode="json")
    response = await self._post(
        f"/projects/{project_id}/data_collections/", json=body
    )
    return response.json()

list_data_collections async

list_data_collections(
    project_id: int,
    params: DataCollectionListParams | None = None,
    **kwargs,
) -> list[dict]

List data collections within a project with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project to list data collections from.

required
params DataCollectionListParams | None

Optional DataCollectionListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of data collection objects matching the filter criteria.

Source code in src/pixel_client/_base.py
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
async def list_data_collections(
    self, project_id: int, params: DataCollectionListParams | None = None, **kwargs
) -> list[dict]:
    """List data collections within a project with optional filtering.

    Args:
        project_id: The ID of the project to list data collections from.
        params: Optional DataCollectionListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of data collection objects matching the filter criteria.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else DataCollectionListParams.model_validate(kwargs).model_dump(
            exclude_none=True
        )
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/", params=params_dict
    )
    return response.json()

list_deleted_data_collections async

list_deleted_data_collections(
    project_id: int,
    params: DataCollectionListParams | None = None,
    **kwargs,
) -> list[dict]

List deleted data collections within a project.

Parameters:

Name Type Description Default
project_id int

The ID of the project to list deleted data collections from.

required

Returns:

Type Description
list[dict]

list[dict]: A list of deleted data collection objects.

Source code in src/pixel_client/_base.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
async def list_deleted_data_collections(
    self, project_id: int, params: DataCollectionListParams | None = None, **kwargs
) -> list[dict]:
    """List deleted data collections within a project.

    Args:
        project_id: The ID of the project to list deleted data collections from.

    Returns:
        list[dict]: A list of deleted data collection objects.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else DataCollectionListParams.model_validate(kwargs).model_dump(
            exclude_none=True
        )
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/deleted", params=params_dict
    )
    return response.json()

get_data_collection async

get_data_collection(
    project_id: int, data_collection_id: int
) -> dict

Retrieve a data collection by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to retrieve.

required

Returns:

Name Type Description
dict dict

The data collection object with its details.

Source code in src/pixel_client/_base.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
async def get_data_collection(
    self, project_id: int, data_collection_id: int
) -> dict:
    """Retrieve a data collection by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to retrieve.

    Returns:
        dict: The data collection object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}"
    )
    return response.json()

update_data_collection async

update_data_collection(
    project_id: int,
    data_collection_id: int,
    name: str | None = None,
    description: str | None = None,
    add_tags: list[str] | None = None,
    remove_tags: list[str] | None = None,
) -> dict

Update an existing data collection with new values.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to update.

required
name str | None

Optional new name for the data collection.

None
description str | None

Optional new description for the data collection.

None
add_tags list[str] | None

Optional list of tags to add to the data collection.

None
remove_tags list[str] | None

Optional list of tags to remove from the data collection.

None

Returns:

Name Type Description
dict dict

The updated data collection object.

Raises:

Type Description
ValueError

If no update parameters are provided.

Source code in src/pixel_client/_base.py
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
async def update_data_collection(
    self,
    project_id: int,
    data_collection_id: int,
    name: str | None = None,
    description: str | None = None,
    add_tags: list[str] | None = None,
    remove_tags: list[str] | None = None,
) -> dict:
    """Update an existing data collection with new values.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to update.
        name: Optional new name for the data collection.
        description: Optional new description for the data collection.
        add_tags: Optional list of tags to add to the data collection.
        remove_tags: Optional list of tags to remove from the data collection.

    Returns:
        dict: The updated data collection object.

    Raises:
        ValueError: If no update parameters are provided.
    """
    body = {}
    for param_name, value in {
        "name": name,
        "description": description,
        "add_tags": add_tags,
        "remove_tags": remove_tags,
    }.items():
        if value is not None:
            body[param_name] = value
    if not body:
        raise ValueError("No update parameters provided")
    response = await self._put(
        f"/projects/{project_id}/data_collections/{data_collection_id}", json=body
    )
    return response.json()

move_data_collection async

move_data_collection(
    project_id: int,
    data_collection_id: int,
    new_project_id: int,
) -> dict

Move a data collection to a different project.

Parameters:

Name Type Description Default
project_id int

The ID of the project currently containing the data collection.

required
data_collection_id int

The ID of the data collection to move.

required
new_project_id int

The ID of the project to move the data collection to.

required

Returns:

Name Type Description
dict dict

The updated data collection object.

Source code in src/pixel_client/_base.py
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
async def move_data_collection(
    self, project_id: int, data_collection_id: int, new_project_id: int
) -> dict:
    """Move a data collection to a different project.

    Args:
        project_id: The ID of the project currently containing the data collection.
        data_collection_id: The ID of the data collection to move.
        new_project_id: The ID of the project to move the data collection to.

    Returns:
        dict: The updated data collection object.
    """
    response = await self._put(
        f"/projects/{project_id}/data_collections/{data_collection_id}",
        params={"new_project_id": new_project_id},
    )
    return response.json()

delete_data_collection async

delete_data_collection(
    project_id: int, data_collection_id: int
) -> dict

Delete a data collection by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
async def delete_data_collection(
    self, project_id: int, data_collection_id: int
) -> dict:
    """Delete a data collection by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(
        f"/projects/{project_id}/data_collections/{data_collection_id}"
    )
    return response.json()

restore_data_collection async

restore_data_collection(
    project_id: int, data_collection_id: int
) -> dict

Restore a deleted data collection by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to restore.

required

Returns:

Name Type Description
dict dict

The restored data collection object.

Source code in src/pixel_client/_base.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
async def restore_data_collection(
    self, project_id: int, data_collection_id: int
) -> dict:
    """Restore a deleted data collection by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to restore.

    Returns:
        dict: The restored data collection object.
    """
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/restore"
    )
    return response.json()

get_images async

get_images(
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> dict

Retrieve images from a data collection with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the images.

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters.

{}

Returns:

Name Type Description
dict dict

A list of image objects matching the filter criteria.

Source code in src/pixel_client/_base.py
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
async def get_images(
    self,
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> dict:
    """Retrieve images from a data collection with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the images.
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters.

    Returns:
        dict: A list of image objects matching the filter criteria.
    """
    params_dict = params.model_dump(exclude_none=True) if params else {}
    params_dict.update(kwargs)
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/images/",
        params=params_dict,
    )
    return response.json()

paginate_images async

paginate_images(
    project_id: int,
    data_collection_id: int,
    page_size: int,
    params: ListParams | None = None,
    **kwargs,
) -> AsyncGenerator[dict, None]

Paginate through images in a data collection with optional filtering.

This method returns an async generator that yields images one at a time, automatically handling pagination in the background.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the images.

required
page_size int

The number of images to fetch per page.

required
params ListParams | None

Optional ListParams object containing filtering parameters (excluding offset and limit).

None
**kwargs

Alternative way to provide filtering parameters.

{}

Yields:

Name Type Description
dict AsyncGenerator[dict, None]

Image objects matching the filter criteria, one at a time.

Source code in src/pixel_client/_base.py
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
async def paginate_images(
    self,
    project_id: int,
    data_collection_id: int,
    page_size: int,
    params: ListParams | None = None,
    **kwargs,
) -> AsyncGenerator[dict, None]:
    """Paginate through images in a data collection with optional filtering.

    This method returns an async generator that yields images one at a time,
    automatically handling pagination in the background.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the images.
        page_size: The number of images to fetch per page.
        params: Optional ListParams object containing filtering parameters (excluding offset and limit).
        **kwargs: Alternative way to provide filtering parameters.

    Yields:
        dict: Image objects matching the filter criteria, one at a time.
    """
    params_dict = (
        params.model_dump(exclude_none=True, exclude={"offset", "limit"})
        if params
        else {}
    )
    params_dict.update(kwargs)
    url = f"/projects/{project_id}/data_collections/{data_collection_id}/images/"
    async for item in self._paginate(url, page_size, params=params_dict):
        yield item

get_image async

get_image(
    project_id: int, data_collection_id: int, image_id: int
) -> dict

Retrieve a specific image by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the image.

required
image_id int

The ID of the image to retrieve.

required

Returns:

Name Type Description
dict dict

The image object with its details.

Source code in src/pixel_client/_base.py
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
async def get_image(
    self,
    project_id: int,
    data_collection_id: int,
    image_id: int,
) -> dict:
    """Retrieve a specific image by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the image.
        image_id: The ID of the image to retrieve.

    Returns:
        dict: The image object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
    )
    return response.json()

get_image_metadata async

get_image_metadata(
    project_id: int, data_collection_id: int, image_id: int
) -> dict

Retrieve metadata for a specific image by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the image.

required
image_id int

The ID of the image to retrieve metadata for.

required

Returns:

Name Type Description
dict dict

The image metadata object with its details.

Source code in src/pixel_client/_base.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
async def get_image_metadata(
    self, project_id: int, data_collection_id: int, image_id: int
) -> dict:
    """
    Retrieve metadata for a specific image by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the image.
        image_id: The ID of the image to retrieve metadata for.

    Returns:
        dict: The image metadata object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}/metadata"
    )
    return response.json()

update_image async

update_image(
    project_id: int,
    data_collection_id: int,
    image_id: int,
    update_input: ImageUpdateInput,
) -> dict

Update an existing image with new values.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the image.

required
image_id int

The ID of the image to update.

required
update_input ImageUpdateInput

ImageUpdateInput object containing the fields to update.

required

Returns:

Name Type Description
dict dict

The updated image object.

Source code in src/pixel_client/_base.py
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
async def update_image(
    self,
    project_id: int,
    data_collection_id: int,
    image_id: int,
    update_input: ImageUpdateInput,
) -> dict:
    """Update an existing image with new values.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the image.
        image_id: The ID of the image to update.
        update_input: ImageUpdateInput object containing the fields to update.

    Returns:
        dict: The updated image object.
    """

    response = await self._put(
        f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}",
        json=update_input.model_dump(mode="json", exclude_none=True),
    )
    return response.json()

delete_image async

delete_image(
    project_id: int, data_collection_id: int, image_id: int
) -> dict

Delete a specific image by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the image.

required
image_id int

The ID of the image to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
async def delete_image(
    self,
    project_id: int,
    data_collection_id: int,
    image_id: int,
) -> dict:
    """Delete a specific image by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the image.
        image_id: The ID of the image to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(
        f"/projects/{project_id}/data_collections/{data_collection_id}/images/{image_id}"
    )
    return response.json()

get_rasters async

get_rasters(
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> dict

Retrieve rasters from a data collection with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the rasters.

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters.

{}

Returns:

Name Type Description
dict dict

A list of raster objects matching the filter criteria.

Source code in src/pixel_client/_base.py
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
async def get_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> dict:
    """Retrieve rasters from a data collection with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the rasters.
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters.

    Returns:
        dict: A list of raster objects matching the filter criteria.
    """
    params_dict = params.model_dump(exclude_none=True) if params else {}
    params_dict.update(kwargs)
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/",
        params=params_dict,
    )
    return response.json()

paginate_rasters async

paginate_rasters(
    project_id: int,
    data_collection_id: int,
    page_size: int,
    params: ListParams | None = None,
    **kwargs,
) -> AsyncGenerator[dict, None]

Paginate through rasters in a data collection with optional filtering.

This method returns an async generator that yields rasters one at a time, automatically handling pagination in the background.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the rasters.

required
page_size int

The number of rasters to fetch per page.

required
params ListParams | None

Optional ListParams object containing filtering parameters (excluding offset and limit).

None
**kwargs

Alternative way to provide filtering parameters.

{}

Yields:

Name Type Description
dict AsyncGenerator[dict, None]

Raster objects matching the filter criteria, one at a time.

Source code in src/pixel_client/_base.py
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
async def paginate_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    page_size: int,
    params: ListParams | None = None,
    **kwargs,
) -> AsyncGenerator[dict, None]:
    """Paginate through rasters in a data collection with optional filtering.

    This method returns an async generator that yields rasters one at a time,
    automatically handling pagination in the background.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the rasters.
        page_size: The number of rasters to fetch per page.
        params: Optional ListParams object containing filtering parameters (excluding offset and limit).
        **kwargs: Alternative way to provide filtering parameters.

    Yields:
        dict: Raster objects matching the filter criteria, one at a time.
    """
    params_dict = (
        params.model_dump(exclude_none=True, exclude={"offset", "limit"})
        if params
        else {}
    )
    params_dict.update(kwargs)
    url = f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/"
    async for item in self._paginate(url, page_size, params=params_dict):
        yield item

get_raster async

get_raster(
    project_id: int, data_collection_id: int, raster_id: int
) -> dict

Retrieve a specific raster by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the raster.

required
raster_id int

The ID of the raster to retrieve.

required

Returns:

Name Type Description
dict dict

The raster object with its details.

Source code in src/pixel_client/_base.py
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
async def get_raster(
    self,
    project_id: int,
    data_collection_id: int,
    raster_id: int,
) -> dict:
    """Retrieve a specific raster by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the raster.
        raster_id: The ID of the raster to retrieve.

    Returns:
        dict: The raster object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
    )
    return response.json()

update_raster async

update_raster(
    project_id: int,
    data_collection_id: int,
    raster_id: int,
    update_input: RasterUpdateInput,
) -> dict

Update an existing raster with new values.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the raster.

required
raster_id int

The ID of the raster to update.

required
update_input RasterUpdateInput

RasterUpdateInput object containing the fields to update.

required

Returns:

Name Type Description
dict dict

The updated raster object.

Source code in src/pixel_client/_base.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
async def update_raster(
    self,
    project_id: int,
    data_collection_id: int,
    raster_id: int,
    update_input: RasterUpdateInput,
) -> dict:
    """Update an existing raster with new values.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the raster.
        raster_id: The ID of the raster to update.
        update_input: RasterUpdateInput object containing the fields to update.

    Returns:
        dict: The updated raster object.

    """
    response = await self._put(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}",
        json=update_input.model_dump(mode="json", exclude_none=True),
    )
    return response.json()

delete_raster async

delete_raster(
    project_id: int, data_collection_id: int, raster_id: int
) -> dict

Delete a specific raster by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the raster.

required
raster_id int

The ID of the raster to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
async def delete_raster(
    self,
    project_id: int,
    data_collection_id: int,
    raster_id: int,
) -> dict:
    """Delete a specific raster by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the raster.
        raster_id: The ID of the raster to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}"
    )
    return response.json()

get_upload_jobs async

get_upload_jobs(
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]

Retrieve upload jobs for a data collection with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to list upload jobs for.

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of upload job objects matching the filter criteria.

Source code in src/pixel_client/_base.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
async def get_upload_jobs(
    self,
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]:
    """Retrieve upload jobs for a data collection with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to list upload jobs for.
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of upload job objects matching the filter criteria.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/upload_jobs/",
        params=params_dict,
    )
    return response.json()

upload_image async

upload_image(
    project_id: int,
    data_collection_id: int,
    file_path: Path,
    metadata: dict | None = None,
    support_files: list[Path] | None = None,
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> dict

Upload an image file to an image data collection.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the image data collection to upload to.

required
file_path Path

Path to the image file to upload.

required
metadata dict | None

Optional dictionary of metadata to associate with the image.

None
support_files list[Path] | None

Optional list of support file paths to upload with the image.

None
multipart bool

If True, use multipart upload for large files.

False
multipart_part_size int | None

Required size of each part in bytes when using multipart upload.

None

Returns:

Name Type Description
dict dict

The created image object.

Raises:

Type Description
ValueError

If the data collection is not an image data collection.

FileNotFoundError

If the file does not exist.

ValueError

If multipart is True but multipart_part_size is not provided.

Source code in src/pixel_client/_base.py
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
async def upload_image(
    self,
    project_id: int,
    data_collection_id: int,
    file_path: Path,
    metadata: dict | None = None,
    support_files: list[Path] | None = None,
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> dict:
    """Upload an image file to an image data collection.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the image data collection to upload to.
        file_path: Path to the image file to upload.
        metadata: Optional dictionary of metadata to associate with the image.
        support_files: Optional list of support file paths to upload with the image.
        multipart: If True, use multipart upload for large files.
        multipart_part_size: Required size of each part in bytes when using multipart upload.

    Returns:
        dict: The created image object.

    Raises:
        ValueError: If the data collection is not an image data collection.
        FileNotFoundError: If the file does not exist.
        ValueError: If multipart is True but multipart_part_size is not provided.
    """
    dc = await self.get_data_collection(project_id, data_collection_id)
    if dc["data_collection_type"] != "image":
        raise ValueError("Data collection is not an image data collection")
    return await self._upload_file(
        project_id,
        data_collection_id,
        file_path,
        support_files=support_files,
        metadata=metadata,
        multipart=multipart,
        multipart_part_size=multipart_part_size,
    )

upload_multiple_images async

upload_multiple_images(
    project_id: int,
    data_collection_id: int,
    files: list[PixelUploadFile],
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> tuple[list[dict], list[PixelUploadJobError]]

Upload multiple image files to an image data collection.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the image data collection to upload to.

required
files list[PixelUploadFile]

List of PixelUploadFile objects containing the files to upload.

required
multipart bool

If True, use multipart upload for large files.

False
multipart_part_size int | None

Required size of each part in bytes when using multipart upload.

None

Returns:

Name Type Description
tuple tuple[list[dict], list[PixelUploadJobError]]

A tuple containing: - list[dict]: List of created image objects. - list[PixelUploadJobError]: List of errors that occurred during upload.

Raises:

Type Description
ValueError

If the data collection is not an image data collection.

ValueError

If any files have duplicate names.

ValueError

If multipart is True but multipart_part_size is not provided.

Source code in src/pixel_client/_base.py
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
async def upload_multiple_images(
    self,
    project_id: int,
    data_collection_id: int,
    files: list[PixelUploadFile],
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> tuple[list[dict], list[PixelUploadJobError]]:
    """Upload multiple image files to an image data collection.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the image data collection to upload to.
        files: List of PixelUploadFile objects containing the files to upload.
        multipart: If True, use multipart upload for large files.
        multipart_part_size: Required size of each part in bytes when using multipart upload.

    Returns:
        tuple: A tuple containing:
            - list[dict]: List of created image objects.
            - list[PixelUploadJobError]: List of errors that occurred during upload.

    Raises:
        ValueError: If the data collection is not an image data collection.
        ValueError: If any files have duplicate names.
        ValueError: If multipart is True but multipart_part_size is not provided.
    """
    dc = await self.get_data_collection(project_id, data_collection_id)
    if dc["data_collection_type"] != "image":
        raise ValueError("Data collection is not an image data collection")
    return await self._upload_multiple_files(
        project_id,
        data_collection_id,
        files,
        multipart,
        multipart_part_size,
    )

upload_multiple_rasters async

upload_multiple_rasters(
    project_id: int,
    data_collection_id: int,
    files: list[PixelUploadFile],
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> tuple[list[dict], list[PixelUploadJobError]]

Upload multiple raster files to a raster data collection.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the raster data collection to upload to.

required
files list[PixelUploadFile]

List of PixelUploadFile objects containing the files to upload.

required
multipart bool

If True, use multipart upload for large files.

False
multipart_part_size int | None

Required size of each part in bytes when using multipart upload.

None

Returns:

Name Type Description
tuple tuple[list[dict], list[PixelUploadJobError]]

A tuple containing: - list[dict]: List of created raster objects. - list[PixelUploadJobError]: List of errors that occurred during upload.

Raises:

Type Description
ValueError

If the data collection is not a raster data collection.

ValueError

If any files have duplicate names.

ValueError

If multipart is True but multipart_part_size is not provided.

Source code in src/pixel_client/_base.py
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
async def upload_multiple_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    files: list[PixelUploadFile],
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> tuple[list[dict], list[PixelUploadJobError]]:
    """Upload multiple raster files to a raster data collection.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the raster data collection to upload to.
        files: List of PixelUploadFile objects containing the files to upload.
        multipart: If True, use multipart upload for large files.
        multipart_part_size: Required size of each part in bytes when using multipart upload.

    Returns:
        tuple: A tuple containing:
            - list[dict]: List of created raster objects.
            - list[PixelUploadJobError]: List of errors that occurred during upload.

    Raises:
        ValueError: If the data collection is not a raster data collection.
        ValueError: If any files have duplicate names.
        ValueError: If multipart is True but multipart_part_size is not provided.
    """
    dc = await self.get_data_collection(project_id, data_collection_id)
    if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
        raise ValueError("Data collection is not a raster data collection")
    return await self._upload_multiple_files(
        project_id,
        data_collection_id,
        files,
        multipart,
        multipart_part_size,
    )

upload_raster async

upload_raster(
    project_id: int,
    data_collection_id: int,
    file_path: Path,
    support_files: list[Path] | None = None,
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> dict

Upload a raster file to a raster data collection.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the raster data collection to upload to.

required
file_path Path

Path to the raster file to upload.

required
support_files list[Path] | None

Optional list of support file paths to upload with the raster.

None
multipart bool

If True, use multipart upload for large files.

False
multipart_part_size int | None

Required size of each part in bytes when using multipart upload.

None

Returns:

Name Type Description
dict dict

The created raster object.

Raises:

Type Description
ValueError

If the data collection is not a raster data collection.

FileNotFoundError

If the file does not exist.

ValueError

If multipart is True but multipart_part_size is not provided.

Source code in src/pixel_client/_base.py
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
async def upload_raster(
    self,
    project_id: int,
    data_collection_id: int,
    file_path: Path,
    support_files: list[Path] | None = None,
    multipart: bool = False,
    multipart_part_size: int | None = None,
) -> dict:
    """Upload a raster file to a raster data collection.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the raster data collection to upload to.
        file_path: Path to the raster file to upload.
        support_files: Optional list of support file paths to upload with the raster.
        multipart: If True, use multipart upload for large files.
        multipart_part_size: Required size of each part in bytes when using multipart upload.

    Returns:
        dict: The created raster object.

    Raises:
        ValueError: If the data collection is not a raster data collection.
        FileNotFoundError: If the file does not exist.
        ValueError: If multipart is True but multipart_part_size is not provided.
    """
    dc = await self.get_data_collection(project_id, data_collection_id)
    if dc["data_collection_type"] not in ("raster", "RGB", "DTM", "DSM"):
        raise ValueError("Data collection is not a raster data collection")
    return await self._upload_file(
        project_id,
        data_collection_id,
        file_path,
        support_files=support_files,
        multipart=multipart,
        multipart_part_size=multipart_part_size,
    )

create_optimized_rasters async

create_optimized_rasters(
    project_id: int,
    data_collection_id: int,
    raster_ids: list[int] | None,
    profile: str | None = None,
    nearblack: NearblackOptions | None = None,
    overview_resampling: OverviewResampling = "average",
) -> list[dict]

Create optimized raster objects in the database.

This function creates optimized raster objects but does not run the actual optimization process. To run the optimization, use the run_optimize_rasters function with the returned optimized raster IDs.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the rasters.

required
raster_ids list[int] | None

Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.

required
profile str | None

Optional profile name to use for optimization.

None
nearblack NearblackOptions | None

Optional NearblackOptions object for configuring the nearblack process.

None
overview_resampling OverviewResampling

The resampling method to use for creating overviews. Default is "average".

'average'

Returns:

Type Description
list[dict]

list[dict]: List of created optimized raster objects.

Source code in src/pixel_client/_base.py
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
async def create_optimized_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    raster_ids: list[int] | None,
    profile: str | None = None,
    nearblack: NearblackOptions | None = None,
    overview_resampling: OverviewResampling = "average",
) -> list[dict]:
    """Create optimized raster objects in the database.

    This function creates optimized raster objects but does not run the actual optimization process.
    To run the optimization, use the run_optimize_rasters function with the returned optimized raster IDs.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the rasters.
        raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
        profile: Optional profile name to use for optimization.
        nearblack: Optional NearblackOptions object for configuring the nearblack process.
        overview_resampling: The resampling method to use for creating overviews. Default is "average".

    Returns:
        list[dict]: List of created optimized raster objects.
    """
    body: dict = {
        "creation_options": {
            "nearblack_options": nearblack.model_dump(
                exclude_none=True, mode="json"
            )
            if nearblack
            else NearblackOptions(enabled=False).model_dump(
                exclude_none=True, mode="json"
            ),
            "overview_resampling": overview_resampling,
        }
    }
    if raster_ids:
        body["raster_ids"] = raster_ids
    if profile:
        body["profile"] = profile
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
        json=body,
    )
    return response.json()

run_optimize_rasters async

run_optimize_rasters(
    project_id: int,
    data_collection_id: int,
    optimize_raster_ids: list[int] | None,
    retry_failed: bool = False,
) -> dict

Run the optimization process on optimized raster objects.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the optimized rasters.

required
optimize_raster_ids list[int] | None

Optional list of optimized raster IDs to process. If None, all optimized rasters in the collection will be processed.

required
retry_failed bool

If True, retry previously failed optimization jobs.

False

Returns:

Name Type Description
dict dict

The group job object representing the optimization process.

Source code in src/pixel_client/_base.py
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
async def run_optimize_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    optimize_raster_ids: list[int] | None,
    retry_failed: bool = False,
) -> dict:
    """Run the optimization process on optimized raster objects.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the optimized rasters.
        optimize_raster_ids: Optional list of optimized raster IDs to process. If None, all optimized rasters in the collection will be processed.
        retry_failed: If True, retry previously failed optimization jobs.

    Returns:
        dict: The group job object representing the optimization process.
    """
    body: dict = {"retry_failed": retry_failed}
    if optimize_raster_ids:
        body["optimized_raster_ids"] = optimize_raster_ids
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/run",
        json=body,
    )
    response_json = response.json()

    job = await self.wait_for_group_job(response_json["group_job"]["group_id"])
    return job

get_job async

get_job(job_id: int) -> dict

Retrieve information about a specific job.

Parameters:

Name Type Description Default
job_id int

The ID of the job to retrieve.

required

Returns:

Name Type Description
dict dict

The job object with its details.

Source code in src/pixel_client/_base.py
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
async def get_job(
    self,
    job_id: int,
) -> dict:
    """Retrieve information about a specific job.

    Args:
        job_id: The ID of the job to retrieve.

    Returns:
        dict: The job object with its details.
    """
    response = await self._get(f"/jobs/{job_id}")
    return response.json()

get_job_group async

get_job_group(job_id: int) -> dict

Retrieve information about a specific job group.

Parameters:

Name Type Description Default
job_id int

The ID of the job group to retrieve.

required

Returns:

Name Type Description
dict dict

The job group object with its details.

Source code in src/pixel_client/_base.py
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
async def get_job_group(
    self,
    job_id: int,
) -> dict:
    """Retrieve information about a specific job group.

    Args:
        job_id: The ID of the job group to retrieve.

    Returns:
        dict: The job group object with its details.
    """
    response = await self._get(f"/jobs/groups/{job_id}")
    return response.json()

wait_for_job async

wait_for_job(job_id: int, timeout: int = 600) -> dict

Wait for a job to complete, polling its status at regular intervals.

Parameters:

Name Type Description Default
job_id int

The ID of the job to wait for.

required
timeout int

Maximum time to wait in seconds before raising a TimeoutError. Default is 600 seconds (10 minutes).

600

Returns:

Name Type Description
dict dict

The completed job object.

Raises:

Type Description
TimeoutError

If the job does not complete within the specified timeout period.

Source code in src/pixel_client/_base.py
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
async def wait_for_job(
    self,
    job_id: int,
    timeout: int = 600,
) -> dict:
    """Wait for a job to complete, polling its status at regular intervals.

    Args:
        job_id: The ID of the job to wait for.
        timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 600 seconds (10 minutes).

    Returns:
        dict: The completed job object.

    Raises:
        TimeoutError: If the job does not complete within the specified timeout period.
    """
    job = await self.get_job(job_id)
    with silence_logger(logging.getLogger("httpx")):
        while not job["completed"]:
            job = await self.get_job(job_id)
            job_name = job["name"] or "unnamed"
            logger.info(f"Job {job_name} {job_id} status: {job['status']}")
            await asyncio.sleep(3)
            timeout -= 5
            if timeout <= 0:
                raise TimeoutError("Timed out waiting for job")
    logger.info(f"Job {job_id} finished with status {job['status']}")
    return job

wait_for_group_job async

wait_for_group_job(
    group_job_id: int, timeout: int = 1200
) -> dict

Wait for a group job to complete, polling its status at regular intervals.

A group job consists of multiple individual jobs. This method displays a progress bar showing the completion status of all jobs in the group.

Parameters:

Name Type Description Default
group_job_id int

The ID of the group job to wait for.

required
timeout int

Maximum time to wait in seconds before raising a TimeoutError. Default is 1200 seconds (20 minutes).

1200

Returns:

Name Type Description
dict dict

The completed group job object.

Raises:

Type Description
TimeoutError

If the group job does not complete within the specified timeout period.

Source code in src/pixel_client/_base.py
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
async def wait_for_group_job(
    self,
    group_job_id: int,
    timeout: int = 1200,
) -> dict:
    """Wait for a group job to complete, polling its status at regular intervals.

    A group job consists of multiple individual jobs. This method displays a progress bar
    showing the completion status of all jobs in the group.

    Args:
        group_job_id: The ID of the group job to wait for.
        timeout: Maximum time to wait in seconds before raising a TimeoutError. Default is 1200 seconds (20 minutes).

    Returns:
        dict: The completed group job object.

    Raises:
        TimeoutError: If the group job does not complete within the specified timeout period.
    """
    job = await self.get_job_group(group_job_id)
    num_jobs = job["total_jobs"]
    with (
        silence_logger(logging.getLogger("httpx")),
        tqdm.tqdm(total=num_jobs, desc=f"Running group job {group_job_id}") as pbar,
    ):
        while not job["completed"]:
            job = await self.get_job_group(group_job_id)
            num_failed = job["failed_count"]
            num_success = job["success_count"]
            num_finished = num_failed + num_success
            pbar.n = num_finished
            pbar.refresh()
            await asyncio.sleep(3)
            timeout -= 5
            if timeout <= 0:
                raise TimeoutError("Timed out waiting for optimize rasters job")
    logger.info(
        f"Group job {group_job_id} finished {job['total_jobs']} jobs, with {num_failed} failures and {num_success} successes"
    )
    return job

get_optimized_rasters async

get_optimized_rasters(
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]

Retrieve optimized rasters from a data collection with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the optimized rasters.

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of optimized raster objects matching the filter criteria.

Source code in src/pixel_client/_base.py
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
async def get_optimized_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]:
    """Retrieve optimized rasters from a data collection with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the optimized rasters.
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters.

    Returns:
        list[dict]: A list of optimized raster objects matching the filter criteria.
    """
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/optimized/",
        params=params_dict,
    )
    return response.json()

delete_optimized_rasters async

delete_optimized_rasters(
    project_id: int,
    data_collection_id: int,
    raster_id: int,
    profile: str | None = None,
) -> list[dict]

Delete optimized rasters associated with a specific raster.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the raster.

required
raster_id int

The ID of the raster whose optimized versions should be deleted.

required
profile str | None

Optional profile name to filter which optimized rasters to delete. If None, all optimized versions of the raster will be deleted.

None

Returns:

Type Description
list[dict]

list[dict]: A list of the deleted optimized raster objects.

Source code in src/pixel_client/_base.py
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
async def delete_optimized_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    raster_id: int,
    profile: str | None = None,
) -> list[dict]:
    """Delete optimized rasters associated with a specific raster.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the raster.
        raster_id: The ID of the raster whose optimized versions should be deleted.
        profile: Optional profile name to filter which optimized rasters to delete.
                If None, all optimized versions of the raster will be deleted.

    Returns:
        list[dict]: A list of the deleted optimized raster objects.
    """
    params = {}
    if profile:
        params["profile"] = profile
    response = await self._delete(
        f"/projects/{project_id}/data_collections/{data_collection_id}/rasters/{raster_id}/optimized",
        params=params,
    )
    return response.json()

optimize_rasters async

optimize_rasters(
    project_id: int,
    data_collection_id: int,
    raster_ids: list[int] | None = None,
    profile: str | None = None,
    nearblack: NearblackOptions | None = None,
    overview_resampling: OverviewResampling = "average",
) -> list[dict]

Create and run optimization on rasters in a data collection.

This is a convenience method that combines create_optimized_rasters and run_optimize_rasters into a single operation.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the rasters.

required
raster_ids list[int] | None

Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.

None
profile str | None

Optional profile name to use for optimization.

None
nearblack NearblackOptions | None

Optional NearblackOptions object for configuring the nearblack process.

None
overview_resampling OverviewResampling

The resampling method to use for creating overviews. Default is "average".

'average'

Returns:

Type Description
list[dict]

list[dict]: List of optimized raster objects after the optimization process has completed.

Source code in src/pixel_client/_base.py
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
async def optimize_rasters(
    self,
    project_id: int,
    data_collection_id: int,
    raster_ids: list[int] | None = None,
    profile: str | None = None,
    nearblack: NearblackOptions | None = None,
    overview_resampling: OverviewResampling = "average",
) -> list[dict]:
    """Create and run optimization on rasters in a data collection.

    This is a convenience method that combines create_optimized_rasters and run_optimize_rasters
    into a single operation.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the rasters.
        raster_ids: Optional list of raster IDs to optimize. If None, all rasters in the collection will be optimized.
        profile: Optional profile name to use for optimization.
        nearblack: Optional NearblackOptions object for configuring the nearblack process.
        overview_resampling: The resampling method to use for creating overviews. Default is "average".

    Returns:
        list[dict]: List of optimized raster objects after the optimization process has completed.
    """
    optimized_rasters = await self.create_optimized_rasters(
        project_id,
        data_collection_id,
        raster_ids,
        profile,
        nearblack=nearblack,
        overview_resampling=overview_resampling,
    )
    await self.run_optimize_rasters(
        project_id, data_collection_id, [r["id"] for r in optimized_rasters]
    )
    optimized_rasters = await self.get_optimized_rasters(
        project_id,
        data_collection_id,
        params=ListParams(
            ids=[r["id"] for r in optimized_rasters], limit=len(optimized_rasters)
        ),
    )
    return optimized_rasters

list_gdo_users async

list_gdo_users() -> list[str]

Retrieve a list of GDO (GeoData Online) users.

Returns:

Type Description
list[str]

list[dict]: A list of GDO user names.

Source code in src/pixel_client/_base.py
2038
2039
2040
2041
2042
2043
2044
2045
async def list_gdo_users(self) -> list[str]:
    """Retrieve a list of GDO (GeoData Online) users.

    Returns:
        list[dict]: A list of GDO user names.
    """
    response = await self._get("/arcgis_services/gdo-users")
    return response.json()

create_arcgis_service async

create_arcgis_service(
    service_type: Literal["Feature", "Image"],
    create_input: ArcgisServiceCreateInput,
) -> dict

Create a new ArcGIS service.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service to create, either "Feature" or "Image".

required
create_input ArcgisServiceCreateInput

ArcgisServiceCreateInput object containing the service configuration.

required

Returns:

Name Type Description
dict dict

The created ArcGIS service object.

Raises:

Type Description
AssertionError

If the create_input does not contain the appropriate service options for the specified service_type.

Source code in src/pixel_client/_base.py
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
async def create_arcgis_service(
    self,
    service_type: Literal["Feature", "Image"],
    create_input: ArcgisServiceCreateInput,
) -> dict:
    """Create a new ArcGIS service.

    Args:
        service_type: The type of service to create, either "Feature" or "Image".
        create_input: ArcgisServiceCreateInput object containing the service configuration.

    Returns:
        dict: The created ArcGIS service object.

    Raises:
        AssertionError: If the create_input does not contain the appropriate service options for the specified service_type.
    """
    assert (
        getattr(
            create_input.options, f"{service_type.lower()}_service_options", None
        )
        is not None
    ), (
        f"Service options for {service_type} service must be provided in the create input"
    )
    response = await self._post(
        f"/arcgis_services/{service_type}/",
        json=create_input.model_dump(mode="json"),
    )
    return response.json()

list_arcgis_services async

list_arcgis_services(
    service_type: Literal["Feature", "Image"],
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]

List ArcGIS services of a specific type with optional filtering.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of services to list, either "Feature" or "Image".

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of ArcGIS service objects matching the filter criteria.

Source code in src/pixel_client/_base.py
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
async def list_arcgis_services(
    self,
    service_type: Literal["Feature", "Image"],
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]:
    """List ArcGIS services of a specific type with optional filtering.

    Args:
        service_type: The type of services to list, either "Feature" or "Image".
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters.

    Returns:
        list[dict]: A list of ArcGIS service objects matching the filter criteria.
    """
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get(
        f"/arcgis_services/{service_type}/", params=params_dict
    )
    return response.json()

get_arcgis_service async

get_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
) -> dict

Retrieve a specific ArcGIS service by its ID.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to retrieve.

required

Returns:

Name Type Description
dict dict

The ArcGIS service object with its details.

Source code in src/pixel_client/_base.py
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
async def get_arcgis_service(
    self, service_type: Literal["Feature", "Image"], service_id: int
) -> dict:
    """Retrieve a specific ArcGIS service by its ID.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to retrieve.

    Returns:
        dict: The ArcGIS service object with its details.
    """
    response = await self._get(f"/arcgis_services/{service_type}/{service_id}")
    return response.json()

delete_arcgis_service async

delete_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
) -> dict

Delete a specific ArcGIS service by its ID.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
async def delete_arcgis_service(
    self, service_type: Literal["Feature", "Image"], service_id: int
) -> dict:
    """Delete a specific ArcGIS service by its ID.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(f"/arcgis_services/{service_type}/{service_id}")
    return response.json()

update_arcgis_service async

update_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
    update_input: ArcgisServiceUpdateInput,
) -> dict

Update an existing ArcGIS service with new values.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to update.

required
update_input ArcgisServiceUpdateInput

ArcgisServiceUpdateInput object containing the fields to update.

required

Returns:

Name Type Description
dict dict

The updated ArcGIS service object.

Source code in src/pixel_client/_base.py
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
async def update_arcgis_service(
    self,
    service_type: Literal["Feature", "Image"],
    service_id: int,
    update_input: ArcgisServiceUpdateInput,
) -> dict:
    """Update an existing ArcGIS service with new values.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to update.
        update_input: ArcgisServiceUpdateInput object containing the fields to update.

    Returns:
        dict: The updated ArcGIS service object.
    """
    response = await self._put(
        f"/arcgis_services/{service_type}/{service_id}",
        json=update_input.model_dump(mode="json"),
    )
    return response.json()

start_arcgis_service async

start_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
    wait: bool = True,
) -> dict

Start a specific ArcGIS service.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to start.

required
wait bool

If True, wait for the start operation to complete before returning. If False, return immediately after initiating the start operation.

True

Returns:

Name Type Description
dict dict

A response object containing job information and, if wait is True, the updated service object after starting.

Source code in src/pixel_client/_base.py
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
async def start_arcgis_service(
    self,
    service_type: Literal["Feature", "Image"],
    service_id: int,
    wait: bool = True,
) -> dict:
    """Start a specific ArcGIS service.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to start.
        wait: If True, wait for the start operation to complete before returning.
             If False, return immediately after initiating the start operation.

    Returns:
        dict: A response object containing job information and, if wait is True,
             the updated service object after starting.
    """
    response = await self._put(
        f"/arcgis_services/{service_type}/{service_id}/start"
    )
    resp = response.json()
    job = resp["job"]
    if wait and job:
        job = await self.wait_for_job(job["job_id"], timeout=1000)
        resp["job"] = job
        resp["arcgis_service"] = await self.get_arcgis_service(
            service_type, service_id
        )
    return resp

stop_arcgis_service async

stop_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
    wait: bool = True,
) -> dict

Stop a specific ArcGIS service.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to stop.

required
wait bool

If True, wait for the stop operation to complete before returning. If False, return immediately after initiating the stop operation.

True

Returns:

Name Type Description
dict dict

A response object containing job information and, if wait is True, the updated service object after stopping.

Source code in src/pixel_client/_base.py
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
async def stop_arcgis_service(
    self,
    service_type: Literal["Feature", "Image"],
    service_id: int,
    wait: bool = True,
) -> dict:
    """Stop a specific ArcGIS service.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to stop.
        wait: If True, wait for the stop operation to complete before returning.
             If False, return immediately after initiating the stop operation.

    Returns:
        dict: A response object containing job information and, if wait is True,
             the updated service object after stopping.
    """
    response = await self._put(f"/arcgis_services/{service_type}/{service_id}/stop")
    resp = response.json()
    job = resp["job"]
    if wait and job:
        job = await self.wait_for_job(job["job_id"], timeout=1000)
        resp["job"] = job
        resp["arcgis_service"] = await self.get_arcgis_service(
            service_type, service_id
        )
    return resp

refresh_arcgis_service async

refresh_arcgis_service(
    service_type: Literal["Feature", "Image"],
    service_id: int,
    refresh_data: bool = False,
    wait: bool = True,
) -> dict

Refresh a specific ArcGIS service, optionally refreshing its data.

Parameters:

Name Type Description Default
service_type Literal['Feature', 'Image']

The type of service, either "Feature" or "Image".

required
service_id int

The ID of the service to refresh.

required
refresh_data bool

If True, also refresh the data used by the service.

False
wait bool

If True, wait for the refresh operation to complete before returning. If False, return immediately after initiating the refresh operation.

True

Returns:

Name Type Description
dict dict

A response object containing job information and, if wait is True, the updated service object after refreshing.

Source code in src/pixel_client/_base.py
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
async def refresh_arcgis_service(
    self,
    service_type: Literal["Feature", "Image"],
    service_id: int,
    refresh_data: bool = False,
    wait: bool = True,
) -> dict:
    """Refresh a specific ArcGIS service, optionally refreshing its data.

    Args:
        service_type: The type of service, either "Feature" or "Image".
        service_id: The ID of the service to refresh.
        refresh_data: If True, also refresh the data used by the service.
        wait: If True, wait for the refresh operation to complete before returning.
             If False, return immediately after initiating the refresh operation.

    Returns:
        dict: A response object containing job information and, if wait is True,
             the updated service object after refreshing.
    """
    response = await self._put(
        f"/arcgis_services/{service_type}/{service_id}/refresh",
        params={"refresh_data": refresh_data},
    )
    resp = response.json()
    job = resp["job"]
    if wait and job:
        job = await self.wait_for_job(job["job_id"], timeout=1000)
        resp["job"] = job
        resp["arcgis_service"] = await self.get_arcgis_service(
            service_type, service_id
        )
    return resp

create_harvest_service async

create_harvest_service(
    project_id: int,
    data_collection_id: int,
    create_input: HarvestServiceCreateInput,
) -> dict

Create a new harvest service for a data collection.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to create the harvest service for.

required
create_input HarvestServiceCreateInput

HarvestServiceCreateInput object containing the service configuration.

required

Returns:

Name Type Description
dict dict

The created harvest service object.

Source code in src/pixel_client/_base.py
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
async def create_harvest_service(
    self,
    project_id: int,
    data_collection_id: int,
    create_input: HarvestServiceCreateInput,
) -> dict:
    """Create a new harvest service for a data collection.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to create the harvest service for.
        create_input: HarvestServiceCreateInput object containing the service configuration.

    Returns:
        dict: The created harvest service object.
    """
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
        json=create_input.model_dump(mode="json"),
        sensitive_content=True,
    )
    return response.json()

list_harvest_services async

list_harvest_services(
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]

List harvest services for a data collection with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection to list harvest services for.

required
params ListParams | None

Optional ListParams object containing filtering parameters.

None
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of harvest service objects matching the filter criteria.

Source code in src/pixel_client/_base.py
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
async def list_harvest_services(
    self,
    project_id: int,
    data_collection_id: int,
    params: ListParams | None = None,
    **kwargs,
) -> list[dict]:
    """List harvest services for a data collection with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection to list harvest services for.
        params: Optional ListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of harvest service objects matching the filter criteria.
    """
    if params and kwargs:
        logger.warning("Ignoring kwargs when params is provided")
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/",
        params=params_dict,
    )
    return response.json()

get_harvest_service async

get_harvest_service(
    project_id: int,
    data_collection_id: int,
    service_id: int,
) -> dict

Retrieve a specific harvest service by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to retrieve.

required

Returns:

Name Type Description
dict dict

The harvest service object with its details.

Source code in src/pixel_client/_base.py
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
async def get_harvest_service(
    self, project_id: int, data_collection_id: int, service_id: int
) -> dict:
    """Retrieve a specific harvest service by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to retrieve.

    Returns:
        dict: The harvest service object with its details.
    """
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
    )
    return response.json()

update_harvest_service async

update_harvest_service(
    project_id: int,
    data_collection_id: int,
    service_id: int,
    update_input: HarvestServiceUpdateInput,
) -> dict

Update an existing harvest service with new values.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to update.

required
update_input HarvestServiceUpdateInput

HarvestServiceUpdateInput object containing the fields to update.

required

Returns:

Name Type Description
dict dict

The updated harvest service object.

Source code in src/pixel_client/_base.py
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
async def update_harvest_service(
    self,
    project_id: int,
    data_collection_id: int,
    service_id: int,
    update_input: HarvestServiceUpdateInput,
) -> dict:
    """Update an existing harvest service with new values.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to update.
        update_input: HarvestServiceUpdateInput object containing the fields to update.

    Returns:
        dict: The updated harvest service object.
    """
    response = await self._put(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}",
        json=update_input.model_dump(mode="json", exclude_none=True),
        sensitive_content=True,
    )
    return response.json()

delete_harvest_service async

delete_harvest_service(
    project_id: int,
    data_collection_id: int,
    service_id: int,
) -> dict

Delete a specific harvest service by its ID.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
async def delete_harvest_service(
    self, project_id: int, data_collection_id: int, service_id: int
) -> dict:
    """Delete a specific harvest service by its ID.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to delete.

    Returns:
        dict: The response confirming deletion.
    """
    response = await self._delete(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}"
    )
    return response.json()

get_harvest_service_tasks async

get_harvest_service_tasks(
    project_id: int,
    data_collection_id: int,
    service_id: int,
    params: HarvestTaskListParams,
    **kwargs,
) -> list[dict]

Retrieve tasks for a specific harvest service with optional filtering.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to retrieve tasks for.

required
params HarvestTaskListParams

HarvestTaskListParams object containing filtering parameters.

required
**kwargs

Alternative way to provide filtering parameters. Ignored if params is provided.

{}

Returns:

Type Description
list[dict]

list[dict]: A list of harvest task objects matching the filter criteria.

Source code in src/pixel_client/_base.py
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
async def get_harvest_service_tasks(
    self,
    project_id: int,
    data_collection_id: int,
    service_id: int,
    params: HarvestTaskListParams,
    **kwargs,
) -> list[dict]:
    """Retrieve tasks for a specific harvest service with optional filtering.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to retrieve tasks for.
        params: HarvestTaskListParams object containing filtering parameters.
        **kwargs: Alternative way to provide filtering parameters. Ignored if params is provided.

    Returns:
        list[dict]: A list of harvest task objects matching the filter criteria.
    """
    params_dict = (
        params.model_dump(exclude_none=True)
        if params
        else ListParams.model_validate(kwargs).model_dump(exclude_none=True)
    )
    response = await self._get(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/",
        params=params_dict,
    )
    return response.json()

start_harvest_service async

start_harvest_service(
    project_id: int,
    data_collection_id: int,
    service_id: int,
) -> dict

Start a specific harvest service.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to start.

required

Returns:

Name Type Description
dict dict

The response confirming the service has been started.

Source code in src/pixel_client/_base.py
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
async def start_harvest_service(
    self, project_id: int, data_collection_id: int, service_id: int
) -> dict:
    """Start a specific harvest service.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to start.

    Returns:
        dict: The response confirming the service has been started.
    """
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/start"
    )
    return response.json()

stop_harvest_service async

stop_harvest_service(
    project_id: int,
    data_collection_id: int,
    service_id: int,
) -> dict

Stop a specific harvest service.

Parameters:

Name Type Description Default
project_id int

The ID of the project containing the data collection.

required
data_collection_id int

The ID of the data collection containing the harvest service.

required
service_id int

The ID of the harvest service to stop.

required

Returns:

Name Type Description
dict dict

The response confirming the service has been stopped.

Source code in src/pixel_client/_base.py
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
async def stop_harvest_service(
    self, project_id: int, data_collection_id: int, service_id: int
) -> dict:
    """Stop a specific harvest service.

    Args:
        project_id: The ID of the project containing the data collection.
        data_collection_id: The ID of the data collection containing the harvest service.
        service_id: The ID of the harvest service to stop.

    Returns:
        dict: The response confirming the service has been stopped.
    """
    response = await self._post(
        f"/projects/{project_id}/data_collections/{data_collection_id}/harvest_services/{service_id}/stop"
    )
    return response.json()

create_oidc_user async

create_oidc_user(create_input: OIDCUserCreateInput) -> dict

Create a new OIDC user in the system.

Parameters:

Name Type Description Default
create_input OIDCUserCreateInput

OIDCUserCreateInput object containing the user information.

required

Returns:

Name Type Description
dict dict

The created user object.

Note

This method handles the extraction of the password from the SecretStr field in the create_input object.

Source code in src/pixel_client/_base.py
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
async def create_oidc_user(self, create_input: OIDCUserCreateInput) -> dict:
    """Create a new OIDC user in the system.

    Args:
        create_input: OIDCUserCreateInput object containing the user information.

    Returns:
        dict: The created user object.

    Note:
        This method handles the extraction of the password from the SecretStr field
        in the create_input object.
    """
    model_dump = create_input.model_dump(mode="json")
    response = await self._post(
        "/users/oidc/", json=model_dump, sensitive_content=True
    )
    return response.json()

update_oidc_user async

update_oidc_user(
    user_id: int, update_input: OIDCUserUpdateInput
) -> dict

Update an existing OIDC user with new values.

Parameters:

Name Type Description Default
user_id int

The ID of the user to update.

required
update_input OIDCUserUpdateInput

OIDCUserUpdateInput object containing the fields to update.

required

Returns:

Name Type Description
dict dict

The updated user object.

Note

This method handles the extraction of the password from the SecretStr field in the update_input object if provided.

Source code in src/pixel_client/_base.py
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
async def update_oidc_user(
    self, user_id: int, update_input: OIDCUserUpdateInput
) -> dict:
    """Update an existing OIDC user with new values.

    Args:
        user_id: The ID of the user to update.
        update_input: OIDCUserUpdateInput object containing the fields to update.

    Returns:
        dict: The updated user object.

    Note:
        This method handles the extraction of the password from the SecretStr field
        in the update_input object if provided.
    """
    model_dump = update_input.model_dump(mode="json")
    response = await self._put(
        f"/users/oidc/{user_id}/", json=model_dump, sensitive_content=True
    )
    return response.json()

list_attachments async

list_attachments(
    resource_type: AttachmentResourceType,
    resource_id: int,
    status: Literal["Pending", "Completed"] | None = None,
) -> list[dict]

List attachments for a specific resource with optional status filtering.

Parameters:

Name Type Description Default
resource_type AttachmentResourceType

The type of resource the attachments belong to.

required
resource_id int

The ID of the resource to list attachments for.

required
status Literal['Pending', 'Completed'] | None

Optional filter for attachment status, either "Pending" or "Completed".

None

Returns:

Type Description
list[dict]

list[dict]: A list of attachment objects matching the filter criteria.

Source code in src/pixel_client/_base.py
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
async def list_attachments(
    self,
    resource_type: AttachmentResourceType,
    resource_id: int,
    status: Literal["Pending", "Completed"] | None = None,
) -> list[dict]:
    """List attachments for a specific resource with optional status filtering.

    Args:
        resource_type: The type of resource the attachments belong to.
        resource_id: The ID of the resource to list attachments for.
        status: Optional filter for attachment status, either "Pending" or "Completed".

    Returns:
        list[dict]: A list of attachment objects matching the filter criteria.
    """
    params = {"resource_type": resource_type, "resource_id": resource_id}
    if status:
        params["status"] = status
    response = await self._get(
        "/attachments/",
        params=params,
    )
    return response.json()

add_attachments async

add_attachments(
    resource_type: AttachmentResourceType,
    resource_id: int,
    files: list[PixelAttachmentUpload | Path]
    | list[Path]
    | list[PixelAttachmentUpload],
) -> list[dict]

Add one or more file attachments to a resource.

Parameters:

Name Type Description Default
resource_type AttachmentResourceType

The type of resource to attach files to.

required
resource_id int

The ID of the resource to attach files to.

required
files list[PixelAttachmentUpload | Path] | list[Path] | list[PixelAttachmentUpload]

List of files to attach, which can be Path objects or PixelAttachmentUpload objects.

required

Returns:

Type Description
list[dict]

list[dict]: A list of the created attachment objects.

Raises:

Type Description
AssertionError

If any attachment names are not unique.

Source code in src/pixel_client/_base.py
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
async def add_attachments(
    self,
    resource_type: AttachmentResourceType,
    resource_id: int,
    files: list[PixelAttachmentUpload | Path]
    | list[Path]
    | list[PixelAttachmentUpload],
) -> list[dict]:
    """Add one or more file attachments to a resource.

    Args:
        resource_type: The type of resource to attach files to.
        resource_id: The ID of the resource to attach files to.
        files: List of files to attach, which can be Path objects or PixelAttachmentUpload objects.

    Returns:
        list[dict]: A list of the created attachment objects.

    Raises:
        AssertionError: If any attachment names are not unique.
    """
    pixel_attachments = [
        PixelAttachmentUpload(
            file=f,
        )
        if isinstance(f, Path)
        else f
        for f in files
    ]
    assert len(set(pa.name for pa in pixel_attachments)) == len(
        pixel_attachments
    ), "Attachment names must be unique"
    response = await self._post(
        "/attachments/",
        params={"resource_type": resource_type, "resource_id": resource_id},
        json={"files": [pa.model_dump(mode="json") for pa in pixel_attachments]},
    )
    attachments = response.json()
    sorted_attachments = sorted(attachments, key=lambda a: a["name"])
    sorted_files = sorted(pixel_attachments, key=lambda f: f.name)
    attachments = await asyncio.gather(
        *[
            self._upload_attachment_to_s3(resource_type, resource_id, a, pa.file)
            for a, pa in zip(sorted_attachments, sorted_files)
        ]
    )
    return attachments

move_attachment async

move_attachment(
    resource_type: AttachmentResourceType,
    resource_id: int,
    attachment_id: int,
    new_resource_type: AttachmentResourceType,
    new_resource_id: int,
) -> dict

Move an attachment from one resource to another.

Parameters:

Name Type Description Default
resource_type AttachmentResourceType

The current resource type of the attachment.

required
resource_id int

The current resource ID the attachment belongs to.

required
attachment_id int

The ID of the attachment to move.

required
new_resource_type AttachmentResourceType

The target resource type to move the attachment to.

required
new_resource_id int

The target resource ID to move the attachment to.

required

Returns:

Name Type Description
dict dict

The updated attachment object.

Source code in src/pixel_client/_base.py
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
async def move_attachment(
    self,
    resource_type: AttachmentResourceType,
    resource_id: int,
    attachment_id: int,
    new_resource_type: AttachmentResourceType,
    new_resource_id: int,
) -> dict:
    """Move an attachment from one resource to another.

    Args:
        resource_type: The current resource type of the attachment.
        resource_id: The current resource ID the attachment belongs to.
        attachment_id: The ID of the attachment to move.
        new_resource_type: The target resource type to move the attachment to.
        new_resource_id: The target resource ID to move the attachment to.

    Returns:
        dict: The updated attachment object.
    """
    resp = await self._put(
        "/attachments/move",
        params={
            "resource_type": resource_type,
            "resource_id": resource_id,
            "attachment_id": attachment_id,
            "new_resource_type": new_resource_type,
            "new_resource_id": new_resource_id,
        },
    )
    return resp.json()

delete_attachment async

delete_attachment(
    resource_type: AttachmentResourceType,
    resource_id: int,
    attachment_id: int,
) -> dict

Delete a specific attachment from a resource.

Parameters:

Name Type Description Default
resource_type AttachmentResourceType

The resource type the attachment belongs to.

required
resource_id int

The resource ID the attachment belongs to.

required
attachment_id int

The ID of the attachment to delete.

required

Returns:

Name Type Description
dict dict

The response confirming deletion.

Source code in src/pixel_client/_base.py
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
async def delete_attachment(
    self,
    resource_type: AttachmentResourceType,
    resource_id: int,
    attachment_id: int,
) -> dict:
    """Delete a specific attachment from a resource.

    Args:
        resource_type: The resource type the attachment belongs to.
        resource_id: The resource ID the attachment belongs to.
        attachment_id: The ID of the attachment to delete.

    Returns:
        dict: The response confirming deletion.
    """
    resp = await self._delete(
        "/attachments/",
        params={
            "resource_type": resource_type,
            "resource_id": resource_id,
            "attachment_id": attachment_id,
        },
    )
    return resp.json()

search_info async

search_info(on: SearchOn)

Retrieve search metadata for a specific resource type.

Parameters:

Name Type Description Default
on SearchOn

The resource type to retrieve search metadata for.

required
Source code in src/pixel_client/_base.py
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
async def search_info(self, on: SearchOn):
    """
    Retrieve search metadata for a specific resource type.

    Args:
        on: The resource type to retrieve search metadata for.
    Returns:
        dict: A dictionary containing output fields, filterable fields and search capabilities.
    """
    response = await self._get(
        "/search/info",
        params={"on": on},
    )
    return response.json()

search async

search(search_query: dict | SearchQuery) -> SearchResults

Perform a search across various resources.

Parameters:

Name Type Description Default
search_query dict | SearchQuery

SearchQuery object or dict containing the search parameters.

required
Source code in src/pixel_client/_base.py
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
async def search(
    self,
    search_query: dict | SearchQuery,
) -> SearchResults:
    """
    Perform a search across various resources.

    Args:
        search_query: SearchQuery object or dict containing the search parameters.
    Returns:
        SearchResults: The search results dictionary.
    """
    search_model = (
        SearchQuery.model_validate(search_query)
        if isinstance(search_query, dict)
        else search_query
    )
    response = await self._post(
        "/search/",
        json=search_model.model_dump(mode="json", exclude_none=True),
    )
    return response.json()
paginate_search(
    search_query: dict | SearchQuery, page_size: int
) -> AsyncGenerator[dict, None]

Perform a paginated search across various resources.

Parameters:

Name Type Description Default
search_query dict | SearchQuery

SearchQuery object or dict containing the search parameters.

required
page_size int

Number of results to retrieve per page.

required

Yields:

Name Type Description
dict AsyncGenerator[dict, None]

Individual search result items.

Source code in src/pixel_client/_base.py
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
async def paginate_search(
    self, search_query: dict | SearchQuery, page_size: int
) -> AsyncGenerator[dict, None]:
    """
    Perform a paginated search across various resources.

    Args:
        search_query: SearchQuery object or dict containing the search parameters.
        page_size: Number of results to retrieve per page.

    Yields:
        dict: Individual search result items.
    """
    search_model = (
        SearchQuery.model_validate(search_query)
        if isinstance(search_query, dict)
        else search_query
    )
    search_query_body = search_model.model_dump(mode="json", exclude_none=True)
    async for item in self._paginate(
        "/search/",
        method="POST",
        page_size=page_size,
        use_body=True,
        # The return of the search endpoint is in the "results" field
        results_parser=lambda resp: resp.get("results", []),
        json=search_query_body,
    ):
        yield item