Skip to content

Asynchronous client implementation for communicating with the Prefect REST API.

Explore the client by communicating with an in-memory webserver — no setup required:

$ # start python REPL with native await functionality
$ python -m asyncio
>>> from prefect import get_client
>>> async with get_client() as client:
...     response = await client.hello()
...     print(response.json())
👋

prefect.client.orchestration

PrefectClient

An asynchronous client for interacting with the Prefect REST API.

Parameters:

Name Type Description Default
api Union[str, FastAPI]

the REST API URL or FastAPI application to connect to

required
api_key str

An optional API key for authentication.

None
api_version str

The API version this client is compatible with.

None
httpx_settings dict

An optional dictionary of settings to pass to the underlying httpx.AsyncClient

None

Examples:

Say hello to a Prefect REST API

>>> async with get_client() as client:
>>>     response = await client.hello()
>>>
>>> print(response.json())
👋
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
 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
class PrefectClient:
    """
    An asynchronous client for interacting with the [Prefect REST API](/api-ref/rest-api/).

    Args:
        api: the REST API URL or FastAPI application to connect to
        api_key: An optional API key for authentication.
        api_version: The API version this client is compatible with.
        httpx_settings: An optional dictionary of settings to pass to the underlying
            `httpx.AsyncClient`

    Examples:

        Say hello to a Prefect REST API

        <div class="terminal">
        ```
        >>> async with get_client() as client:
        >>>     response = await client.hello()
        >>>
        >>> print(response.json())
        👋
        ```
        </div>
    """

    def __init__(
        self,
        api: Union[str, FastAPI],
        *,
        api_key: str = None,
        api_version: str = None,
        httpx_settings: dict = None,
    ) -> None:
        httpx_settings = httpx_settings.copy() if httpx_settings else {}
        httpx_settings.setdefault("headers", {})

        if PREFECT_API_TLS_INSECURE_SKIP_VERIFY:
            httpx_settings.setdefault("verify", False)

        if api_version is None:
            # deferred import to avoid importing the entire server unless needed
            from prefect.server.api.server import SERVER_API_VERSION

            api_version = SERVER_API_VERSION
        httpx_settings["headers"].setdefault("X-PREFECT-API-VERSION", api_version)
        if api_key:
            httpx_settings["headers"].setdefault("Authorization", f"Bearer {api_key}")

        # Context management
        self._exit_stack = AsyncExitStack()
        self._ephemeral_app: Optional[FastAPI] = None
        self.manage_lifespan = True
        self.server_type: ServerType

        # Only set if this client started the lifespan of the application
        self._ephemeral_lifespan: Optional[LifespanManager] = None

        self._closed = False
        self._started = False

        # Connect to an external application
        if isinstance(api, str):
            if httpx_settings.get("app"):
                raise ValueError(
                    "Invalid httpx settings: `app` cannot be set when providing an "
                    "api url. `app` is only for use with ephemeral instances. Provide "
                    "it as the `api` parameter instead."
                )
            httpx_settings.setdefault("base_url", api)

            # See https://www.python-httpx.org/advanced/#pool-limit-configuration
            httpx_settings.setdefault(
                "limits",
                httpx.Limits(
                    # We see instability when allowing the client to open many connections at once.
                    # Limiting concurrency results in more stable performance.
                    max_connections=16,
                    max_keepalive_connections=8,
                    # The Prefect Cloud LB will keep connections alive for 30s.
                    # Only allow the client to keep connections alive for 25s.
                    keepalive_expiry=25,
                ),
            )

            # See https://www.python-httpx.org/http2/
            # Enabling HTTP/2 support on the client does not necessarily mean that your requests
            # and responses will be transported over HTTP/2, since both the client and the server
            # need to support HTTP/2. If you connect to a server that only supports HTTP/1.1 the
            # client will use a standard HTTP/1.1 connection instead.
            httpx_settings.setdefault("http2", PREFECT_API_ENABLE_HTTP2.value())

            self.server_type = (
                ServerType.CLOUD
                if api.startswith(PREFECT_CLOUD_API_URL.value())
                else ServerType.SERVER
            )

        # Connect to an in-process application
        elif isinstance(api, FastAPI):
            self._ephemeral_app = api
            self.server_type = ServerType.EPHEMERAL

            # When using an ephemeral server, server-side exceptions can be raised
            # client-side breaking all of our response error code handling. To work
            # around this, we create an ASGI transport with application exceptions
            # disabled instead of using the application directly.
            # refs:
            # - https://github.com/PrefectHQ/prefect/pull/9637
            # - https://github.com/encode/starlette/blob/d3a11205ed35f8e5a58a711db0ff59c86fa7bb31/starlette/middleware/errors.py#L184
            # - https://github.com/tiangolo/fastapi/blob/8cc967a7605d3883bd04ceb5d25cc94ae079612f/fastapi/applications.py#L163-L164
            httpx_settings.setdefault(
                "transport",
                httpx.ASGITransport(
                    app=self._ephemeral_app, raise_app_exceptions=False
                ),
            )
            httpx_settings.setdefault("base_url", "http://ephemeral-prefect/api")

        else:
            raise TypeError(
                f"Unexpected type {type(api).__name__!r} for argument `api`. Expected"
                " 'str' or 'FastAPI'"
            )

        # See https://www.python-httpx.org/advanced/#timeout-configuration
        httpx_settings.setdefault(
            "timeout",
            httpx.Timeout(
                connect=PREFECT_API_REQUEST_TIMEOUT.value(),
                read=PREFECT_API_REQUEST_TIMEOUT.value(),
                write=PREFECT_API_REQUEST_TIMEOUT.value(),
                pool=PREFECT_API_REQUEST_TIMEOUT.value(),
            ),
        )

        if not PREFECT_UNIT_TEST_MODE:
            httpx_settings.setdefault("follow_redirects", True)
        self._client = PrefectHttpxClient(**httpx_settings)
        self._loop = None

        # See https://www.python-httpx.org/advanced/#custom-transports
        #
        # If we're using an HTTP/S client (not the ephemeral client), adjust the
        # transport to add retries _after_ it is instantiated. If we alter the transport
        # before instantiation, the transport will not be aware of proxies unless we
        # reproduce all of the logic to make it so.
        #
        # Only alter the transport to set our default of 3 retries, don't modify any
        # transport a user may have provided via httpx_settings.
        #
        # Making liberal use of getattr and isinstance checks here to avoid any
        # surprises if the internals of httpx or httpcore change on us
        if isinstance(api, str) and not httpx_settings.get("transport"):
            transport_for_url = getattr(self._client, "_transport_for_url", None)
            if callable(transport_for_url):
                server_transport = transport_for_url(httpx.URL(api))
                if isinstance(server_transport, httpx.AsyncHTTPTransport):
                    pool = getattr(server_transport, "_pool", None)
                    if isinstance(pool, httpcore.AsyncConnectionPool):
                        pool._retries = 3

        self.logger = get_logger("client")

    @property
    def api_url(self) -> httpx.URL:
        """
        Get the base URL for the API.
        """
        return self._client.base_url

    # API methods ----------------------------------------------------------------------

    async def api_healthcheck(self) -> Optional[Exception]:
        """
        Attempts to connect to the API and returns the encountered exception if not
        successful.

        If successful, returns `None`.
        """
        try:
            await self._client.get("/health")
            return None
        except Exception as exc:
            return exc

    async def hello(self) -> httpx.Response:
        """
        Send a GET request to /hello for testing purposes.
        """
        return await self._client.get("/hello")

    async def create_flow(self, flow: "FlowObject") -> UUID:
        """
        Create a flow in the Prefect API.

        Args:
            flow: a [Flow][prefect.flows.Flow] object

        Raises:
            httpx.RequestError: if a flow was not created for any reason

        Returns:
            the ID of the flow in the backend
        """
        return await self.create_flow_from_name(flow.name)

    async def create_flow_from_name(self, flow_name: str) -> UUID:
        """
        Create a flow in the Prefect API.

        Args:
            flow_name: the name of the new flow

        Raises:
            httpx.RequestError: if a flow was not created for any reason

        Returns:
            the ID of the flow in the backend
        """
        flow_data = FlowCreate(name=flow_name)
        response = await self._client.post(
            "/flows/", json=flow_data.dict(json_compatible=True)
        )

        flow_id = response.json().get("id")
        if not flow_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        # Return the id of the created flow
        return UUID(flow_id)

    async def read_flow(self, flow_id: UUID) -> Flow:
        """
        Query the Prefect API for a flow by id.

        Args:
            flow_id: the flow ID of interest

        Returns:
            a [Flow model][prefect.client.schemas.objects.Flow] representation of the flow
        """
        response = await self._client.get(f"/flows/{flow_id}")
        return Flow.parse_obj(response.json())

    async def read_flows(
        self,
        *,
        flow_filter: FlowFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        deployment_filter: DeploymentFilter = None,
        work_pool_filter: WorkPoolFilter = None,
        work_queue_filter: WorkQueueFilter = None,
        sort: FlowSort = None,
        limit: int = None,
        offset: int = 0,
    ) -> List[Flow]:
        """
        Query the Prefect API for flows. Only flows matching all criteria will
        be returned.

        Args:
            flow_filter: filter criteria for flows
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            deployment_filter: filter criteria for deployments
            work_pool_filter: filter criteria for work pools
            work_queue_filter: filter criteria for work pool queues
            sort: sort criteria for the flows
            limit: limit for the flow query
            offset: offset for the flow query

        Returns:
            a list of Flow model representations of the flows
        """
        body = {
            "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True, exclude_unset=True)
                if flow_run_filter
                else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "deployments": (
                deployment_filter.dict(json_compatible=True)
                if deployment_filter
                else None
            ),
            "work_pools": (
                work_pool_filter.dict(json_compatible=True)
                if work_pool_filter
                else None
            ),
            "work_queues": (
                work_queue_filter.dict(json_compatible=True)
                if work_queue_filter
                else None
            ),
            "sort": sort,
            "limit": limit,
            "offset": offset,
        }

        response = await self._client.post("/flows/filter", json=body)
        return pydantic.parse_obj_as(List[Flow], response.json())

    async def read_flow_by_name(
        self,
        flow_name: str,
    ) -> Flow:
        """
        Query the Prefect API for a flow by name.

        Args:
            flow_name: the name of a flow

        Returns:
            a fully hydrated Flow model
        """
        response = await self._client.get(f"/flows/name/{flow_name}")
        return Flow.parse_obj(response.json())

    async def create_flow_run_from_deployment(
        self,
        deployment_id: UUID,
        *,
        parameters: Dict[str, Any] = None,
        context: dict = None,
        state: prefect.states.State = None,
        name: str = None,
        tags: Iterable[str] = None,
        idempotency_key: str = None,
        parent_task_run_id: UUID = None,
    ) -> FlowRun:
        """
        Create a flow run for a deployment.

        Args:
            deployment_id: The deployment ID to create the flow run from
            parameters: Parameter overrides for this flow run. Merged with the
                deployment defaults
            context: Optional run context data
            state: The initial state for the run. If not provided, defaults to
                `Scheduled` for now. Should always be a `Scheduled` type.
            name: An optional name for the flow run. If not provided, the server will
                generate a name.
            tags: An optional iterable of tags to apply to the flow run; these tags
                are merged with the deployment's tags.
            idempotency_key: Optional idempotency key for creation of the flow run.
                If the key matches the key of an existing flow run, the existing run will
                be returned instead of creating a new one.
            parent_task_run_id: if a subflow run is being created, the placeholder task
                run identifier in the parent flow

        Raises:
            httpx.RequestError: if the Prefect API does not successfully create a run for any reason

        Returns:
            The flow run model
        """
        parameters = parameters or {}
        context = context or {}
        state = state or prefect.states.Scheduled()
        tags = tags or []

        flow_run_create = DeploymentFlowRunCreate(
            parameters=parameters,
            context=context,
            state=state.to_state_create(),
            tags=tags,
            name=name,
            idempotency_key=idempotency_key,
            parent_task_run_id=parent_task_run_id,
        )

        response = await self._client.post(
            f"/deployments/{deployment_id}/create_flow_run",
            json=flow_run_create.dict(json_compatible=True),
        )
        return FlowRun.parse_obj(response.json())

    async def create_flow_run(
        self,
        flow: "FlowObject",
        name: str = None,
        parameters: Dict[str, Any] = None,
        context: dict = None,
        tags: Iterable[str] = None,
        parent_task_run_id: UUID = None,
        state: "prefect.states.State" = None,
    ) -> FlowRun:
        """
        Create a flow run for a flow.

        Args:
            flow: The flow model to create the flow run for
            name: An optional name for the flow run
            parameters: Parameter overrides for this flow run.
            context: Optional run context data
            tags: a list of tags to apply to this flow run
            parent_task_run_id: if a subflow run is being created, the placeholder task
                run identifier in the parent flow
            state: The initial state for the run. If not provided, defaults to
                `Scheduled` for now. Should always be a `Scheduled` type.

        Raises:
            httpx.RequestError: if the Prefect API does not successfully create a run for any reason

        Returns:
            The flow run model
        """
        parameters = parameters or {}
        context = context or {}

        if state is None:
            state = prefect.states.Pending()

        # Retrieve the flow id
        flow_id = await self.create_flow(flow)

        flow_run_create = FlowRunCreate(
            flow_id=flow_id,
            flow_version=flow.version,
            name=name,
            parameters=parameters,
            context=context,
            tags=list(tags or []),
            parent_task_run_id=parent_task_run_id,
            state=state.to_state_create(),
            empirical_policy=FlowRunPolicy(
                retries=flow.retries,
                retry_delay=flow.retry_delay_seconds,
            ),
        )

        flow_run_create_json = flow_run_create.dict(json_compatible=True)
        response = await self._client.post("/flow_runs/", json=flow_run_create_json)
        flow_run = FlowRun.parse_obj(response.json())

        # Restore the parameters to the local objects to retain expectations about
        # Python objects
        flow_run.parameters = parameters

        return flow_run

    async def update_flow_run(
        self,
        flow_run_id: UUID,
        flow_version: Optional[str] = None,
        parameters: Optional[dict] = None,
        name: Optional[str] = None,
        tags: Optional[Iterable[str]] = None,
        empirical_policy: Optional[FlowRunPolicy] = None,
        infrastructure_pid: Optional[str] = None,
    ) -> httpx.Response:
        """
        Update a flow run's details.

        Args:
            flow_run_id: The identifier for the flow run to update.
            flow_version: A new version string for the flow run.
            parameters: A dictionary of parameter values for the flow run. This will not
                be merged with any existing parameters.
            name: A new name for the flow run.
            empirical_policy: A new flow run orchestration policy. This will not be
                merged with any existing policy.
            tags: An iterable of new tags for the flow run. These will not be merged with
                any existing tags.
            infrastructure_pid: The id of flow run as returned by an
                infrastructure block.

        Returns:
            an `httpx.Response` object from the PATCH request
        """
        params = {}
        if flow_version is not None:
            params["flow_version"] = flow_version
        if parameters is not None:
            params["parameters"] = parameters
        if name is not None:
            params["name"] = name
        if tags is not None:
            params["tags"] = tags
        if empirical_policy is not None:
            params["empirical_policy"] = empirical_policy
        if infrastructure_pid:
            params["infrastructure_pid"] = infrastructure_pid

        flow_run_data = FlowRunUpdate(**params)

        return await self._client.patch(
            f"/flow_runs/{flow_run_id}",
            json=flow_run_data.dict(json_compatible=True, exclude_unset=True),
        )

    async def delete_flow_run(
        self,
        flow_run_id: UUID,
    ) -> None:
        """
        Delete a flow run by UUID.

        Args:
            flow_run_id: The flow run UUID of interest.
        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If requests fails
        """
        try:
            await self._client.delete(f"/flow_runs/{flow_run_id}"),
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def create_concurrency_limit(
        self,
        tag: str,
        concurrency_limit: int,
    ) -> UUID:
        """
        Create a tag concurrency limit in the Prefect API. These limits govern concurrently
        running tasks.

        Args:
            tag: a tag the concurrency limit is applied to
            concurrency_limit: the maximum number of concurrent task runs for a given tag

        Raises:
            httpx.RequestError: if the concurrency limit was not created for any reason

        Returns:
            the ID of the concurrency limit in the backend
        """

        concurrency_limit_create = ConcurrencyLimitCreate(
            tag=tag,
            concurrency_limit=concurrency_limit,
        )
        response = await self._client.post(
            "/concurrency_limits/",
            json=concurrency_limit_create.dict(json_compatible=True),
        )

        concurrency_limit_id = response.json().get("id")

        if not concurrency_limit_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        return UUID(concurrency_limit_id)

    async def read_concurrency_limit_by_tag(
        self,
        tag: str,
    ):
        """
        Read the concurrency limit set on a specific tag.

        Args:
            tag: a tag the concurrency limit is applied to

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: if the concurrency limit was not created for any reason

        Returns:
            the concurrency limit set on a specific tag
        """
        try:
            response = await self._client.get(
                f"/concurrency_limits/tag/{tag}",
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

        concurrency_limit_id = response.json().get("id")

        if not concurrency_limit_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        concurrency_limit = ConcurrencyLimit.parse_obj(response.json())
        return concurrency_limit

    async def read_concurrency_limits(
        self,
        limit: int,
        offset: int,
    ):
        """
        Lists concurrency limits set on task run tags.

        Args:
            limit: the maximum number of concurrency limits returned
            offset: the concurrency limit query offset

        Returns:
            a list of concurrency limits
        """

        body = {
            "limit": limit,
            "offset": offset,
        }

        response = await self._client.post("/concurrency_limits/filter", json=body)
        return pydantic.parse_obj_as(List[ConcurrencyLimit], response.json())

    async def reset_concurrency_limit_by_tag(
        self,
        tag: str,
        slot_override: Optional[List[Union[UUID, str]]] = None,
    ):
        """
        Resets the concurrency limit slots set on a specific tag.

        Args:
            tag: a tag the concurrency limit is applied to
            slot_override: a list of task run IDs that are currently using a
                concurrency slot, please check that any task run IDs included in
                `slot_override` are currently running, otherwise those concurrency
                slots will never be released.

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If request fails

        """
        if slot_override is not None:
            slot_override = [str(slot) for slot in slot_override]

        try:
            await self._client.post(
                f"/concurrency_limits/tag/{tag}/reset",
                json=dict(slot_override=slot_override),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def delete_concurrency_limit_by_tag(
        self,
        tag: str,
    ):
        """
        Delete the concurrency limit set on a specific tag.

        Args:
            tag: a tag the concurrency limit is applied to

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If request fails

        """
        try:
            await self._client.delete(
                f"/concurrency_limits/tag/{tag}",
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def create_work_queue(
        self,
        name: str,
        tags: Optional[List[str]] = None,
        description: Optional[str] = None,
        is_paused: Optional[bool] = None,
        concurrency_limit: Optional[int] = None,
        priority: Optional[int] = None,
        work_pool_name: Optional[str] = None,
    ) -> WorkQueue:
        """
        Create a work queue.

        Args:
            name: a unique name for the work queue
            tags: DEPRECATED: an optional list of tags to filter on; only work scheduled with these tags
                will be included in the queue. This option will be removed on 2023-02-23.
            description: An optional description for the work queue.
            is_paused: Whether or not the work queue is paused.
            concurrency_limit: An optional concurrency limit for the work queue.
            priority: The queue's priority. Lower values are higher priority (1 is the highest).
            work_pool_name: The name of the work pool to use for this queue.

        Raises:
            prefect.exceptions.ObjectAlreadyExists: If request returns 409
            httpx.RequestError: If request fails

        Returns:
            The created work queue
        """
        if tags:
            warnings.warn(
                (
                    "The use of tags for creating work queue filters is deprecated."
                    " This option will be removed on 2023-02-23."
                ),
                DeprecationWarning,
            )
            filter = QueueFilter(tags=tags)
        else:
            filter = None
        create_model = WorkQueueCreate(name=name, filter=filter)
        if description is not None:
            create_model.description = description
        if is_paused is not None:
            create_model.is_paused = is_paused
        if concurrency_limit is not None:
            create_model.concurrency_limit = concurrency_limit
        if priority is not None:
            create_model.priority = priority

        data = create_model.dict(json_compatible=True)
        try:
            if work_pool_name is not None:
                response = await self._client.post(
                    f"/work_pools/{work_pool_name}/queues", json=data
                )
            else:
                response = await self._client.post("/work_queues/", json=data)
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_409_CONFLICT:
                raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
            elif e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return WorkQueue.parse_obj(response.json())

    async def read_work_queue_by_name(
        self,
        name: str,
        work_pool_name: Optional[str] = None,
    ) -> WorkQueue:
        """
        Read a work queue by name.

        Args:
            name (str): a unique name for the work queue
            work_pool_name (str, optional): the name of the work pool
                the queue belongs to.

        Raises:
            prefect.exceptions.ObjectNotFound: if no work queue is found
            httpx.HTTPStatusError: other status errors

        Returns:
            WorkQueue: a work queue API object
        """
        try:
            if work_pool_name is not None:
                response = await self._client.get(
                    f"/work_pools/{work_pool_name}/queues/{name}"
                )
            else:
                response = await self._client.get(f"/work_queues/name/{name}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

        return WorkQueue.parse_obj(response.json())

    async def update_work_queue(self, id: UUID, **kwargs):
        """
        Update properties of a work queue.

        Args:
            id: the ID of the work queue to update
            **kwargs: the fields to update

        Raises:
            ValueError: if no kwargs are provided
            prefect.exceptions.ObjectNotFound: if request returns 404
            httpx.RequestError: if the request fails

        """
        if not kwargs:
            raise ValueError("No fields provided to update.")

        data = WorkQueueUpdate(**kwargs).dict(json_compatible=True, exclude_unset=True)
        try:
            await self._client.patch(f"/work_queues/{id}", json=data)
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def get_runs_in_work_queue(
        self,
        id: UUID,
        limit: int = 10,
        scheduled_before: datetime.datetime = None,
    ) -> List[FlowRun]:
        """
        Read flow runs off a work queue.

        Args:
            id: the id of the work queue to read from
            limit: a limit on the number of runs to return
            scheduled_before: a timestamp; only runs scheduled before this time will be returned.
                Defaults to now.

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If request fails

        Returns:
            List[FlowRun]: a list of FlowRun objects read from the queue
        """
        if scheduled_before is None:
            scheduled_before = pendulum.now()

        try:
            response = await self._client.post(
                f"/work_queues/{id}/get_runs",
                json={
                    "limit": limit,
                    "scheduled_before": scheduled_before.isoformat(),
                },
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return pydantic.parse_obj_as(List[FlowRun], response.json())

    async def read_work_queue(
        self,
        id: UUID,
    ) -> WorkQueue:
        """
        Read a work queue.

        Args:
            id: the id of the work queue to load

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If request fails

        Returns:
            WorkQueue: an instantiated WorkQueue object
        """
        try:
            response = await self._client.get(f"/work_queues/{id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return WorkQueue.parse_obj(response.json())

    async def match_work_queues(
        self,
        prefixes: List[str],
    ) -> List[WorkQueue]:
        """
        Query the Prefect API for work queues with names with a specific prefix.

        Args:
            prefixes: a list of strings used to match work queue name prefixes

        Returns:
            a list of WorkQueue model representations
                of the work queues
        """
        page_length = 100
        current_page = 0
        work_queues = []

        while True:
            new_queues = await self.read_work_queues(
                offset=current_page * page_length,
                limit=page_length,
                work_queue_filter=WorkQueueFilter(
                    name=WorkQueueFilterName(startswith_=prefixes)
                ),
            )
            if not new_queues:
                break
            work_queues += new_queues
            current_page += 1

        return work_queues

    async def delete_work_queue_by_id(
        self,
        id: UUID,
    ):
        """
        Delete a work queue by its ID.

        Args:
            id: the id of the work queue to delete

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If requests fails
        """
        try:
            await self._client.delete(
                f"/work_queues/{id}",
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def create_block_type(self, block_type: BlockTypeCreate) -> BlockType:
        """
        Create a block type in the Prefect API.
        """
        try:
            response = await self._client.post(
                "/block_types/",
                json=block_type.dict(
                    json_compatible=True, exclude_unset=True, exclude={"id"}
                ),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_409_CONFLICT:
                raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
            else:
                raise
        return BlockType.parse_obj(response.json())

    async def create_block_schema(self, block_schema: BlockSchemaCreate) -> BlockSchema:
        """
        Create a block schema in the Prefect API.
        """
        try:
            response = await self._client.post(
                "/block_schemas/",
                json=block_schema.dict(
                    json_compatible=True,
                    exclude_unset=True,
                    exclude={"id", "block_type", "checksum"},
                ),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_409_CONFLICT:
                raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
            else:
                raise
        return BlockSchema.parse_obj(response.json())

    async def create_block_document(
        self,
        block_document: Union[BlockDocument, BlockDocumentCreate],
        include_secrets: bool = True,
    ) -> BlockDocument:
        """
        Create a block document in the Prefect API. This data is used to configure a
        corresponding Block.

        Args:
            include_secrets (bool): whether to include secret values
                on the stored Block, corresponding to Pydantic's `SecretStr` and
                `SecretBytes` fields. Note Blocks may not work as expected if
                this is set to `False`.
        """
        if isinstance(block_document, BlockDocument):
            block_document = BlockDocumentCreate.parse_obj(
                block_document.dict(
                    json_compatible=True,
                    include_secrets=include_secrets,
                    exclude_unset=True,
                    exclude={"id", "block_schema", "block_type"},
                ),
            )

        try:
            response = await self._client.post(
                "/block_documents/",
                json=block_document.dict(
                    json_compatible=True,
                    include_secrets=include_secrets,
                    exclude_unset=True,
                    exclude={"id", "block_schema", "block_type"},
                ),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_409_CONFLICT:
                raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
            else:
                raise
        return BlockDocument.parse_obj(response.json())

    async def update_block_document(
        self,
        block_document_id: UUID,
        block_document: BlockDocumentUpdate,
    ):
        """
        Update a block document in the Prefect API.
        """
        try:
            await self._client.patch(
                f"/block_documents/{block_document_id}",
                json=block_document.dict(
                    json_compatible=True,
                    exclude_unset=True,
                    include={"data", "merge_existing_data", "block_schema_id"},
                    include_secrets=True,
                ),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def delete_block_document(self, block_document_id: UUID):
        """
        Delete a block document.
        """
        try:
            await self._client.delete(f"/block_documents/{block_document_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_block_type_by_slug(self, slug: str) -> BlockType:
        """
        Read a block type by its slug.
        """
        try:
            response = await self._client.get(f"/block_types/slug/{slug}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return BlockType.parse_obj(response.json())

    async def read_block_schema_by_checksum(
        self, checksum: str, version: Optional[str] = None
    ) -> BlockSchema:
        """
        Look up a block schema checksum
        """
        try:
            url = f"/block_schemas/checksum/{checksum}"
            if version is not None:
                url = f"{url}?version={version}"
            response = await self._client.get(url)
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return BlockSchema.parse_obj(response.json())

    async def update_block_type(self, block_type_id: UUID, block_type: BlockTypeUpdate):
        """
        Update a block document in the Prefect API.
        """
        try:
            await self._client.patch(
                f"/block_types/{block_type_id}",
                json=block_type.dict(
                    json_compatible=True,
                    exclude_unset=True,
                    include=BlockTypeUpdate.updatable_fields(),
                    include_secrets=True,
                ),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def delete_block_type(self, block_type_id: UUID):
        """
        Delete a block type.
        """
        try:
            await self._client.delete(f"/block_types/{block_type_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            elif (
                e.response.status_code == status.HTTP_403_FORBIDDEN
                and e.response.json()["detail"]
                == "protected block types cannot be deleted."
            ):
                raise prefect.exceptions.ProtectedBlockError(
                    "Protected block types cannot be deleted."
                ) from e
            else:
                raise

    async def read_block_types(self) -> List[BlockType]:
        """
        Read all block types
        Raises:
            httpx.RequestError: if the block types were not found

        Returns:
            List of BlockTypes.
        """
        response = await self._client.post("/block_types/filter", json={})
        return pydantic.parse_obj_as(List[BlockType], response.json())

    async def read_block_schemas(self) -> List[BlockSchema]:
        """
        Read all block schemas
        Raises:
            httpx.RequestError: if a valid block schema was not found

        Returns:
            A BlockSchema.
        """
        response = await self._client.post("/block_schemas/filter", json={})
        return pydantic.parse_obj_as(List[BlockSchema], response.json())

    async def read_block_document(
        self,
        block_document_id: UUID,
        include_secrets: bool = True,
    ):
        """
        Read the block document with the specified ID.

        Args:
            block_document_id: the block document id
            include_secrets (bool): whether to include secret values
                on the Block, corresponding to Pydantic's `SecretStr` and
                `SecretBytes` fields. These fields are automatically obfuscated
                by Pydantic, but users can additionally choose not to receive
                their values from the API. Note that any business logic on the
                Block may not work if this is `False`.

        Raises:
            httpx.RequestError: if the block document was not found for any reason

        Returns:
            A block document or None.
        """
        try:
            response = await self._client.get(
                f"/block_documents/{block_document_id}",
                params=dict(include_secrets=include_secrets),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return BlockDocument.parse_obj(response.json())

    async def read_block_document_by_name(
        self,
        name: str,
        block_type_slug: str,
        include_secrets: bool = True,
    ):
        """
        Read the block document with the specified name that corresponds to a
        specific block type name.

        Args:
            name: The block document name.
            block_type_slug: The block type slug.
            include_secrets (bool): whether to include secret values
                on the Block, corresponding to Pydantic's `SecretStr` and
                `SecretBytes` fields. These fields are automatically obfuscated
                by Pydantic, but users can additionally choose not to receive
                their values from the API. Note that any business logic on the
                Block may not work if this is `False`.

        Raises:
            httpx.RequestError: if the block document was not found for any reason

        Returns:
            A block document or None.
        """
        try:
            response = await self._client.get(
                f"/block_types/slug/{block_type_slug}/block_documents/name/{name}",
                params=dict(include_secrets=include_secrets),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return BlockDocument.parse_obj(response.json())

    async def read_block_documents(
        self,
        block_schema_type: Optional[str] = None,
        offset: Optional[int] = None,
        limit: Optional[int] = None,
        include_secrets: bool = True,
    ):
        """
        Read block documents

        Args:
            block_schema_type: an optional block schema type
            offset: an offset
            limit: the number of blocks to return
            include_secrets (bool): whether to include secret values
                on the Block, corresponding to Pydantic's `SecretStr` and
                `SecretBytes` fields. These fields are automatically obfuscated
                by Pydantic, but users can additionally choose not to receive
                their values from the API. Note that any business logic on the
                Block may not work if this is `False`.

        Returns:
            A list of block documents
        """
        response = await self._client.post(
            "/block_documents/filter",
            json=dict(
                block_schema_type=block_schema_type,
                offset=offset,
                limit=limit,
                include_secrets=include_secrets,
            ),
        )
        return pydantic.parse_obj_as(List[BlockDocument], response.json())

    async def create_deployment(
        self,
        flow_id: UUID,
        name: str,
        version: str = None,
        schedule: SCHEDULE_TYPES = None,
        parameters: Dict[str, Any] = None,
        description: str = None,
        work_queue_name: str = None,
        work_pool_name: str = None,
        tags: List[str] = None,
        storage_document_id: UUID = None,
        manifest_path: str = None,
        path: str = None,
        entrypoint: str = None,
        infrastructure_document_id: UUID = None,
        infra_overrides: Dict[str, Any] = None,
        parameter_openapi_schema: dict = None,
        is_schedule_active: Optional[bool] = None,
        pull_steps: Optional[List[dict]] = None,
    ) -> UUID:
        """
        Create a deployment.

        Args:
            flow_id: the flow ID to create a deployment for
            name: the name of the deployment
            version: an optional version string for the deployment
            schedule: an optional schedule to apply to the deployment
            tags: an optional list of tags to apply to the deployment
            storage_document_id: an reference to the storage block document
                used for the deployed flow
            infrastructure_document_id: an reference to the infrastructure block document
                to use for this deployment

        Raises:
            httpx.RequestError: if the deployment was not created for any reason

        Returns:
            the ID of the deployment in the backend
        """
        deployment_create = DeploymentCreate(
            flow_id=flow_id,
            name=name,
            version=version,
            schedule=schedule,
            parameters=dict(parameters or {}),
            tags=list(tags or []),
            work_queue_name=work_queue_name,
            description=description,
            storage_document_id=storage_document_id,
            path=path,
            entrypoint=entrypoint,
            manifest_path=manifest_path,  # for backwards compat
            infrastructure_document_id=infrastructure_document_id,
            infra_overrides=infra_overrides or {},
            parameter_openapi_schema=parameter_openapi_schema,
            is_schedule_active=is_schedule_active,
            pull_steps=pull_steps,
        )

        if work_pool_name is not None:
            deployment_create.work_pool_name = work_pool_name

        # Exclude newer fields that are not set to avoid compatibility issues
        exclude = {
            field
            for field in ["work_pool_name", "work_queue_name"]
            if field not in deployment_create.__fields_set__
        }

        if deployment_create.is_schedule_active is None:
            exclude.add("is_schedule_active")

        if deployment_create.pull_steps is None:
            exclude.add("pull_steps")

        json = deployment_create.dict(json_compatible=True, exclude=exclude)
        response = await self._client.post(
            "/deployments/",
            json=json,
        )
        deployment_id = response.json().get("id")
        if not deployment_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        return UUID(deployment_id)

    async def update_deployment(
        self,
        deployment: Deployment,
        schedule: SCHEDULE_TYPES = None,
        is_schedule_active: bool = None,
    ):
        deployment_update = DeploymentUpdate(
            version=deployment.version,
            schedule=schedule if schedule is not None else deployment.schedule,
            is_schedule_active=(
                is_schedule_active
                if is_schedule_active is not None
                else deployment.is_schedule_active
            ),
            description=deployment.description,
            work_queue_name=deployment.work_queue_name,
            tags=deployment.tags,
            manifest_path=deployment.manifest_path,
            path=deployment.path,
            entrypoint=deployment.entrypoint,
            parameters=deployment.parameters,
            storage_document_id=deployment.storage_document_id,
            infrastructure_document_id=deployment.infrastructure_document_id,
            infra_overrides=deployment.infra_overrides,
        )

        if getattr(deployment, "work_pool_name", None) is not None:
            deployment_update.work_pool_name = deployment.work_pool_name

        await self._client.patch(
            f"/deployments/{deployment.id}",
            json=deployment_update.dict(json_compatible=True),
        )

    async def _create_deployment_from_schema(self, schema: DeploymentCreate) -> UUID:
        """
        Create a deployment from a prepared `DeploymentCreate` schema.
        """
        # TODO: We are likely to remove this method once we have considered the
        #       packaging interface for deployments further.
        response = await self._client.post(
            "/deployments/", json=schema.dict(json_compatible=True)
        )
        deployment_id = response.json().get("id")
        if not deployment_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        return UUID(deployment_id)

    async def read_deployment(
        self,
        deployment_id: UUID,
    ) -> DeploymentResponse:
        """
        Query the Prefect API for a deployment by id.

        Args:
            deployment_id: the deployment ID of interest

        Returns:
            a [Deployment model][prefect.client.schemas.objects.Deployment] representation of the deployment
        """
        try:
            response = await self._client.get(f"/deployments/{deployment_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return DeploymentResponse.parse_obj(response.json())

    async def read_deployment_by_name(
        self,
        name: str,
    ) -> DeploymentResponse:
        """
        Query the Prefect API for a deployment by name.

        Args:
            name: A deployed flow's name: <FLOW_NAME>/<DEPLOYMENT_NAME>

        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If request fails

        Returns:
            a Deployment model representation of the deployment
        """
        try:
            response = await self._client.get(f"/deployments/name/{name}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

        return DeploymentResponse.parse_obj(response.json())

    async def read_deployments(
        self,
        *,
        flow_filter: FlowFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        deployment_filter: DeploymentFilter = None,
        work_pool_filter: WorkPoolFilter = None,
        work_queue_filter: WorkQueueFilter = None,
        limit: int = None,
        sort: DeploymentSort = None,
        offset: int = 0,
    ) -> List[DeploymentResponse]:
        """
        Query the Prefect API for deployments. Only deployments matching all
        the provided criteria will be returned.

        Args:
            flow_filter: filter criteria for flows
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            deployment_filter: filter criteria for deployments
            work_pool_filter: filter criteria for work pools
            work_queue_filter: filter criteria for work pool queues
            limit: a limit for the deployment query
            offset: an offset for the deployment query

        Returns:
            a list of Deployment model representations
                of the deployments
        """
        body = {
            "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True, exclude_unset=True)
                if flow_run_filter
                else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "deployments": (
                deployment_filter.dict(json_compatible=True)
                if deployment_filter
                else None
            ),
            "work_pools": (
                work_pool_filter.dict(json_compatible=True)
                if work_pool_filter
                else None
            ),
            "work_pool_queues": (
                work_queue_filter.dict(json_compatible=True)
                if work_queue_filter
                else None
            ),
            "limit": limit,
            "offset": offset,
            "sort": sort,
        }

        response = await self._client.post("/deployments/filter", json=body)
        return pydantic.parse_obj_as(List[DeploymentResponse], response.json())

    async def delete_deployment(
        self,
        deployment_id: UUID,
    ):
        """
        Delete deployment by id.

        Args:
            deployment_id: The deployment id of interest.
        Raises:
            prefect.exceptions.ObjectNotFound: If request returns 404
            httpx.RequestError: If requests fails
        """
        try:
            await self._client.delete(f"/deployments/{deployment_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_flow_run(self, flow_run_id: UUID) -> FlowRun:
        """
        Query the Prefect API for a flow run by id.

        Args:
            flow_run_id: the flow run ID of interest

        Returns:
            a Flow Run model representation of the flow run
        """
        try:
            response = await self._client.get(f"/flow_runs/{flow_run_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
        return FlowRun.parse_obj(response.json())

    async def resume_flow_run(self, flow_run_id: UUID) -> OrchestrationResult:
        """
        Resumes a paused flow run.

        Args:
            flow_run_id: the flow run ID of interest

        Returns:
            an OrchestrationResult model representation of state orchestration output
        """
        try:
            response = await self._client.post(f"/flow_runs/{flow_run_id}/resume")
        except httpx.HTTPStatusError:
            raise

        return OrchestrationResult.parse_obj(response.json())

    async def read_flow_runs(
        self,
        *,
        flow_filter: FlowFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        deployment_filter: DeploymentFilter = None,
        work_pool_filter: WorkPoolFilter = None,
        work_queue_filter: WorkQueueFilter = None,
        sort: FlowRunSort = None,
        limit: int = None,
        offset: int = 0,
    ) -> List[FlowRun]:
        """
        Query the Prefect API for flow runs. Only flow runs matching all criteria will
        be returned.

        Args:
            flow_filter: filter criteria for flows
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            deployment_filter: filter criteria for deployments
            work_pool_filter: filter criteria for work pools
            work_queue_filter: filter criteria for work pool queues
            sort: sort criteria for the flow runs
            limit: limit for the flow run query
            offset: offset for the flow run query

        Returns:
            a list of Flow Run model representations
                of the flow runs
        """
        body = {
            "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True, exclude_unset=True)
                if flow_run_filter
                else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "deployments": (
                deployment_filter.dict(json_compatible=True)
                if deployment_filter
                else None
            ),
            "work_pools": (
                work_pool_filter.dict(json_compatible=True)
                if work_pool_filter
                else None
            ),
            "work_pool_queues": (
                work_queue_filter.dict(json_compatible=True)
                if work_queue_filter
                else None
            ),
            "sort": sort,
            "limit": limit,
            "offset": offset,
        }

        response = await self._client.post("/flow_runs/filter", json=body)
        return pydantic.parse_obj_as(List[FlowRun], response.json())

    async def set_flow_run_state(
        self,
        flow_run_id: UUID,
        state: "prefect.states.State",
        force: bool = False,
    ) -> OrchestrationResult:
        """
        Set the state of a flow run.

        Args:
            flow_run_id: the id of the flow run
            state: the state to set
            force: if True, disregard orchestration logic when setting the state,
                forcing the Prefect API to accept the state

        Returns:
            an OrchestrationResult model representation of state orchestration output
        """
        state_create = state.to_state_create()
        state_create.state_details.flow_run_id = flow_run_id
        try:
            response = await self._client.post(
                f"/flow_runs/{flow_run_id}/set_state",
                json=dict(state=state_create.dict(json_compatible=True), force=force),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

        return OrchestrationResult.parse_obj(response.json())

    async def read_flow_run_states(
        self, flow_run_id: UUID
    ) -> List[prefect.states.State]:
        """
        Query for the states of a flow run

        Args:
            flow_run_id: the id of the flow run

        Returns:
            a list of State model representations
                of the flow run states
        """
        response = await self._client.get(
            "/flow_run_states/", params=dict(flow_run_id=str(flow_run_id))
        )
        return pydantic.parse_obj_as(List[prefect.states.State], response.json())

    async def set_task_run_name(self, task_run_id: UUID, name: str):
        task_run_data = TaskRunUpdate(name=name)
        return await self._client.patch(
            f"/task_runs/{task_run_id}",
            json=task_run_data.dict(json_compatible=True, exclude_unset=True),
        )

    async def create_task_run(
        self,
        task: "TaskObject",
        flow_run_id: UUID,
        dynamic_key: str,
        name: str = None,
        extra_tags: Iterable[str] = None,
        state: prefect.states.State = None,
        task_inputs: Dict[
            str,
            List[
                Union[
                    TaskRunResult,
                    Parameter,
                    Constant,
                ]
            ],
        ] = None,
    ) -> TaskRun:
        """
        Create a task run

        Args:
            task: The Task to run
            flow_run_id: The flow run id with which to associate the task run
            dynamic_key: A key unique to this particular run of a Task within the flow
            name: An optional name for the task run
            extra_tags: an optional list of extra tags to apply to the task run in
                addition to `task.tags`
            state: The initial state for the run. If not provided, defaults to
                `Pending` for now. Should always be a `Scheduled` type.
            task_inputs: the set of inputs passed to the task

        Returns:
            The created task run.
        """
        tags = set(task.tags).union(extra_tags or [])

        if state is None:
            state = prefect.states.Pending()

        task_run_data = TaskRunCreate(
            name=name,
            flow_run_id=flow_run_id,
            task_key=task.task_key,
            dynamic_key=dynamic_key,
            tags=list(tags),
            task_version=task.version,
            empirical_policy=TaskRunPolicy(
                retries=task.retries,
                retry_delay=task.retry_delay_seconds,
                retry_jitter_factor=task.retry_jitter_factor,
            ),
            state=state.to_state_create(),
            task_inputs=task_inputs or {},
        )

        response = await self._client.post(
            "/task_runs/", json=task_run_data.dict(json_compatible=True)
        )
        return TaskRun.parse_obj(response.json())

    async def read_task_run(self, task_run_id: UUID) -> TaskRun:
        """
        Query the Prefect API for a task run by id.

        Args:
            task_run_id: the task run ID of interest

        Returns:
            a Task Run model representation of the task run
        """
        response = await self._client.get(f"/task_runs/{task_run_id}")
        return TaskRun.parse_obj(response.json())

    async def read_task_runs(
        self,
        *,
        flow_filter: FlowFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        deployment_filter: DeploymentFilter = None,
        sort: TaskRunSort = None,
        limit: int = None,
        offset: int = 0,
    ) -> List[TaskRun]:
        """
        Query the Prefect API for task runs. Only task runs matching all criteria will
        be returned.

        Args:
            flow_filter: filter criteria for flows
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            deployment_filter: filter criteria for deployments
            sort: sort criteria for the task runs
            limit: a limit for the task run query
            offset: an offset for the task run query

        Returns:
            a list of Task Run model representations
                of the task runs
        """
        body = {
            "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True, exclude_unset=True)
                if flow_run_filter
                else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "deployments": (
                deployment_filter.dict(json_compatible=True)
                if deployment_filter
                else None
            ),
            "sort": sort,
            "limit": limit,
            "offset": offset,
        }
        response = await self._client.post("/task_runs/filter", json=body)
        return pydantic.parse_obj_as(List[TaskRun], response.json())

    async def set_task_run_state(
        self,
        task_run_id: UUID,
        state: prefect.states.State,
        force: bool = False,
    ) -> OrchestrationResult:
        """
        Set the state of a task run.

        Args:
            task_run_id: the id of the task run
            state: the state to set
            force: if True, disregard orchestration logic when setting the state,
                forcing the Prefect API to accept the state

        Returns:
            an OrchestrationResult model representation of state orchestration output
        """
        state_create = state.to_state_create()
        state_create.state_details.task_run_id = task_run_id
        response = await self._client.post(
            f"/task_runs/{task_run_id}/set_state",
            json=dict(state=state_create.dict(json_compatible=True), force=force),
        )
        return OrchestrationResult.parse_obj(response.json())

    async def read_task_run_states(
        self, task_run_id: UUID
    ) -> List[prefect.states.State]:
        """
        Query for the states of a task run

        Args:
            task_run_id: the id of the task run

        Returns:
            a list of State model representations of the task run states
        """
        response = await self._client.get(
            "/task_run_states/", params=dict(task_run_id=str(task_run_id))
        )
        return pydantic.parse_obj_as(List[prefect.states.State], response.json())

    async def create_logs(self, logs: Iterable[Union[LogCreate, dict]]) -> None:
        """
        Create logs for a flow or task run

        Args:
            logs: An iterable of `LogCreate` objects or already json-compatible dicts
        """
        serialized_logs = [
            log.dict(json_compatible=True) if isinstance(log, LogCreate) else log
            for log in logs
        ]
        await self._client.post("/logs/", json=serialized_logs)

    async def create_flow_run_notification_policy(
        self,
        block_document_id: UUID,
        is_active: bool = True,
        tags: List[str] = None,
        state_names: List[str] = None,
        message_template: Optional[str] = None,
    ) -> UUID:
        """
        Create a notification policy for flow runs

        Args:
            block_document_id: The block document UUID
            is_active: Whether the notification policy is active
            tags: List of flow tags
            state_names: List of state names
            message_template: Notification message template
        """
        if tags is None:
            tags = []
        if state_names is None:
            state_names = []

        policy = FlowRunNotificationPolicyCreate(
            block_document_id=block_document_id,
            is_active=is_active,
            tags=tags,
            state_names=state_names,
            message_template=message_template,
        )
        response = await self._client.post(
            "/flow_run_notification_policies/",
            json=policy.dict(json_compatible=True),
        )

        policy_id = response.json().get("id")
        if not policy_id:
            raise httpx.RequestError(f"Malformed response: {response}")

        return UUID(policy_id)

    async def read_flow_run_notification_policies(
        self,
        flow_run_notification_policy_filter: FlowRunNotificationPolicyFilter,
        limit: Optional[int] = None,
        offset: int = 0,
    ) -> List[FlowRunNotificationPolicy]:
        """
        Query the Prefect API for flow run notification policies. Only policies matching all criteria will
        be returned.

        Args:
            flow_run_notification_policy_filter: filter criteria for notification policies
            limit: a limit for the notification policies query
            offset: an offset for the notification policies query

        Returns:
            a list of FlowRunNotificationPolicy model representations
                of the notification policies
        """
        body = {
            "flow_run_notification_policy_filter": (
                flow_run_notification_policy_filter.dict(json_compatible=True)
                if flow_run_notification_policy_filter
                else None
            ),
            "limit": limit,
            "offset": offset,
        }
        response = await self._client.post(
            "/flow_run_notification_policies/filter", json=body
        )
        return pydantic.parse_obj_as(List[FlowRunNotificationPolicy], response.json())

    async def read_logs(
        self,
        log_filter: LogFilter = None,
        limit: int = None,
        offset: int = None,
        sort: LogSort = LogSort.TIMESTAMP_ASC,
    ) -> None:
        """
        Read flow and task run logs.
        """
        body = {
            "logs": log_filter.dict(json_compatible=True) if log_filter else None,
            "limit": limit,
            "offset": offset,
            "sort": sort,
        }

        response = await self._client.post("/logs/filter", json=body)
        return pydantic.parse_obj_as(List[Log], response.json())

    async def resolve_datadoc(self, datadoc: DataDocument) -> Any:
        """
        Recursively decode possibly nested data documents.

        "server" encoded documents will be retrieved from the server.

        Args:
            datadoc: The data document to resolve

        Returns:
            a decoded object, the innermost data
        """
        if not isinstance(datadoc, DataDocument):
            raise TypeError(
                f"`resolve_datadoc` received invalid type {type(datadoc).__name__}"
            )

        async def resolve_inner(data):
            if isinstance(data, bytes):
                try:
                    data = DataDocument.parse_raw(data)
                except pydantic.ValidationError:
                    return data

            if isinstance(data, DataDocument):
                return await resolve_inner(data.decode())

            return data

        return await resolve_inner(datadoc)

    async def send_worker_heartbeat(self, work_pool_name: str, worker_name: str):
        """
        Sends a worker heartbeat for a given work pool.

        Args:
            work_pool_name: The name of the work pool to heartbeat against.
            worker_name: The name of the worker sending the heartbeat.
        """
        await self._client.post(
            f"/work_pools/{work_pool_name}/workers/heartbeat",
            json={"name": worker_name},
        )

    async def read_workers_for_work_pool(
        self,
        work_pool_name: str,
        worker_filter: Optional[WorkerFilter] = None,
        offset: Optional[int] = None,
        limit: Optional[int] = None,
    ) -> List[Worker]:
        """
        Reads workers for a given work pool.

        Args:
            work_pool_name: The name of the work pool for which to get
                member workers.
            worker_filter: Criteria by which to filter workers.
            limit: Limit for the worker query.
            offset: Limit for the worker query.
        """
        response = await self._client.post(
            f"/work_pools/{work_pool_name}/workers/filter",
            json={
                "worker_filter": (
                    worker_filter.dict(json_compatible=True, exclude_unset=True)
                    if worker_filter
                    else None
                ),
                "offset": offset,
                "limit": limit,
            },
        )

        return pydantic.parse_obj_as(List[Worker], response.json())

    async def read_work_pool(self, work_pool_name: str) -> WorkPool:
        """
        Reads information for a given work pool

        Args:
            work_pool_name: The name of the work pool to for which to get
                information.

        Returns:
            Information about the requested work pool.
        """
        try:
            response = await self._client.get(f"/work_pools/{work_pool_name}")
            return pydantic.parse_obj_as(WorkPool, response.json())
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_work_pools(
        self,
        limit: Optional[int] = None,
        offset: int = 0,
        work_pool_filter: Optional[WorkPoolFilter] = None,
    ) -> List[WorkPool]:
        """
        Reads work pools.

        Args:
            limit: Limit for the work pool query.
            offset: Offset for the work pool query.
            work_pool_filter: Criteria by which to filter work pools.

        Returns:
            A list of work pools.
        """

        body = {
            "limit": limit,
            "offset": offset,
            "work_pools": (
                work_pool_filter.dict(json_compatible=True)
                if work_pool_filter
                else None
            ),
        }
        response = await self._client.post("/work_pools/filter", json=body)
        return pydantic.parse_obj_as(List[WorkPool], response.json())

    async def create_work_pool(
        self,
        work_pool: WorkPoolCreate,
    ) -> WorkPool:
        """
        Creates a work pool with the provided configuration.

        Args:
            work_pool: Desired configuration for the new work pool.

        Returns:
            Information about the newly created work pool.
        """
        try:
            response = await self._client.post(
                "/work_pools/",
                json=work_pool.dict(json_compatible=True, exclude_unset=True),
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_409_CONFLICT:
                raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
            else:
                raise

        return pydantic.parse_obj_as(WorkPool, response.json())

    async def update_work_pool(
        self,
        work_pool_name: str,
        work_pool: WorkPoolUpdate,
    ):
        await self._client.patch(
            f"/work_pools/{work_pool_name}",
            json=work_pool.dict(json_compatible=True, exclude_unset=True),
        )

    async def delete_work_pool(
        self,
        work_pool_name: str,
    ):
        """
        Deletes a work pool.

        Args:
            work_pool_name: Name of the work pool to delete.
        """
        try:
            await self._client.delete(f"/work_pools/{work_pool_name}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_work_queues(
        self,
        work_pool_name: Optional[str] = None,
        work_queue_filter: Optional[WorkQueueFilter] = None,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
    ) -> List[WorkQueue]:
        """
        Retrieves queues for a work pool.

        Args:
            work_pool_name: Name of the work pool for which to get queues.
            work_queue_filter: Criteria by which to filter queues.
            limit: Limit for the queue query.
            offset: Limit for the queue query.

        Returns:
            List of queues for the specified work pool.
        """
        json = {
            "work_queues": (
                work_queue_filter.dict(json_compatible=True, exclude_unset=True)
                if work_queue_filter
                else None
            ),
            "limit": limit,
            "offset": offset,
        }

        if work_pool_name:
            try:
                response = await self._client.post(
                    f"/work_pools/{work_pool_name}/queues/filter",
                    json=json,
                )
            except httpx.HTTPStatusError as e:
                if e.response.status_code == status.HTTP_404_NOT_FOUND:
                    raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
                else:
                    raise
        else:
            response = await self._client.post("/work_queues/filter", json=json)

        return pydantic.parse_obj_as(List[WorkQueue], response.json())

    async def get_scheduled_flow_runs_for_work_pool(
        self,
        work_pool_name: str,
        work_queue_names: Optional[List[str]] = None,
        scheduled_before: Optional[datetime.datetime] = None,
    ) -> List[WorkerFlowRunResponse]:
        """
        Retrieves scheduled flow runs for the provided set of work pool queues.

        Args:
            work_pool_name: The name of the work pool that the work pool
                queues are associated with.
            work_queue_names: The names of the work pool queues from which
                to get scheduled flow runs.
            scheduled_before: Datetime used to filter returned flow runs. Flow runs
                scheduled for after the given datetime string will not be returned.

        Returns:
            A list of worker flow run responses containing information about the
            retrieved flow runs.
        """
        body: Dict[str, Any] = {}
        if work_queue_names is not None:
            body["work_queue_names"] = list(work_queue_names)
        if scheduled_before:
            body["scheduled_before"] = str(scheduled_before)

        response = await self._client.post(
            f"/work_pools/{work_pool_name}/get_scheduled_flow_runs",
            json=body,
        )

        return pydantic.parse_obj_as(List[WorkerFlowRunResponse], response.json())

    async def create_artifact(
        self,
        artifact: ArtifactCreate,
    ) -> Artifact:
        """
        Creates an artifact with the provided configuration.

        Args:
            artifact: Desired configuration for the new artifact.
        Returns:
            Information about the newly created artifact.
        """

        response = await self._client.post(
            "/artifacts/",
            json=artifact.dict(json_compatible=True, exclude_unset=True),
        )

        return pydantic.parse_obj_as(Artifact, response.json())

    async def read_artifacts(
        self,
        *,
        artifact_filter: ArtifactFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        sort: ArtifactSort = None,
        limit: int = None,
        offset: int = 0,
    ) -> List[Artifact]:
        """
        Query the Prefect API for artifacts. Only artifacts matching all criteria will
        be returned.
        Args:
            artifact_filter: filter criteria for artifacts
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            sort: sort criteria for the artifacts
            limit: limit for the artifact query
            offset: offset for the artifact query
        Returns:
            a list of Artifact model representations of the artifacts
        """
        body = {
            "artifacts": (
                artifact_filter.dict(json_compatible=True) if artifact_filter else None
            ),
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True) if flow_run_filter else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "sort": sort,
            "limit": limit,
            "offset": offset,
        }
        response = await self._client.post("/artifacts/filter", json=body)
        return pydantic.parse_obj_as(List[Artifact], response.json())

    async def read_latest_artifacts(
        self,
        *,
        artifact_filter: ArtifactCollectionFilter = None,
        flow_run_filter: FlowRunFilter = None,
        task_run_filter: TaskRunFilter = None,
        sort: ArtifactCollectionSort = None,
        limit: int = None,
        offset: int = 0,
    ) -> List[ArtifactCollection]:
        """
        Query the Prefect API for artifacts. Only artifacts matching all criteria will
        be returned.
        Args:
            artifact_filter: filter criteria for artifacts
            flow_run_filter: filter criteria for flow runs
            task_run_filter: filter criteria for task runs
            sort: sort criteria for the artifacts
            limit: limit for the artifact query
            offset: offset for the artifact query
        Returns:
            a list of Artifact model representations of the artifacts
        """
        body = {
            "artifacts": (
                artifact_filter.dict(json_compatible=True) if artifact_filter else None
            ),
            "flow_runs": (
                flow_run_filter.dict(json_compatible=True) if flow_run_filter else None
            ),
            "task_runs": (
                task_run_filter.dict(json_compatible=True) if task_run_filter else None
            ),
            "sort": sort,
            "limit": limit,
            "offset": offset,
        }
        response = await self._client.post("/artifacts/latest/filter", json=body)
        return pydantic.parse_obj_as(List[ArtifactCollection], response.json())

    async def delete_artifact(self, artifact_id: UUID) -> None:
        """
        Deletes an artifact with the provided id.

        Args:
            artifact_id: The id of the artifact to delete.
        """
        try:
            await self._client.delete(f"/artifacts/{artifact_id}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_variable_by_name(self, name: str) -> Optional[Variable]:
        """Reads a variable by name. Returns None if no variable is found."""
        try:
            response = await self._client.get(f"/variables/name/{name}")
            return pydantic.parse_obj_as(Variable, response.json())
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                return None
            else:
                raise

    async def delete_variable_by_name(self, name: str):
        """Deletes a variable by name."""
        try:
            await self._client.delete(f"/variables/name/{name}")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 404:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise

    async def read_variables(self, limit: int = None) -> List[Variable]:
        """Reads all variables."""
        response = await self._client.post("/variables/filter", json={"limit": limit})
        return pydantic.parse_obj_as(List[Variable], response.json())

    async def read_worker_metadata(self) -> Dict[str, Any]:
        """Reads worker metadata stored in Prefect collection registry."""
        response = await self._client.get("collections/views/aggregate-worker-metadata")
        response.raise_for_status()
        return response.json()

    async def create_automation(self, automation: Automation) -> UUID:
        """Creates an automation in Prefect Cloud."""
        if self.server_type != ServerType.CLOUD:
            raise RuntimeError("Automations are only supported for Prefect Cloud.")

        response = await self._client.post(
            "/automations/",
            json=automation.dict(json_compatible=True),
        )

        return UUID(response.json()["id"])

    async def read_resource_related_automations(
        self, resource_id: str
    ) -> List[ExistingAutomation]:
        if self.server_type != ServerType.CLOUD:
            raise RuntimeError("Automations are only supported for Prefect Cloud.")

        response = await self._client.get(f"/automations/related-to/{resource_id}")
        response.raise_for_status()
        return pydantic.parse_obj_as(List[ExistingAutomation], response.json())

    async def delete_resource_owned_automations(self, resource_id: str):
        if self.server_type != ServerType.CLOUD:
            raise RuntimeError("Automations are only supported for Prefect Cloud.")

        await self._client.delete(f"/automations/owned-by/{resource_id}")

    async def __aenter__(self):
        """
        Start the client.

        If the client is already started, this will raise an exception.

        If the client is already closed, this will raise an exception. Use a new client
        instance instead.
        """
        if self._closed:
            # httpx.AsyncClient does not allow reuse so we will not either.
            raise RuntimeError(
                "The client cannot be started again after closing. "
                "Retrieve a new client with `get_client()` instead."
            )

        if self._started:
            # httpx.AsyncClient does not allow reentrancy so we will not either.
            raise RuntimeError("The client cannot be started more than once.")

        self._loop = asyncio.get_running_loop()
        await self._exit_stack.__aenter__()

        # Enter a lifespan context if using an ephemeral application.
        # See https://github.com/encode/httpx/issues/350
        if self._ephemeral_app and self.manage_lifespan:
            self._ephemeral_lifespan = await self._exit_stack.enter_async_context(
                app_lifespan_context(self._ephemeral_app)
            )

        if self._ephemeral_app:
            self.logger.debug(
                "Using ephemeral application with database at "
                f"{PREFECT_API_DATABASE_CONNECTION_URL.value()}"
            )
        else:
            self.logger.debug(f"Connecting to API at {self.api_url}")

        # Enter the httpx client's context
        await self._exit_stack.enter_async_context(self._client)

        self._started = True

        return self

    async def __aexit__(self, *exc_info):
        """
        Shutdown the client.
        """
        self._closed = True
        return await self._exit_stack.__aexit__(*exc_info)

    def __enter__(self):
        raise RuntimeError(
            "The `PrefectClient` must be entered with an async context. Use 'async "
            "with PrefectClient(...)' not 'with PrefectClient(...)'"
        )

    def __exit__(self, *_):
        assert False, "This should never be called but must be defined for __enter__"

api_url: httpx.URL property

Get the base URL for the API.

api_healthcheck async

Attempts to connect to the API and returns the encountered exception if not successful.

If successful, returns None.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
319
320
321
322
323
324
325
326
327
328
329
330
async def api_healthcheck(self) -> Optional[Exception]:
    """
    Attempts to connect to the API and returns the encountered exception if not
    successful.

    If successful, returns `None`.
    """
    try:
        await self._client.get("/health")
        return None
    except Exception as exc:
        return exc

hello async

Send a GET request to /hello for testing purposes.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
332
333
334
335
336
async def hello(self) -> httpx.Response:
    """
    Send a GET request to /hello for testing purposes.
    """
    return await self._client.get("/hello")

create_flow async

Create a flow in the Prefect API.

Parameters:

Name Type Description Default
flow FlowObject

a Flow object

required

Raises:

Type Description
httpx.RequestError

if a flow was not created for any reason

Returns:

Type Description
UUID

the ID of the flow in the backend

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
async def create_flow(self, flow: "FlowObject") -> UUID:
    """
    Create a flow in the Prefect API.

    Args:
        flow: a [Flow][prefect.flows.Flow] object

    Raises:
        httpx.RequestError: if a flow was not created for any reason

    Returns:
        the ID of the flow in the backend
    """
    return await self.create_flow_from_name(flow.name)

create_flow_from_name async

Create a flow in the Prefect API.

Parameters:

Name Type Description Default
flow_name str

the name of the new flow

required

Raises:

Type Description
httpx.RequestError

if a flow was not created for any reason

Returns:

Type Description
UUID

the ID of the flow in the backend

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
async def create_flow_from_name(self, flow_name: str) -> UUID:
    """
    Create a flow in the Prefect API.

    Args:
        flow_name: the name of the new flow

    Raises:
        httpx.RequestError: if a flow was not created for any reason

    Returns:
        the ID of the flow in the backend
    """
    flow_data = FlowCreate(name=flow_name)
    response = await self._client.post(
        "/flows/", json=flow_data.dict(json_compatible=True)
    )

    flow_id = response.json().get("id")
    if not flow_id:
        raise httpx.RequestError(f"Malformed response: {response}")

    # Return the id of the created flow
    return UUID(flow_id)

read_flow async

Query the Prefect API for a flow by id.

Parameters:

Name Type Description Default
flow_id UUID

the flow ID of interest

required

Returns:

Type Description
Flow

a [Flow model][prefect.client.schemas.objects.Flow] representation of the flow

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
378
379
380
381
382
383
384
385
386
387
388
389
async def read_flow(self, flow_id: UUID) -> Flow:
    """
    Query the Prefect API for a flow by id.

    Args:
        flow_id: the flow ID of interest

    Returns:
        a [Flow model][prefect.client.schemas.objects.Flow] representation of the flow
    """
    response = await self._client.get(f"/flows/{flow_id}")
    return Flow.parse_obj(response.json())

read_flows async

Query the Prefect API for flows. Only flows matching all criteria will be returned.

Parameters:

Name Type Description Default
flow_filter FlowFilter

filter criteria for flows

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
deployment_filter DeploymentFilter

filter criteria for deployments

None
work_pool_filter WorkPoolFilter

filter criteria for work pools

None
work_queue_filter WorkQueueFilter

filter criteria for work pool queues

None
sort FlowSort

sort criteria for the flows

None
limit int

limit for the flow query

None
offset int

offset for the flow query

0

Returns:

Type Description
List[Flow]

a list of Flow model representations of the flows

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_flows(
    self,
    *,
    flow_filter: FlowFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    deployment_filter: DeploymentFilter = None,
    work_pool_filter: WorkPoolFilter = None,
    work_queue_filter: WorkQueueFilter = None,
    sort: FlowSort = None,
    limit: int = None,
    offset: int = 0,
) -> List[Flow]:
    """
    Query the Prefect API for flows. Only flows matching all criteria will
    be returned.

    Args:
        flow_filter: filter criteria for flows
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        deployment_filter: filter criteria for deployments
        work_pool_filter: filter criteria for work pools
        work_queue_filter: filter criteria for work pool queues
        sort: sort criteria for the flows
        limit: limit for the flow query
        offset: offset for the flow query

    Returns:
        a list of Flow model representations of the flows
    """
    body = {
        "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True, exclude_unset=True)
            if flow_run_filter
            else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "deployments": (
            deployment_filter.dict(json_compatible=True)
            if deployment_filter
            else None
        ),
        "work_pools": (
            work_pool_filter.dict(json_compatible=True)
            if work_pool_filter
            else None
        ),
        "work_queues": (
            work_queue_filter.dict(json_compatible=True)
            if work_queue_filter
            else None
        ),
        "sort": sort,
        "limit": limit,
        "offset": offset,
    }

    response = await self._client.post("/flows/filter", json=body)
    return pydantic.parse_obj_as(List[Flow], response.json())

read_flow_by_name async

Query the Prefect API for a flow by name.

Parameters:

Name Type Description Default
flow_name str

the name of a flow

required

Returns:

Type Description
Flow

a fully hydrated Flow model

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
async def read_flow_by_name(
    self,
    flow_name: str,
) -> Flow:
    """
    Query the Prefect API for a flow by name.

    Args:
        flow_name: the name of a flow

    Returns:
        a fully hydrated Flow model
    """
    response = await self._client.get(f"/flows/name/{flow_name}")
    return Flow.parse_obj(response.json())

create_flow_run_from_deployment async

Create a flow run for a deployment.

Parameters:

Name Type Description Default
deployment_id UUID

The deployment ID to create the flow run from

required
parameters Dict[str, Any]

Parameter overrides for this flow run. Merged with the deployment defaults

None
context dict

Optional run context data

None
state prefect.states.State

The initial state for the run. If not provided, defaults to Scheduled for now. Should always be a Scheduled type.

None
name str

An optional name for the flow run. If not provided, the server will generate a name.

None
tags Iterable[str]

An optional iterable of tags to apply to the flow run; these tags are merged with the deployment's tags.

None
idempotency_key str

Optional idempotency key for creation of the flow run. If the key matches the key of an existing flow run, the existing run will be returned instead of creating a new one.

None
parent_task_run_id UUID

if a subflow run is being created, the placeholder task run identifier in the parent flow

None

Raises:

Type Description
httpx.RequestError

if the Prefect API does not successfully create a run for any reason

Returns:

Type Description
FlowRun

The flow run model

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_flow_run_from_deployment(
    self,
    deployment_id: UUID,
    *,
    parameters: Dict[str, Any] = None,
    context: dict = None,
    state: prefect.states.State = None,
    name: str = None,
    tags: Iterable[str] = None,
    idempotency_key: str = None,
    parent_task_run_id: UUID = None,
) -> FlowRun:
    """
    Create a flow run for a deployment.

    Args:
        deployment_id: The deployment ID to create the flow run from
        parameters: Parameter overrides for this flow run. Merged with the
            deployment defaults
        context: Optional run context data
        state: The initial state for the run. If not provided, defaults to
            `Scheduled` for now. Should always be a `Scheduled` type.
        name: An optional name for the flow run. If not provided, the server will
            generate a name.
        tags: An optional iterable of tags to apply to the flow run; these tags
            are merged with the deployment's tags.
        idempotency_key: Optional idempotency key for creation of the flow run.
            If the key matches the key of an existing flow run, the existing run will
            be returned instead of creating a new one.
        parent_task_run_id: if a subflow run is being created, the placeholder task
            run identifier in the parent flow

    Raises:
        httpx.RequestError: if the Prefect API does not successfully create a run for any reason

    Returns:
        The flow run model
    """
    parameters = parameters or {}
    context = context or {}
    state = state or prefect.states.Scheduled()
    tags = tags or []

    flow_run_create = DeploymentFlowRunCreate(
        parameters=parameters,
        context=context,
        state=state.to_state_create(),
        tags=tags,
        name=name,
        idempotency_key=idempotency_key,
        parent_task_run_id=parent_task_run_id,
    )

    response = await self._client.post(
        f"/deployments/{deployment_id}/create_flow_run",
        json=flow_run_create.dict(json_compatible=True),
    )
    return FlowRun.parse_obj(response.json())

create_flow_run async

Create a flow run for a flow.

Parameters:

Name Type Description Default
flow FlowObject

The flow model to create the flow run for

required
name str

An optional name for the flow run

None
parameters Dict[str, Any]

Parameter overrides for this flow run.

None
context dict

Optional run context data

None
tags Iterable[str]

a list of tags to apply to this flow run

None
parent_task_run_id UUID

if a subflow run is being created, the placeholder task run identifier in the parent flow

None
state prefect.states.State

The initial state for the run. If not provided, defaults to Scheduled for now. Should always be a Scheduled type.

None

Raises:

Type Description
httpx.RequestError

if the Prefect API does not successfully create a run for any reason

Returns:

Type Description
FlowRun

The flow run model

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_flow_run(
    self,
    flow: "FlowObject",
    name: str = None,
    parameters: Dict[str, Any] = None,
    context: dict = None,
    tags: Iterable[str] = None,
    parent_task_run_id: UUID = None,
    state: "prefect.states.State" = None,
) -> FlowRun:
    """
    Create a flow run for a flow.

    Args:
        flow: The flow model to create the flow run for
        name: An optional name for the flow run
        parameters: Parameter overrides for this flow run.
        context: Optional run context data
        tags: a list of tags to apply to this flow run
        parent_task_run_id: if a subflow run is being created, the placeholder task
            run identifier in the parent flow
        state: The initial state for the run. If not provided, defaults to
            `Scheduled` for now. Should always be a `Scheduled` type.

    Raises:
        httpx.RequestError: if the Prefect API does not successfully create a run for any reason

    Returns:
        The flow run model
    """
    parameters = parameters or {}
    context = context or {}

    if state is None:
        state = prefect.states.Pending()

    # Retrieve the flow id
    flow_id = await self.create_flow(flow)

    flow_run_create = FlowRunCreate(
        flow_id=flow_id,
        flow_version=flow.version,
        name=name,
        parameters=parameters,
        context=context,
        tags=list(tags or []),
        parent_task_run_id=parent_task_run_id,
        state=state.to_state_create(),
        empirical_policy=FlowRunPolicy(
            retries=flow.retries,
            retry_delay=flow.retry_delay_seconds,
        ),
    )

    flow_run_create_json = flow_run_create.dict(json_compatible=True)
    response = await self._client.post("/flow_runs/", json=flow_run_create_json)
    flow_run = FlowRun.parse_obj(response.json())

    # Restore the parameters to the local objects to retain expectations about
    # Python objects
    flow_run.parameters = parameters

    return flow_run

update_flow_run async

Update a flow run's details.

Parameters:

Name Type Description Default
flow_run_id UUID

The identifier for the flow run to update.

required
flow_version Optional[str]

A new version string for the flow run.

None
parameters Optional[dict]

A dictionary of parameter values for the flow run. This will not be merged with any existing parameters.

None
name Optional[str]

A new name for the flow run.

None
empirical_policy Optional[FlowRunPolicy]

A new flow run orchestration policy. This will not be merged with any existing policy.

None
tags Optional[Iterable[str]]

An iterable of new tags for the flow run. These will not be merged with any existing tags.

None
infrastructure_pid Optional[str]

The id of flow run as returned by an infrastructure block.

None

Returns:

Type Description
httpx.Response

an httpx.Response object from the PATCH request

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def update_flow_run(
    self,
    flow_run_id: UUID,
    flow_version: Optional[str] = None,
    parameters: Optional[dict] = None,
    name: Optional[str] = None,
    tags: Optional[Iterable[str]] = None,
    empirical_policy: Optional[FlowRunPolicy] = None,
    infrastructure_pid: Optional[str] = None,
) -> httpx.Response:
    """
    Update a flow run's details.

    Args:
        flow_run_id: The identifier for the flow run to update.
        flow_version: A new version string for the flow run.
        parameters: A dictionary of parameter values for the flow run. This will not
            be merged with any existing parameters.
        name: A new name for the flow run.
        empirical_policy: A new flow run orchestration policy. This will not be
            merged with any existing policy.
        tags: An iterable of new tags for the flow run. These will not be merged with
            any existing tags.
        infrastructure_pid: The id of flow run as returned by an
            infrastructure block.

    Returns:
        an `httpx.Response` object from the PATCH request
    """
    params = {}
    if flow_version is not None:
        params["flow_version"] = flow_version
    if parameters is not None:
        params["parameters"] = parameters
    if name is not None:
        params["name"] = name
    if tags is not None:
        params["tags"] = tags
    if empirical_policy is not None:
        params["empirical_policy"] = empirical_policy
    if infrastructure_pid:
        params["infrastructure_pid"] = infrastructure_pid

    flow_run_data = FlowRunUpdate(**params)

    return await self._client.patch(
        f"/flow_runs/{flow_run_id}",
        json=flow_run_data.dict(json_compatible=True, exclude_unset=True),
    )

delete_flow_run async

Delete a flow run by UUID.

Parameters:

Name Type Description Default
flow_run_id UUID

The flow run UUID of interest.

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If requests fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
async def delete_flow_run(
    self,
    flow_run_id: UUID,
) -> None:
    """
    Delete a flow run by UUID.

    Args:
        flow_run_id: The flow run UUID of interest.
    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If requests fails
    """
    try:
        await self._client.delete(f"/flow_runs/{flow_run_id}"),
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

create_concurrency_limit async

Create a tag concurrency limit in the Prefect API. These limits govern concurrently running tasks.

Parameters:

Name Type Description Default
tag str

a tag the concurrency limit is applied to

required
concurrency_limit int

the maximum number of concurrent task runs for a given tag

required

Raises:

Type Description
httpx.RequestError

if the concurrency limit was not created for any reason

Returns:

Type Description
UUID

the ID of the concurrency limit in the backend

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_concurrency_limit(
    self,
    tag: str,
    concurrency_limit: int,
) -> UUID:
    """
    Create a tag concurrency limit in the Prefect API. These limits govern concurrently
    running tasks.

    Args:
        tag: a tag the concurrency limit is applied to
        concurrency_limit: the maximum number of concurrent task runs for a given tag

    Raises:
        httpx.RequestError: if the concurrency limit was not created for any reason

    Returns:
        the ID of the concurrency limit in the backend
    """

    concurrency_limit_create = ConcurrencyLimitCreate(
        tag=tag,
        concurrency_limit=concurrency_limit,
    )
    response = await self._client.post(
        "/concurrency_limits/",
        json=concurrency_limit_create.dict(json_compatible=True),
    )

    concurrency_limit_id = response.json().get("id")

    if not concurrency_limit_id:
        raise httpx.RequestError(f"Malformed response: {response}")

    return UUID(concurrency_limit_id)

read_concurrency_limit_by_tag async

Read the concurrency limit set on a specific tag.

Parameters:

Name Type Description Default
tag str

a tag the concurrency limit is applied to

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

if the concurrency limit was not created for any reason

Returns:

Type Description

the concurrency limit set on a specific tag

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_concurrency_limit_by_tag(
    self,
    tag: str,
):
    """
    Read the concurrency limit set on a specific tag.

    Args:
        tag: a tag the concurrency limit is applied to

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: if the concurrency limit was not created for any reason

    Returns:
        the concurrency limit set on a specific tag
    """
    try:
        response = await self._client.get(
            f"/concurrency_limits/tag/{tag}",
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

    concurrency_limit_id = response.json().get("id")

    if not concurrency_limit_id:
        raise httpx.RequestError(f"Malformed response: {response}")

    concurrency_limit = ConcurrencyLimit.parse_obj(response.json())
    return concurrency_limit

read_concurrency_limits async

Lists concurrency limits set on task run tags.

Parameters:

Name Type Description Default
limit int

the maximum number of concurrency limits returned

required
offset int

the concurrency limit query offset

required

Returns:

Type Description

a list of concurrency limits

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
async def read_concurrency_limits(
    self,
    limit: int,
    offset: int,
):
    """
    Lists concurrency limits set on task run tags.

    Args:
        limit: the maximum number of concurrency limits returned
        offset: the concurrency limit query offset

    Returns:
        a list of concurrency limits
    """

    body = {
        "limit": limit,
        "offset": offset,
    }

    response = await self._client.post("/concurrency_limits/filter", json=body)
    return pydantic.parse_obj_as(List[ConcurrencyLimit], response.json())

reset_concurrency_limit_by_tag async

Resets the concurrency limit slots set on a specific tag.

Parameters:

Name Type Description Default
tag str

a tag the concurrency limit is applied to

required
slot_override Optional[List[Union[UUID, str]]]

a list of task run IDs that are currently using a concurrency slot, please check that any task run IDs included in slot_override are currently running, otherwise those concurrency slots will never be released.

None

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If request fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def reset_concurrency_limit_by_tag(
    self,
    tag: str,
    slot_override: Optional[List[Union[UUID, str]]] = None,
):
    """
    Resets the concurrency limit slots set on a specific tag.

    Args:
        tag: a tag the concurrency limit is applied to
        slot_override: a list of task run IDs that are currently using a
            concurrency slot, please check that any task run IDs included in
            `slot_override` are currently running, otherwise those concurrency
            slots will never be released.

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If request fails

    """
    if slot_override is not None:
        slot_override = [str(slot) for slot in slot_override]

    try:
        await self._client.post(
            f"/concurrency_limits/tag/{tag}/reset",
            json=dict(slot_override=slot_override),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

delete_concurrency_limit_by_tag async

Delete the concurrency limit set on a specific tag.

Parameters:

Name Type Description Default
tag str

a tag the concurrency limit is applied to

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If request fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
async def delete_concurrency_limit_by_tag(
    self,
    tag: str,
):
    """
    Delete the concurrency limit set on a specific tag.

    Args:
        tag: a tag the concurrency limit is applied to

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If request fails

    """
    try:
        await self._client.delete(
            f"/concurrency_limits/tag/{tag}",
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

create_work_queue async

Create a work queue.

Parameters:

Name Type Description Default
name str

a unique name for the work queue

required
tags Optional[List[str]]

will be included in the queue. This option will be removed on 2023-02-23.

None
description Optional[str]

An optional description for the work queue.

None
is_paused Optional[bool]

Whether or not the work queue is paused.

None
concurrency_limit Optional[int]

An optional concurrency limit for the work queue.

None
priority Optional[int]

The queue's priority. Lower values are higher priority (1 is the highest).

None
work_pool_name Optional[str]

The name of the work pool to use for this queue.

None

Raises:

Type Description
prefect.exceptions.ObjectAlreadyExists

If request returns 409

httpx.RequestError

If request fails

Returns:

Type Description
WorkQueue

The created work queue

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_work_queue(
    self,
    name: str,
    tags: Optional[List[str]] = None,
    description: Optional[str] = None,
    is_paused: Optional[bool] = None,
    concurrency_limit: Optional[int] = None,
    priority: Optional[int] = None,
    work_pool_name: Optional[str] = None,
) -> WorkQueue:
    """
    Create a work queue.

    Args:
        name: a unique name for the work queue
        tags: DEPRECATED: an optional list of tags to filter on; only work scheduled with these tags
            will be included in the queue. This option will be removed on 2023-02-23.
        description: An optional description for the work queue.
        is_paused: Whether or not the work queue is paused.
        concurrency_limit: An optional concurrency limit for the work queue.
        priority: The queue's priority. Lower values are higher priority (1 is the highest).
        work_pool_name: The name of the work pool to use for this queue.

    Raises:
        prefect.exceptions.ObjectAlreadyExists: If request returns 409
        httpx.RequestError: If request fails

    Returns:
        The created work queue
    """
    if tags:
        warnings.warn(
            (
                "The use of tags for creating work queue filters is deprecated."
                " This option will be removed on 2023-02-23."
            ),
            DeprecationWarning,
        )
        filter = QueueFilter(tags=tags)
    else:
        filter = None
    create_model = WorkQueueCreate(name=name, filter=filter)
    if description is not None:
        create_model.description = description
    if is_paused is not None:
        create_model.is_paused = is_paused
    if concurrency_limit is not None:
        create_model.concurrency_limit = concurrency_limit
    if priority is not None:
        create_model.priority = priority

    data = create_model.dict(json_compatible=True)
    try:
        if work_pool_name is not None:
            response = await self._client.post(
                f"/work_pools/{work_pool_name}/queues", json=data
            )
        else:
            response = await self._client.post("/work_queues/", json=data)
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_409_CONFLICT:
            raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
        elif e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return WorkQueue.parse_obj(response.json())

read_work_queue_by_name async

Read a work queue by name.

Parameters:

Name Type Description Default
name str

a unique name for the work queue

required
work_pool_name str

the name of the work pool the queue belongs to.

None

Raises:

Type Description
prefect.exceptions.ObjectNotFound

if no work queue is found

httpx.HTTPStatusError

other status errors

Returns:

Name Type Description
WorkQueue WorkQueue

a work queue API object

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_work_queue_by_name(
    self,
    name: str,
    work_pool_name: Optional[str] = None,
) -> WorkQueue:
    """
    Read a work queue by name.

    Args:
        name (str): a unique name for the work queue
        work_pool_name (str, optional): the name of the work pool
            the queue belongs to.

    Raises:
        prefect.exceptions.ObjectNotFound: if no work queue is found
        httpx.HTTPStatusError: other status errors

    Returns:
        WorkQueue: a work queue API object
    """
    try:
        if work_pool_name is not None:
            response = await self._client.get(
                f"/work_pools/{work_pool_name}/queues/{name}"
            )
        else:
            response = await self._client.get(f"/work_queues/name/{name}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

    return WorkQueue.parse_obj(response.json())

update_work_queue async

Update properties of a work queue.

Parameters:

Name Type Description Default
id UUID

the ID of the work queue to update

required
**kwargs

the fields to update

{}

Raises:

Type Description
ValueError

if no kwargs are provided

prefect.exceptions.ObjectNotFound

if request returns 404

httpx.RequestError

if the request fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def update_work_queue(self, id: UUID, **kwargs):
    """
    Update properties of a work queue.

    Args:
        id: the ID of the work queue to update
        **kwargs: the fields to update

    Raises:
        ValueError: if no kwargs are provided
        prefect.exceptions.ObjectNotFound: if request returns 404
        httpx.RequestError: if the request fails

    """
    if not kwargs:
        raise ValueError("No fields provided to update.")

    data = WorkQueueUpdate(**kwargs).dict(json_compatible=True, exclude_unset=True)
    try:
        await self._client.patch(f"/work_queues/{id}", json=data)
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

get_runs_in_work_queue async

Read flow runs off a work queue.

Parameters:

Name Type Description Default
id UUID

the id of the work queue to read from

required
limit int

a limit on the number of runs to return

10
scheduled_before datetime.datetime

a timestamp; only runs scheduled before this time will be returned. Defaults to now.

None

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If request fails

Returns:

Type Description
List[FlowRun]

List[FlowRun]: a list of FlowRun objects read from the queue

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def get_runs_in_work_queue(
    self,
    id: UUID,
    limit: int = 10,
    scheduled_before: datetime.datetime = None,
) -> List[FlowRun]:
    """
    Read flow runs off a work queue.

    Args:
        id: the id of the work queue to read from
        limit: a limit on the number of runs to return
        scheduled_before: a timestamp; only runs scheduled before this time will be returned.
            Defaults to now.

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If request fails

    Returns:
        List[FlowRun]: a list of FlowRun objects read from the queue
    """
    if scheduled_before is None:
        scheduled_before = pendulum.now()

    try:
        response = await self._client.post(
            f"/work_queues/{id}/get_runs",
            json={
                "limit": limit,
                "scheduled_before": scheduled_before.isoformat(),
            },
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return pydantic.parse_obj_as(List[FlowRun], response.json())

read_work_queue async

Read a work queue.

Parameters:

Name Type Description Default
id UUID

the id of the work queue to load

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If request fails

Returns:

Name Type Description
WorkQueue WorkQueue

an instantiated WorkQueue object

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
 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
async def read_work_queue(
    self,
    id: UUID,
) -> WorkQueue:
    """
    Read a work queue.

    Args:
        id: the id of the work queue to load

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If request fails

    Returns:
        WorkQueue: an instantiated WorkQueue object
    """
    try:
        response = await self._client.get(f"/work_queues/{id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return WorkQueue.parse_obj(response.json())

match_work_queues async

Query the Prefect API for work queues with names with a specific prefix.

Parameters:

Name Type Description Default
prefixes List[str]

a list of strings used to match work queue name prefixes

required

Returns:

Type Description
List[WorkQueue]

a list of WorkQueue model representations of the work queues

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def match_work_queues(
    self,
    prefixes: List[str],
) -> List[WorkQueue]:
    """
    Query the Prefect API for work queues with names with a specific prefix.

    Args:
        prefixes: a list of strings used to match work queue name prefixes

    Returns:
        a list of WorkQueue model representations
            of the work queues
    """
    page_length = 100
    current_page = 0
    work_queues = []

    while True:
        new_queues = await self.read_work_queues(
            offset=current_page * page_length,
            limit=page_length,
            work_queue_filter=WorkQueueFilter(
                name=WorkQueueFilterName(startswith_=prefixes)
            ),
        )
        if not new_queues:
            break
        work_queues += new_queues
        current_page += 1

    return work_queues

delete_work_queue_by_id async

Delete a work queue by its ID.

Parameters:

Name Type Description Default
id UUID

the id of the work queue to delete

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If requests fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
async def delete_work_queue_by_id(
    self,
    id: UUID,
):
    """
    Delete a work queue by its ID.

    Args:
        id: the id of the work queue to delete

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If requests fails
    """
    try:
        await self._client.delete(
            f"/work_queues/{id}",
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

create_block_type async

Create a block type in the Prefect API.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
async def create_block_type(self, block_type: BlockTypeCreate) -> BlockType:
    """
    Create a block type in the Prefect API.
    """
    try:
        response = await self._client.post(
            "/block_types/",
            json=block_type.dict(
                json_compatible=True, exclude_unset=True, exclude={"id"}
            ),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_409_CONFLICT:
            raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
        else:
            raise
    return BlockType.parse_obj(response.json())

create_block_schema async

Create a block schema in the Prefect API.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
async def create_block_schema(self, block_schema: BlockSchemaCreate) -> BlockSchema:
    """
    Create a block schema in the Prefect API.
    """
    try:
        response = await self._client.post(
            "/block_schemas/",
            json=block_schema.dict(
                json_compatible=True,
                exclude_unset=True,
                exclude={"id", "block_type", "checksum"},
            ),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_409_CONFLICT:
            raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
        else:
            raise
    return BlockSchema.parse_obj(response.json())

create_block_document async

Create a block document in the Prefect API. This data is used to configure a corresponding Block.

Parameters:

Name Type Description Default
include_secrets bool

whether to include secret values on the stored Block, corresponding to Pydantic's SecretStr and SecretBytes fields. Note Blocks may not work as expected if this is set to False.

True
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_block_document(
    self,
    block_document: Union[BlockDocument, BlockDocumentCreate],
    include_secrets: bool = True,
) -> BlockDocument:
    """
    Create a block document in the Prefect API. This data is used to configure a
    corresponding Block.

    Args:
        include_secrets (bool): whether to include secret values
            on the stored Block, corresponding to Pydantic's `SecretStr` and
            `SecretBytes` fields. Note Blocks may not work as expected if
            this is set to `False`.
    """
    if isinstance(block_document, BlockDocument):
        block_document = BlockDocumentCreate.parse_obj(
            block_document.dict(
                json_compatible=True,
                include_secrets=include_secrets,
                exclude_unset=True,
                exclude={"id", "block_schema", "block_type"},
            ),
        )

    try:
        response = await self._client.post(
            "/block_documents/",
            json=block_document.dict(
                json_compatible=True,
                include_secrets=include_secrets,
                exclude_unset=True,
                exclude={"id", "block_schema", "block_type"},
            ),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_409_CONFLICT:
            raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
        else:
            raise
    return BlockDocument.parse_obj(response.json())

update_block_document async

Update a block document in the Prefect API.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
async def update_block_document(
    self,
    block_document_id: UUID,
    block_document: BlockDocumentUpdate,
):
    """
    Update a block document in the Prefect API.
    """
    try:
        await self._client.patch(
            f"/block_documents/{block_document_id}",
            json=block_document.dict(
                json_compatible=True,
                exclude_unset=True,
                include={"data", "merge_existing_data", "block_schema_id"},
                include_secrets=True,
            ),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

delete_block_document async

Delete a block document.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
async def delete_block_document(self, block_document_id: UUID):
    """
    Delete a block document.
    """
    try:
        await self._client.delete(f"/block_documents/{block_document_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_block_type_by_slug async

Read a block type by its slug.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
async def read_block_type_by_slug(self, slug: str) -> BlockType:
    """
    Read a block type by its slug.
    """
    try:
        response = await self._client.get(f"/block_types/slug/{slug}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return BlockType.parse_obj(response.json())

read_block_schema_by_checksum async

Look up a block schema checksum

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
async def read_block_schema_by_checksum(
    self, checksum: str, version: Optional[str] = None
) -> BlockSchema:
    """
    Look up a block schema checksum
    """
    try:
        url = f"/block_schemas/checksum/{checksum}"
        if version is not None:
            url = f"{url}?version={version}"
        response = await self._client.get(url)
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return BlockSchema.parse_obj(response.json())

update_block_type async

Update a block document in the Prefect API.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
async def update_block_type(self, block_type_id: UUID, block_type: BlockTypeUpdate):
    """
    Update a block document in the Prefect API.
    """
    try:
        await self._client.patch(
            f"/block_types/{block_type_id}",
            json=block_type.dict(
                json_compatible=True,
                exclude_unset=True,
                include=BlockTypeUpdate.updatable_fields(),
                include_secrets=True,
            ),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

delete_block_type async

Delete a block type.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
async def delete_block_type(self, block_type_id: UUID):
    """
    Delete a block type.
    """
    try:
        await self._client.delete(f"/block_types/{block_type_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        elif (
            e.response.status_code == status.HTTP_403_FORBIDDEN
            and e.response.json()["detail"]
            == "protected block types cannot be deleted."
        ):
            raise prefect.exceptions.ProtectedBlockError(
                "Protected block types cannot be deleted."
            ) from e
        else:
            raise

read_block_types async

Read all block types

Raises:

Type Description
httpx.RequestError

if the block types were not found

Returns:

Type Description
List[BlockType]

List of BlockTypes.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
async def read_block_types(self) -> List[BlockType]:
    """
    Read all block types
    Raises:
        httpx.RequestError: if the block types were not found

    Returns:
        List of BlockTypes.
    """
    response = await self._client.post("/block_types/filter", json={})
    return pydantic.parse_obj_as(List[BlockType], response.json())

read_block_schemas async

Read all block schemas

Raises:

Type Description
httpx.RequestError

if a valid block schema was not found

Returns:

Type Description
List[BlockSchema]

A BlockSchema.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
async def read_block_schemas(self) -> List[BlockSchema]:
    """
    Read all block schemas
    Raises:
        httpx.RequestError: if a valid block schema was not found

    Returns:
        A BlockSchema.
    """
    response = await self._client.post("/block_schemas/filter", json={})
    return pydantic.parse_obj_as(List[BlockSchema], response.json())

read_block_document async

Read the block document with the specified ID.

Parameters:

Name Type Description Default
block_document_id UUID

the block document id

required
include_secrets bool

whether to include secret values on the Block, corresponding to Pydantic's SecretStr and SecretBytes fields. These fields are automatically obfuscated by Pydantic, but users can additionally choose not to receive their values from the API. Note that any business logic on the Block may not work if this is False.

True

Raises:

Type Description
httpx.RequestError

if the block document was not found for any reason

Returns:

Type Description

A block document or None.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_block_document(
    self,
    block_document_id: UUID,
    include_secrets: bool = True,
):
    """
    Read the block document with the specified ID.

    Args:
        block_document_id: the block document id
        include_secrets (bool): whether to include secret values
            on the Block, corresponding to Pydantic's `SecretStr` and
            `SecretBytes` fields. These fields are automatically obfuscated
            by Pydantic, but users can additionally choose not to receive
            their values from the API. Note that any business logic on the
            Block may not work if this is `False`.

    Raises:
        httpx.RequestError: if the block document was not found for any reason

    Returns:
        A block document or None.
    """
    try:
        response = await self._client.get(
            f"/block_documents/{block_document_id}",
            params=dict(include_secrets=include_secrets),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return BlockDocument.parse_obj(response.json())

read_block_document_by_name async

Read the block document with the specified name that corresponds to a specific block type name.

Parameters:

Name Type Description Default
name str

The block document name.

required
block_type_slug str

The block type slug.

required
include_secrets bool

whether to include secret values on the Block, corresponding to Pydantic's SecretStr and SecretBytes fields. These fields are automatically obfuscated by Pydantic, but users can additionally choose not to receive their values from the API. Note that any business logic on the Block may not work if this is False.

True

Raises:

Type Description
httpx.RequestError

if the block document was not found for any reason

Returns:

Type Description

A block document or None.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_block_document_by_name(
    self,
    name: str,
    block_type_slug: str,
    include_secrets: bool = True,
):
    """
    Read the block document with the specified name that corresponds to a
    specific block type name.

    Args:
        name: The block document name.
        block_type_slug: The block type slug.
        include_secrets (bool): whether to include secret values
            on the Block, corresponding to Pydantic's `SecretStr` and
            `SecretBytes` fields. These fields are automatically obfuscated
            by Pydantic, but users can additionally choose not to receive
            their values from the API. Note that any business logic on the
            Block may not work if this is `False`.

    Raises:
        httpx.RequestError: if the block document was not found for any reason

    Returns:
        A block document or None.
    """
    try:
        response = await self._client.get(
            f"/block_types/slug/{block_type_slug}/block_documents/name/{name}",
            params=dict(include_secrets=include_secrets),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return BlockDocument.parse_obj(response.json())

read_block_documents async

Read block documents

Parameters:

Name Type Description Default
block_schema_type Optional[str]

an optional block schema type

None
offset Optional[int]

an offset

None
limit Optional[int]

the number of blocks to return

None
include_secrets bool

whether to include secret values on the Block, corresponding to Pydantic's SecretStr and SecretBytes fields. These fields are automatically obfuscated by Pydantic, but users can additionally choose not to receive their values from the API. Note that any business logic on the Block may not work if this is False.

True

Returns:

Type Description

A list of block documents

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_block_documents(
    self,
    block_schema_type: Optional[str] = None,
    offset: Optional[int] = None,
    limit: Optional[int] = None,
    include_secrets: bool = True,
):
    """
    Read block documents

    Args:
        block_schema_type: an optional block schema type
        offset: an offset
        limit: the number of blocks to return
        include_secrets (bool): whether to include secret values
            on the Block, corresponding to Pydantic's `SecretStr` and
            `SecretBytes` fields. These fields are automatically obfuscated
            by Pydantic, but users can additionally choose not to receive
            their values from the API. Note that any business logic on the
            Block may not work if this is `False`.

    Returns:
        A list of block documents
    """
    response = await self._client.post(
        "/block_documents/filter",
        json=dict(
            block_schema_type=block_schema_type,
            offset=offset,
            limit=limit,
            include_secrets=include_secrets,
        ),
    )
    return pydantic.parse_obj_as(List[BlockDocument], response.json())

create_deployment async

Create a deployment.

Parameters:

Name Type Description Default
flow_id UUID

the flow ID to create a deployment for

required
name str

the name of the deployment

required
version str

an optional version string for the deployment

None
schedule SCHEDULE_TYPES

an optional schedule to apply to the deployment

None
tags List[str]

an optional list of tags to apply to the deployment

None
storage_document_id UUID

an reference to the storage block document used for the deployed flow

None
infrastructure_document_id UUID

an reference to the infrastructure block document to use for this deployment

None

Raises:

Type Description
httpx.RequestError

if the deployment was not created for any reason

Returns:

Type Description
UUID

the ID of the deployment in the backend

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_deployment(
    self,
    flow_id: UUID,
    name: str,
    version: str = None,
    schedule: SCHEDULE_TYPES = None,
    parameters: Dict[str, Any] = None,
    description: str = None,
    work_queue_name: str = None,
    work_pool_name: str = None,
    tags: List[str] = None,
    storage_document_id: UUID = None,
    manifest_path: str = None,
    path: str = None,
    entrypoint: str = None,
    infrastructure_document_id: UUID = None,
    infra_overrides: Dict[str, Any] = None,
    parameter_openapi_schema: dict = None,
    is_schedule_active: Optional[bool] = None,
    pull_steps: Optional[List[dict]] = None,
) -> UUID:
    """
    Create a deployment.

    Args:
        flow_id: the flow ID to create a deployment for
        name: the name of the deployment
        version: an optional version string for the deployment
        schedule: an optional schedule to apply to the deployment
        tags: an optional list of tags to apply to the deployment
        storage_document_id: an reference to the storage block document
            used for the deployed flow
        infrastructure_document_id: an reference to the infrastructure block document
            to use for this deployment

    Raises:
        httpx.RequestError: if the deployment was not created for any reason

    Returns:
        the ID of the deployment in the backend
    """
    deployment_create = DeploymentCreate(
        flow_id=flow_id,
        name=name,
        version=version,
        schedule=schedule,
        parameters=dict(parameters or {}),
        tags=list(tags or []),
        work_queue_name=work_queue_name,
        description=description,
        storage_document_id=storage_document_id,
        path=path,
        entrypoint=entrypoint,
        manifest_path=manifest_path,  # for backwards compat
        infrastructure_document_id=infrastructure_document_id,
        infra_overrides=infra_overrides or {},
        parameter_openapi_schema=parameter_openapi_schema,
        is_schedule_active=is_schedule_active,
        pull_steps=pull_steps,
    )

    if work_pool_name is not None:
        deployment_create.work_pool_name = work_pool_name

    # Exclude newer fields that are not set to avoid compatibility issues
    exclude = {
        field
        for field in ["work_pool_name", "work_queue_name"]
        if field not in deployment_create.__fields_set__
    }

    if deployment_create.is_schedule_active is None:
        exclude.add("is_schedule_active")

    if deployment_create.pull_steps is None:
        exclude.add("pull_steps")

    json = deployment_create.dict(json_compatible=True, exclude=exclude)
    response = await self._client.post(
        "/deployments/",
        json=json,
    )
    deployment_id = response.json().get("id")
    if not deployment_id:
        raise httpx.RequestError(f"Malformed response: {response}")

    return UUID(deployment_id)

read_deployment async

Query the Prefect API for a deployment by id.

Parameters:

Name Type Description Default
deployment_id UUID

the deployment ID of interest

required

Returns:

Type Description
DeploymentResponse

a [Deployment model][prefect.client.schemas.objects.Deployment] representation of the deployment

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
async def read_deployment(
    self,
    deployment_id: UUID,
) -> DeploymentResponse:
    """
    Query the Prefect API for a deployment by id.

    Args:
        deployment_id: the deployment ID of interest

    Returns:
        a [Deployment model][prefect.client.schemas.objects.Deployment] representation of the deployment
    """
    try:
        response = await self._client.get(f"/deployments/{deployment_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return DeploymentResponse.parse_obj(response.json())

read_deployment_by_name async

Query the Prefect API for a deployment by name.

Parameters:

Name Type Description Default
name str

A deployed flow's name: /

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If request fails

Returns:

Type Description
DeploymentResponse

a Deployment model representation of the deployment

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_deployment_by_name(
    self,
    name: str,
) -> DeploymentResponse:
    """
    Query the Prefect API for a deployment by name.

    Args:
        name: A deployed flow's name: <FLOW_NAME>/<DEPLOYMENT_NAME>

    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If request fails

    Returns:
        a Deployment model representation of the deployment
    """
    try:
        response = await self._client.get(f"/deployments/name/{name}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

    return DeploymentResponse.parse_obj(response.json())

read_deployments async

Query the Prefect API for deployments. Only deployments matching all the provided criteria will be returned.

Parameters:

Name Type Description Default
flow_filter FlowFilter

filter criteria for flows

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
deployment_filter DeploymentFilter

filter criteria for deployments

None
work_pool_filter WorkPoolFilter

filter criteria for work pools

None
work_queue_filter WorkQueueFilter

filter criteria for work pool queues

None
limit int

a limit for the deployment query

None
offset int

an offset for the deployment query

0

Returns:

Type Description
List[DeploymentResponse]

a list of Deployment model representations of the deployments

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_deployments(
    self,
    *,
    flow_filter: FlowFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    deployment_filter: DeploymentFilter = None,
    work_pool_filter: WorkPoolFilter = None,
    work_queue_filter: WorkQueueFilter = None,
    limit: int = None,
    sort: DeploymentSort = None,
    offset: int = 0,
) -> List[DeploymentResponse]:
    """
    Query the Prefect API for deployments. Only deployments matching all
    the provided criteria will be returned.

    Args:
        flow_filter: filter criteria for flows
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        deployment_filter: filter criteria for deployments
        work_pool_filter: filter criteria for work pools
        work_queue_filter: filter criteria for work pool queues
        limit: a limit for the deployment query
        offset: an offset for the deployment query

    Returns:
        a list of Deployment model representations
            of the deployments
    """
    body = {
        "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True, exclude_unset=True)
            if flow_run_filter
            else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "deployments": (
            deployment_filter.dict(json_compatible=True)
            if deployment_filter
            else None
        ),
        "work_pools": (
            work_pool_filter.dict(json_compatible=True)
            if work_pool_filter
            else None
        ),
        "work_pool_queues": (
            work_queue_filter.dict(json_compatible=True)
            if work_queue_filter
            else None
        ),
        "limit": limit,
        "offset": offset,
        "sort": sort,
    }

    response = await self._client.post("/deployments/filter", json=body)
    return pydantic.parse_obj_as(List[DeploymentResponse], response.json())

delete_deployment async

Delete deployment by id.

Parameters:

Name Type Description Default
deployment_id UUID

The deployment id of interest.

required

Raises:

Type Description
prefect.exceptions.ObjectNotFound

If request returns 404

httpx.RequestError

If requests fails

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
async def delete_deployment(
    self,
    deployment_id: UUID,
):
    """
    Delete deployment by id.

    Args:
        deployment_id: The deployment id of interest.
    Raises:
        prefect.exceptions.ObjectNotFound: If request returns 404
        httpx.RequestError: If requests fails
    """
    try:
        await self._client.delete(f"/deployments/{deployment_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_flow_run async

Query the Prefect API for a flow run by id.

Parameters:

Name Type Description Default
flow_run_id UUID

the flow run ID of interest

required

Returns:

Type Description
FlowRun

a Flow Run model representation of the flow run

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
async def read_flow_run(self, flow_run_id: UUID) -> FlowRun:
    """
    Query the Prefect API for a flow run by id.

    Args:
        flow_run_id: the flow run ID of interest

    Returns:
        a Flow Run model representation of the flow run
    """
    try:
        response = await self._client.get(f"/flow_runs/{flow_run_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise
    return FlowRun.parse_obj(response.json())

resume_flow_run async

Resumes a paused flow run.

Parameters:

Name Type Description Default
flow_run_id UUID

the flow run ID of interest

required

Returns:

Type Description
OrchestrationResult

an OrchestrationResult model representation of state orchestration output

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
async def resume_flow_run(self, flow_run_id: UUID) -> OrchestrationResult:
    """
    Resumes a paused flow run.

    Args:
        flow_run_id: the flow run ID of interest

    Returns:
        an OrchestrationResult model representation of state orchestration output
    """
    try:
        response = await self._client.post(f"/flow_runs/{flow_run_id}/resume")
    except httpx.HTTPStatusError:
        raise

    return OrchestrationResult.parse_obj(response.json())

read_flow_runs async

Query the Prefect API for flow runs. Only flow runs matching all criteria will be returned.

Parameters:

Name Type Description Default
flow_filter FlowFilter

filter criteria for flows

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
deployment_filter DeploymentFilter

filter criteria for deployments

None
work_pool_filter WorkPoolFilter

filter criteria for work pools

None
work_queue_filter WorkQueueFilter

filter criteria for work pool queues

None
sort FlowRunSort

sort criteria for the flow runs

None
limit int

limit for the flow run query

None
offset int

offset for the flow run query

0

Returns:

Type Description
List[FlowRun]

a list of Flow Run model representations of the flow runs

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_flow_runs(
    self,
    *,
    flow_filter: FlowFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    deployment_filter: DeploymentFilter = None,
    work_pool_filter: WorkPoolFilter = None,
    work_queue_filter: WorkQueueFilter = None,
    sort: FlowRunSort = None,
    limit: int = None,
    offset: int = 0,
) -> List[FlowRun]:
    """
    Query the Prefect API for flow runs. Only flow runs matching all criteria will
    be returned.

    Args:
        flow_filter: filter criteria for flows
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        deployment_filter: filter criteria for deployments
        work_pool_filter: filter criteria for work pools
        work_queue_filter: filter criteria for work pool queues
        sort: sort criteria for the flow runs
        limit: limit for the flow run query
        offset: offset for the flow run query

    Returns:
        a list of Flow Run model representations
            of the flow runs
    """
    body = {
        "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True, exclude_unset=True)
            if flow_run_filter
            else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "deployments": (
            deployment_filter.dict(json_compatible=True)
            if deployment_filter
            else None
        ),
        "work_pools": (
            work_pool_filter.dict(json_compatible=True)
            if work_pool_filter
            else None
        ),
        "work_pool_queues": (
            work_queue_filter.dict(json_compatible=True)
            if work_queue_filter
            else None
        ),
        "sort": sort,
        "limit": limit,
        "offset": offset,
    }

    response = await self._client.post("/flow_runs/filter", json=body)
    return pydantic.parse_obj_as(List[FlowRun], response.json())

set_flow_run_state async

Set the state of a flow run.

Parameters:

Name Type Description Default
flow_run_id UUID

the id of the flow run

required
state prefect.states.State

the state to set

required
force bool

if True, disregard orchestration logic when setting the state, forcing the Prefect API to accept the state

False

Returns:

Type Description
OrchestrationResult

an OrchestrationResult model representation of state orchestration output

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def set_flow_run_state(
    self,
    flow_run_id: UUID,
    state: "prefect.states.State",
    force: bool = False,
) -> OrchestrationResult:
    """
    Set the state of a flow run.

    Args:
        flow_run_id: the id of the flow run
        state: the state to set
        force: if True, disregard orchestration logic when setting the state,
            forcing the Prefect API to accept the state

    Returns:
        an OrchestrationResult model representation of state orchestration output
    """
    state_create = state.to_state_create()
    state_create.state_details.flow_run_id = flow_run_id
    try:
        response = await self._client.post(
            f"/flow_runs/{flow_run_id}/set_state",
            json=dict(state=state_create.dict(json_compatible=True), force=force),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

    return OrchestrationResult.parse_obj(response.json())

read_flow_run_states async

Query for the states of a flow run

Parameters:

Name Type Description Default
flow_run_id UUID

the id of the flow run

required

Returns:

Type Description
List[prefect.states.State]

a list of State model representations of the flow run states

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
async def read_flow_run_states(
    self, flow_run_id: UUID
) -> List[prefect.states.State]:
    """
    Query for the states of a flow run

    Args:
        flow_run_id: the id of the flow run

    Returns:
        a list of State model representations
            of the flow run states
    """
    response = await self._client.get(
        "/flow_run_states/", params=dict(flow_run_id=str(flow_run_id))
    )
    return pydantic.parse_obj_as(List[prefect.states.State], response.json())

create_task_run async

Create a task run

Parameters:

Name Type Description Default
task TaskObject

The Task to run

required
flow_run_id UUID

The flow run id with which to associate the task run

required
dynamic_key str

A key unique to this particular run of a Task within the flow

required
name str

An optional name for the task run

None
extra_tags Iterable[str]

an optional list of extra tags to apply to the task run in addition to task.tags

None
state prefect.states.State

The initial state for the run. If not provided, defaults to Pending for now. Should always be a Scheduled type.

None
task_inputs Dict[str, List[Union[TaskRunResult, Parameter, Constant]]]

the set of inputs passed to the task

None

Returns:

Type Description
TaskRun

The created task run.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_task_run(
    self,
    task: "TaskObject",
    flow_run_id: UUID,
    dynamic_key: str,
    name: str = None,
    extra_tags: Iterable[str] = None,
    state: prefect.states.State = None,
    task_inputs: Dict[
        str,
        List[
            Union[
                TaskRunResult,
                Parameter,
                Constant,
            ]
        ],
    ] = None,
) -> TaskRun:
    """
    Create a task run

    Args:
        task: The Task to run
        flow_run_id: The flow run id with which to associate the task run
        dynamic_key: A key unique to this particular run of a Task within the flow
        name: An optional name for the task run
        extra_tags: an optional list of extra tags to apply to the task run in
            addition to `task.tags`
        state: The initial state for the run. If not provided, defaults to
            `Pending` for now. Should always be a `Scheduled` type.
        task_inputs: the set of inputs passed to the task

    Returns:
        The created task run.
    """
    tags = set(task.tags).union(extra_tags or [])

    if state is None:
        state = prefect.states.Pending()

    task_run_data = TaskRunCreate(
        name=name,
        flow_run_id=flow_run_id,
        task_key=task.task_key,
        dynamic_key=dynamic_key,
        tags=list(tags),
        task_version=task.version,
        empirical_policy=TaskRunPolicy(
            retries=task.retries,
            retry_delay=task.retry_delay_seconds,
            retry_jitter_factor=task.retry_jitter_factor,
        ),
        state=state.to_state_create(),
        task_inputs=task_inputs or {},
    )

    response = await self._client.post(
        "/task_runs/", json=task_run_data.dict(json_compatible=True)
    )
    return TaskRun.parse_obj(response.json())

read_task_run async

Query the Prefect API for a task run by id.

Parameters:

Name Type Description Default
task_run_id UUID

the task run ID of interest

required

Returns:

Type Description
TaskRun

a Task Run model representation of the task run

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
async def read_task_run(self, task_run_id: UUID) -> TaskRun:
    """
    Query the Prefect API for a task run by id.

    Args:
        task_run_id: the task run ID of interest

    Returns:
        a Task Run model representation of the task run
    """
    response = await self._client.get(f"/task_runs/{task_run_id}")
    return TaskRun.parse_obj(response.json())

read_task_runs async

Query the Prefect API for task runs. Only task runs matching all criteria will be returned.

Parameters:

Name Type Description Default
flow_filter FlowFilter

filter criteria for flows

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
deployment_filter DeploymentFilter

filter criteria for deployments

None
sort TaskRunSort

sort criteria for the task runs

None
limit int

a limit for the task run query

None
offset int

an offset for the task run query

0

Returns:

Type Description
List[TaskRun]

a list of Task Run model representations of the task runs

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_task_runs(
    self,
    *,
    flow_filter: FlowFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    deployment_filter: DeploymentFilter = None,
    sort: TaskRunSort = None,
    limit: int = None,
    offset: int = 0,
) -> List[TaskRun]:
    """
    Query the Prefect API for task runs. Only task runs matching all criteria will
    be returned.

    Args:
        flow_filter: filter criteria for flows
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        deployment_filter: filter criteria for deployments
        sort: sort criteria for the task runs
        limit: a limit for the task run query
        offset: an offset for the task run query

    Returns:
        a list of Task Run model representations
            of the task runs
    """
    body = {
        "flows": flow_filter.dict(json_compatible=True) if flow_filter else None,
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True, exclude_unset=True)
            if flow_run_filter
            else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "deployments": (
            deployment_filter.dict(json_compatible=True)
            if deployment_filter
            else None
        ),
        "sort": sort,
        "limit": limit,
        "offset": offset,
    }
    response = await self._client.post("/task_runs/filter", json=body)
    return pydantic.parse_obj_as(List[TaskRun], response.json())

set_task_run_state async

Set the state of a task run.

Parameters:

Name Type Description Default
task_run_id UUID

the id of the task run

required
state prefect.states.State

the state to set

required
force bool

if True, disregard orchestration logic when setting the state, forcing the Prefect API to accept the state

False

Returns:

Type Description
OrchestrationResult

an OrchestrationResult model representation of state orchestration output

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def set_task_run_state(
    self,
    task_run_id: UUID,
    state: prefect.states.State,
    force: bool = False,
) -> OrchestrationResult:
    """
    Set the state of a task run.

    Args:
        task_run_id: the id of the task run
        state: the state to set
        force: if True, disregard orchestration logic when setting the state,
            forcing the Prefect API to accept the state

    Returns:
        an OrchestrationResult model representation of state orchestration output
    """
    state_create = state.to_state_create()
    state_create.state_details.task_run_id = task_run_id
    response = await self._client.post(
        f"/task_runs/{task_run_id}/set_state",
        json=dict(state=state_create.dict(json_compatible=True), force=force),
    )
    return OrchestrationResult.parse_obj(response.json())

read_task_run_states async

Query for the states of a task run

Parameters:

Name Type Description Default
task_run_id UUID

the id of the task run

required

Returns:

Type Description
List[prefect.states.State]

a list of State model representations of the task run states

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
async def read_task_run_states(
    self, task_run_id: UUID
) -> List[prefect.states.State]:
    """
    Query for the states of a task run

    Args:
        task_run_id: the id of the task run

    Returns:
        a list of State model representations of the task run states
    """
    response = await self._client.get(
        "/task_run_states/", params=dict(task_run_id=str(task_run_id))
    )
    return pydantic.parse_obj_as(List[prefect.states.State], response.json())

create_logs async

Create logs for a flow or task run

Parameters:

Name Type Description Default
logs Iterable[Union[LogCreate, dict]]

An iterable of LogCreate objects or already json-compatible dicts

required
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
async def create_logs(self, logs: Iterable[Union[LogCreate, dict]]) -> None:
    """
    Create logs for a flow or task run

    Args:
        logs: An iterable of `LogCreate` objects or already json-compatible dicts
    """
    serialized_logs = [
        log.dict(json_compatible=True) if isinstance(log, LogCreate) else log
        for log in logs
    ]
    await self._client.post("/logs/", json=serialized_logs)

create_flow_run_notification_policy async

Create a notification policy for flow runs

Parameters:

Name Type Description Default
block_document_id UUID

The block document UUID

required
is_active bool

Whether the notification policy is active

True
tags List[str]

List of flow tags

None
state_names List[str]

List of state names

None
message_template Optional[str]

Notification message template

None
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_flow_run_notification_policy(
    self,
    block_document_id: UUID,
    is_active: bool = True,
    tags: List[str] = None,
    state_names: List[str] = None,
    message_template: Optional[str] = None,
) -> UUID:
    """
    Create a notification policy for flow runs

    Args:
        block_document_id: The block document UUID
        is_active: Whether the notification policy is active
        tags: List of flow tags
        state_names: List of state names
        message_template: Notification message template
    """
    if tags is None:
        tags = []
    if state_names is None:
        state_names = []

    policy = FlowRunNotificationPolicyCreate(
        block_document_id=block_document_id,
        is_active=is_active,
        tags=tags,
        state_names=state_names,
        message_template=message_template,
    )
    response = await self._client.post(
        "/flow_run_notification_policies/",
        json=policy.dict(json_compatible=True),
    )

    policy_id = response.json().get("id")
    if not policy_id:
        raise httpx.RequestError(f"Malformed response: {response}")

    return UUID(policy_id)

read_flow_run_notification_policies async

Query the Prefect API for flow run notification policies. Only policies matching all criteria will be returned.

Parameters:

Name Type Description Default
flow_run_notification_policy_filter FlowRunNotificationPolicyFilter

filter criteria for notification policies

required
limit Optional[int]

a limit for the notification policies query

None
offset int

an offset for the notification policies query

0

Returns:

Type Description
List[FlowRunNotificationPolicy]

a list of FlowRunNotificationPolicy model representations of the notification policies

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_flow_run_notification_policies(
    self,
    flow_run_notification_policy_filter: FlowRunNotificationPolicyFilter,
    limit: Optional[int] = None,
    offset: int = 0,
) -> List[FlowRunNotificationPolicy]:
    """
    Query the Prefect API for flow run notification policies. Only policies matching all criteria will
    be returned.

    Args:
        flow_run_notification_policy_filter: filter criteria for notification policies
        limit: a limit for the notification policies query
        offset: an offset for the notification policies query

    Returns:
        a list of FlowRunNotificationPolicy model representations
            of the notification policies
    """
    body = {
        "flow_run_notification_policy_filter": (
            flow_run_notification_policy_filter.dict(json_compatible=True)
            if flow_run_notification_policy_filter
            else None
        ),
        "limit": limit,
        "offset": offset,
    }
    response = await self._client.post(
        "/flow_run_notification_policies/filter", json=body
    )
    return pydantic.parse_obj_as(List[FlowRunNotificationPolicy], response.json())

read_logs async

Read flow and task run logs.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
async def read_logs(
    self,
    log_filter: LogFilter = None,
    limit: int = None,
    offset: int = None,
    sort: LogSort = LogSort.TIMESTAMP_ASC,
) -> None:
    """
    Read flow and task run logs.
    """
    body = {
        "logs": log_filter.dict(json_compatible=True) if log_filter else None,
        "limit": limit,
        "offset": offset,
        "sort": sort,
    }

    response = await self._client.post("/logs/filter", json=body)
    return pydantic.parse_obj_as(List[Log], response.json())

resolve_datadoc async

Recursively decode possibly nested data documents.

"server" encoded documents will be retrieved from the server.

Parameters:

Name Type Description Default
datadoc DataDocument

The data document to resolve

required

Returns:

Type Description
Any

a decoded object, the innermost data

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def resolve_datadoc(self, datadoc: DataDocument) -> Any:
    """
    Recursively decode possibly nested data documents.

    "server" encoded documents will be retrieved from the server.

    Args:
        datadoc: The data document to resolve

    Returns:
        a decoded object, the innermost data
    """
    if not isinstance(datadoc, DataDocument):
        raise TypeError(
            f"`resolve_datadoc` received invalid type {type(datadoc).__name__}"
        )

    async def resolve_inner(data):
        if isinstance(data, bytes):
            try:
                data = DataDocument.parse_raw(data)
            except pydantic.ValidationError:
                return data

        if isinstance(data, DataDocument):
            return await resolve_inner(data.decode())

        return data

    return await resolve_inner(datadoc)

send_worker_heartbeat async

Sends a worker heartbeat for a given work pool.

Parameters:

Name Type Description Default
work_pool_name str

The name of the work pool to heartbeat against.

required
worker_name str

The name of the worker sending the heartbeat.

required
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
async def send_worker_heartbeat(self, work_pool_name: str, worker_name: str):
    """
    Sends a worker heartbeat for a given work pool.

    Args:
        work_pool_name: The name of the work pool to heartbeat against.
        worker_name: The name of the worker sending the heartbeat.
    """
    await self._client.post(
        f"/work_pools/{work_pool_name}/workers/heartbeat",
        json={"name": worker_name},
    )

read_workers_for_work_pool async

Reads workers for a given work pool.

Parameters:

Name Type Description Default
work_pool_name str

The name of the work pool for which to get member workers.

required
worker_filter Optional[WorkerFilter]

Criteria by which to filter workers.

None
limit Optional[int]

Limit for the worker query.

None
offset Optional[int]

Limit for the worker query.

None
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_workers_for_work_pool(
    self,
    work_pool_name: str,
    worker_filter: Optional[WorkerFilter] = None,
    offset: Optional[int] = None,
    limit: Optional[int] = None,
) -> List[Worker]:
    """
    Reads workers for a given work pool.

    Args:
        work_pool_name: The name of the work pool for which to get
            member workers.
        worker_filter: Criteria by which to filter workers.
        limit: Limit for the worker query.
        offset: Limit for the worker query.
    """
    response = await self._client.post(
        f"/work_pools/{work_pool_name}/workers/filter",
        json={
            "worker_filter": (
                worker_filter.dict(json_compatible=True, exclude_unset=True)
                if worker_filter
                else None
            ),
            "offset": offset,
            "limit": limit,
        },
    )

    return pydantic.parse_obj_as(List[Worker], response.json())

read_work_pool async

Reads information for a given work pool

Parameters:

Name Type Description Default
work_pool_name str

The name of the work pool to for which to get information.

required

Returns:

Type Description
WorkPool

Information about the requested work pool.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
async def read_work_pool(self, work_pool_name: str) -> WorkPool:
    """
    Reads information for a given work pool

    Args:
        work_pool_name: The name of the work pool to for which to get
            information.

    Returns:
        Information about the requested work pool.
    """
    try:
        response = await self._client.get(f"/work_pools/{work_pool_name}")
        return pydantic.parse_obj_as(WorkPool, response.json())
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_work_pools async

Reads work pools.

Parameters:

Name Type Description Default
limit Optional[int]

Limit for the work pool query.

None
offset int

Offset for the work pool query.

0
work_pool_filter Optional[WorkPoolFilter]

Criteria by which to filter work pools.

None

Returns:

Type Description
List[WorkPool]

A list of work pools.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_work_pools(
    self,
    limit: Optional[int] = None,
    offset: int = 0,
    work_pool_filter: Optional[WorkPoolFilter] = None,
) -> List[WorkPool]:
    """
    Reads work pools.

    Args:
        limit: Limit for the work pool query.
        offset: Offset for the work pool query.
        work_pool_filter: Criteria by which to filter work pools.

    Returns:
        A list of work pools.
    """

    body = {
        "limit": limit,
        "offset": offset,
        "work_pools": (
            work_pool_filter.dict(json_compatible=True)
            if work_pool_filter
            else None
        ),
    }
    response = await self._client.post("/work_pools/filter", json=body)
    return pydantic.parse_obj_as(List[WorkPool], response.json())

create_work_pool async

Creates a work pool with the provided configuration.

Parameters:

Name Type Description Default
work_pool WorkPoolCreate

Desired configuration for the new work pool.

required

Returns:

Type Description
WorkPool

Information about the newly created work pool.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def create_work_pool(
    self,
    work_pool: WorkPoolCreate,
) -> WorkPool:
    """
    Creates a work pool with the provided configuration.

    Args:
        work_pool: Desired configuration for the new work pool.

    Returns:
        Information about the newly created work pool.
    """
    try:
        response = await self._client.post(
            "/work_pools/",
            json=work_pool.dict(json_compatible=True, exclude_unset=True),
        )
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_409_CONFLICT:
            raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e
        else:
            raise

    return pydantic.parse_obj_as(WorkPool, response.json())

delete_work_pool async

Deletes a work pool.

Parameters:

Name Type Description Default
work_pool_name str

Name of the work pool to delete.

required
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
async def delete_work_pool(
    self,
    work_pool_name: str,
):
    """
    Deletes a work pool.

    Args:
        work_pool_name: Name of the work pool to delete.
    """
    try:
        await self._client.delete(f"/work_pools/{work_pool_name}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_work_queues async

Retrieves queues for a work pool.

Parameters:

Name Type Description Default
work_pool_name Optional[str]

Name of the work pool for which to get queues.

None
work_queue_filter Optional[WorkQueueFilter]

Criteria by which to filter queues.

None
limit Optional[int]

Limit for the queue query.

None
offset Optional[int]

Limit for the queue query.

None

Returns:

Type Description
List[WorkQueue]

List of queues for the specified work pool.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_work_queues(
    self,
    work_pool_name: Optional[str] = None,
    work_queue_filter: Optional[WorkQueueFilter] = None,
    limit: Optional[int] = None,
    offset: Optional[int] = None,
) -> List[WorkQueue]:
    """
    Retrieves queues for a work pool.

    Args:
        work_pool_name: Name of the work pool for which to get queues.
        work_queue_filter: Criteria by which to filter queues.
        limit: Limit for the queue query.
        offset: Limit for the queue query.

    Returns:
        List of queues for the specified work pool.
    """
    json = {
        "work_queues": (
            work_queue_filter.dict(json_compatible=True, exclude_unset=True)
            if work_queue_filter
            else None
        ),
        "limit": limit,
        "offset": offset,
    }

    if work_pool_name:
        try:
            response = await self._client.post(
                f"/work_pools/{work_pool_name}/queues/filter",
                json=json,
            )
        except httpx.HTTPStatusError as e:
            if e.response.status_code == status.HTTP_404_NOT_FOUND:
                raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
            else:
                raise
    else:
        response = await self._client.post("/work_queues/filter", json=json)

    return pydantic.parse_obj_as(List[WorkQueue], response.json())

get_scheduled_flow_runs_for_work_pool async

Retrieves scheduled flow runs for the provided set of work pool queues.

Parameters:

Name Type Description Default
work_pool_name str

The name of the work pool that the work pool queues are associated with.

required
work_queue_names Optional[List[str]]

The names of the work pool queues from which to get scheduled flow runs.

None
scheduled_before Optional[datetime.datetime]

Datetime used to filter returned flow runs. Flow runs scheduled for after the given datetime string will not be returned.

None

Returns:

Type Description
List[WorkerFlowRunResponse]

A list of worker flow run responses containing information about the

List[WorkerFlowRunResponse]

retrieved flow runs.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def get_scheduled_flow_runs_for_work_pool(
    self,
    work_pool_name: str,
    work_queue_names: Optional[List[str]] = None,
    scheduled_before: Optional[datetime.datetime] = None,
) -> List[WorkerFlowRunResponse]:
    """
    Retrieves scheduled flow runs for the provided set of work pool queues.

    Args:
        work_pool_name: The name of the work pool that the work pool
            queues are associated with.
        work_queue_names: The names of the work pool queues from which
            to get scheduled flow runs.
        scheduled_before: Datetime used to filter returned flow runs. Flow runs
            scheduled for after the given datetime string will not be returned.

    Returns:
        A list of worker flow run responses containing information about the
        retrieved flow runs.
    """
    body: Dict[str, Any] = {}
    if work_queue_names is not None:
        body["work_queue_names"] = list(work_queue_names)
    if scheduled_before:
        body["scheduled_before"] = str(scheduled_before)

    response = await self._client.post(
        f"/work_pools/{work_pool_name}/get_scheduled_flow_runs",
        json=body,
    )

    return pydantic.parse_obj_as(List[WorkerFlowRunResponse], response.json())

create_artifact async

Creates an artifact with the provided configuration.

Parameters:

Name Type Description Default
artifact ArtifactCreate

Desired configuration for the new artifact.

required

Returns:

Type Description
Artifact

Information about the newly created artifact.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
async def create_artifact(
    self,
    artifact: ArtifactCreate,
) -> Artifact:
    """
    Creates an artifact with the provided configuration.

    Args:
        artifact: Desired configuration for the new artifact.
    Returns:
        Information about the newly created artifact.
    """

    response = await self._client.post(
        "/artifacts/",
        json=artifact.dict(json_compatible=True, exclude_unset=True),
    )

    return pydantic.parse_obj_as(Artifact, response.json())

read_artifacts async

Query the Prefect API for artifacts. Only artifacts matching all criteria will be returned.

Parameters:

Name Type Description Default
artifact_filter ArtifactFilter

filter criteria for artifacts

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
sort ArtifactSort

sort criteria for the artifacts

None
limit int

limit for the artifact query

None
offset int

offset for the artifact query

0

Returns:

Type Description
List[Artifact]

a list of Artifact model representations of the artifacts

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_artifacts(
    self,
    *,
    artifact_filter: ArtifactFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    sort: ArtifactSort = None,
    limit: int = None,
    offset: int = 0,
) -> List[Artifact]:
    """
    Query the Prefect API for artifacts. Only artifacts matching all criteria will
    be returned.
    Args:
        artifact_filter: filter criteria for artifacts
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        sort: sort criteria for the artifacts
        limit: limit for the artifact query
        offset: offset for the artifact query
    Returns:
        a list of Artifact model representations of the artifacts
    """
    body = {
        "artifacts": (
            artifact_filter.dict(json_compatible=True) if artifact_filter else None
        ),
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True) if flow_run_filter else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "sort": sort,
        "limit": limit,
        "offset": offset,
    }
    response = await self._client.post("/artifacts/filter", json=body)
    return pydantic.parse_obj_as(List[Artifact], response.json())

read_latest_artifacts async

Query the Prefect API for artifacts. Only artifacts matching all criteria will be returned.

Parameters:

Name Type Description Default
artifact_filter ArtifactCollectionFilter

filter criteria for artifacts

None
flow_run_filter FlowRunFilter

filter criteria for flow runs

None
task_run_filter TaskRunFilter

filter criteria for task runs

None
sort ArtifactCollectionSort

sort criteria for the artifacts

None
limit int

limit for the artifact query

None
offset int

offset for the artifact query

0

Returns:

Type Description
List[ArtifactCollection]

a list of Artifact model representations of the artifacts

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
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
async def read_latest_artifacts(
    self,
    *,
    artifact_filter: ArtifactCollectionFilter = None,
    flow_run_filter: FlowRunFilter = None,
    task_run_filter: TaskRunFilter = None,
    sort: ArtifactCollectionSort = None,
    limit: int = None,
    offset: int = 0,
) -> List[ArtifactCollection]:
    """
    Query the Prefect API for artifacts. Only artifacts matching all criteria will
    be returned.
    Args:
        artifact_filter: filter criteria for artifacts
        flow_run_filter: filter criteria for flow runs
        task_run_filter: filter criteria for task runs
        sort: sort criteria for the artifacts
        limit: limit for the artifact query
        offset: offset for the artifact query
    Returns:
        a list of Artifact model representations of the artifacts
    """
    body = {
        "artifacts": (
            artifact_filter.dict(json_compatible=True) if artifact_filter else None
        ),
        "flow_runs": (
            flow_run_filter.dict(json_compatible=True) if flow_run_filter else None
        ),
        "task_runs": (
            task_run_filter.dict(json_compatible=True) if task_run_filter else None
        ),
        "sort": sort,
        "limit": limit,
        "offset": offset,
    }
    response = await self._client.post("/artifacts/latest/filter", json=body)
    return pydantic.parse_obj_as(List[ArtifactCollection], response.json())

delete_artifact async

Deletes an artifact with the provided id.

Parameters:

Name Type Description Default
artifact_id UUID

The id of the artifact to delete.

required
Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
async def delete_artifact(self, artifact_id: UUID) -> None:
    """
    Deletes an artifact with the provided id.

    Args:
        artifact_id: The id of the artifact to delete.
    """
    try:
        await self._client.delete(f"/artifacts/{artifact_id}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_variable_by_name async

Reads a variable by name. Returns None if no variable is found.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
async def read_variable_by_name(self, name: str) -> Optional[Variable]:
    """Reads a variable by name. Returns None if no variable is found."""
    try:
        response = await self._client.get(f"/variables/name/{name}")
        return pydantic.parse_obj_as(Variable, response.json())
    except httpx.HTTPStatusError as e:
        if e.response.status_code == status.HTTP_404_NOT_FOUND:
            return None
        else:
            raise

delete_variable_by_name async

Deletes a variable by name.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2480
2481
2482
2483
2484
2485
2486
2487
2488
async def delete_variable_by_name(self, name: str):
    """Deletes a variable by name."""
    try:
        await self._client.delete(f"/variables/name/{name}")
    except httpx.HTTPStatusError as e:
        if e.response.status_code == 404:
            raise prefect.exceptions.ObjectNotFound(http_exc=e) from e
        else:
            raise

read_variables async

Reads all variables.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2490
2491
2492
2493
async def read_variables(self, limit: int = None) -> List[Variable]:
    """Reads all variables."""
    response = await self._client.post("/variables/filter", json={"limit": limit})
    return pydantic.parse_obj_as(List[Variable], response.json())

read_worker_metadata async

Reads worker metadata stored in Prefect collection registry.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2495
2496
2497
2498
2499
async def read_worker_metadata(self) -> Dict[str, Any]:
    """Reads worker metadata stored in Prefect collection registry."""
    response = await self._client.get("collections/views/aggregate-worker-metadata")
    response.raise_for_status()
    return response.json()

create_automation async

Creates an automation in Prefect Cloud.

Source code in /home/runner/work/docs/docs/prefect_source/src/prefect/client/orchestration.py
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
async def create_automation(self, automation: Automation) -> UUID:
    """Creates an automation in Prefect Cloud."""
    if self.server_type != ServerType.CLOUD:
        raise RuntimeError("Automations are only supported for Prefect Cloud.")

    response = await self._client.post(
        "/automations/",
        json=automation.dict(json_compatible=True),
    )

    return UUID(response.json()["id"])

OrionClient

Bases: <