Skip to content

Client

v5.0.0 is object-oriented

Many Synapse client methods documented below are deprecated in favor of the object-oriented models (see the Object-Oriented Models section of the API reference) and the synapseclient.operations functions. The Synapse object is still required for authentication via syn.login. New code should prefer the object-oriented models — start with the Python client tutorial.

synapseclient.Synapse

Bases: object

Constructs a Python client object for the Synapse repository service

ATTRIBUTE DESCRIPTION
repoEndpoint

Location of Synapse repository

authEndpoint

Location of authentication service

fileHandleEndpoint

Location of file service

portalEndpoint

Location of the website

debug

Print debugging messages if True

skip_checks

Skip version and endpoint checks

configPath

Path to config File with setting for Synapse. Defaults to ~/.synapseConfig

requests_session

A custom requests.Session object that this Synapse instance will use when making http requests.

cache_root_dir

Root directory for storing cache data

silent

Defaults to False.

requests_session_async_synapse

A custom httpx.AsyncClient that this synapse instance will use when making HTTP requests. requests_session is being deprecated in favor of this.

requests_session_storage

A custom httpx.Client that this synapse instance will use when making HTTP requests to storage providers like AWS S3 and Google Cloud Storage.

asyncio_event_loop

The event loop that is going to be used while executing this code. This is optional and only used when you are manually specifying an async HTTPX client. This is important to pass when you are using the requests_session_async_synapse kwarg because the connection pooling is tied to the event loop.

cache_client

Whether to cache the Synapse client object in the Synapse module. Defaults to True. When set to True anywhere a Synapse object is optional you do not need to pass an instance of Synapse to that function, method, or class. When working in a multi-user environment it is recommended to set this to False, or use Synapse.allow_client_caching(False).

user_agent

Additional values to add to the User-Agent header on HTTP requests. This should be in the format of "my-project-identifier/1.0.0". This may be a single string or a list of strings to add onto the header. If the format is incorrect a ValueError exception will be raised. These will be appended to the default User-Agent header that already includes the version of this client that you are using, and the HTTP library used to make the request.

timeout

The timeout in seconds for HTTP requests. The default is 70 seconds. You may increase this if you are experiencing timeouts when interacting with slow services.

Getting started

Logging in to Synapse using an authToken

import synapseclient
syn = synapseclient.login(authToken="authtoken")

Using environment variable or .synapseConfig

import synapseclient
syn = synapseclient.login()
Adding an additional user_agent value

This example shows how to add an additional user_agent to the HTTP headers on the request. This is useful for tracking the requests that are being made from your application.

from synapseclient import Synapse

my_agent = "my-project-identifier/1.0.0"
# You may also provide a list of strings to add to the User-Agent header.
# my_agent = ["my-sub-library/1.0.0", "my-parent-project/2.0.0"]

syn = Synapse(user_agent=my_agent)
Source code in synapseclient/client.py
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
class Synapse(object):
    """
    Constructs a Python client object for the Synapse repository service

    Attributes:
        repoEndpoint:          Location of Synapse repository
        authEndpoint:          Location of authentication service
        fileHandleEndpoint:    Location of file service
        portalEndpoint:        Location of the website
        debug:                 Print debugging messages if True
        skip_checks:           Skip version and endpoint checks
        configPath:            Path to config File with setting for Synapse. Defaults to ~/.synapseConfig
        requests_session:      A custom [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) that this Synapse instance will use
                               when making http requests.
        cache_root_dir:        Root directory for storing cache data
        silent:                Defaults to False.
        requests_session_async_synapse: A custom
            [httpx.AsyncClient](https://www.python-httpx.org/async/) that this synapse
            instance will use when making HTTP requests. `requests_session` is being
            deprecated in favor of this.
        requests_session_storage: A custom
            [httpx.Client](https://www.python-httpx.org/advanced/clients/) that this synapse
            instance will use when making HTTP requests to storage providers like AWS S3
            and Google Cloud Storage.
        asyncio_event_loop: The event loop that is going to be used while executing
            this code. This is optional and only used when you are manually specifying
            an async HTTPX client. This is important to pass when you are using the
            `requests_session_async_synapse` kwarg because the connection pooling is
            tied to the event loop.
        cache_client: Whether to cache the Synapse client object in the Synapse module.
            Defaults to True. When set to True anywhere a `Synapse` object is optional
            you do not need to pass an instance of `Synapse` to that function, method,
            or class. When working in a multi-user environment it is recommended to set
            this to False, or use `Synapse.allow_client_caching(False)`.
        user_agent: Additional values to add to the `User-Agent` header on HTTP
            requests. This should be in the format of `"my-project-identifier/1.0.0"`.
            This may be a single string or a list of strings to add onto the
            header. If the format is incorrect a `ValueError` exception will be
            raised. These will be appended to the default `User-Agent` header that
            already includes the version of this client that you are using, and the
            HTTP library used to make the request.
        timeout: The timeout in seconds for HTTP requests. The default is 70 seconds.
            You may increase this if you are experiencing timeouts when interacting
            with slow services.

    Example: Getting started
        Logging in to Synapse using an authToken

        ```python
        import synapseclient
        syn = synapseclient.login(authToken="authtoken")
        ```

        Using environment variable or `.synapseConfig`

        ```python
        import synapseclient
        syn = synapseclient.login()
        ```

    Example: Adding an additional `user_agent` value
        This example shows how to add an additional `user_agent` to the HTTP headers
        on the request. This is useful for tracking the requests that are being made
        from your application.

        ```python
        from synapseclient import Synapse

        my_agent = "my-project-identifier/1.0.0"
        # You may also provide a list of strings to add to the User-Agent header.
        # my_agent = ["my-sub-library/1.0.0", "my-parent-project/2.0.0"]

        syn = Synapse(user_agent=my_agent)
        ```

    """

    _synapse_client = None
    _allow_client_caching = True

    # TODO: add additional boolean for write to disk?
    def __init__(
        self,
        repoEndpoint: str = None,
        authEndpoint: str = None,
        fileHandleEndpoint: str = None,
        portalEndpoint: str = None,
        debug: bool = None,
        skip_checks: bool = False,
        configPath: str = CONFIG_FILE,
        requests_session: requests.Session = None,
        cache_root_dir: str = None,
        silent: bool = None,
        requests_session_async_synapse: httpx.AsyncClient = None,
        requests_session_storage: httpx.Client = None,
        asyncio_event_loop: asyncio.AbstractEventLoop = None,
        cache_client: bool = True,
        user_agent: Union[str, List[str]] = None,
        http_timeout_seconds: int = 70,
    ) -> "Synapse":
        """
        Initialize Synapse object

        Arguments:
            repoEndpoint:       Location of Synapse repository.
            authEndpoint:       Location of authentication service.
            fileHandleEndpoint: Location of file service.
            portalEndpoint:     Location of the website.
            debug:              Print debugging messages if True.
            skip_checks:        Skip version and endpoint checks.
            configPath:         Path to config File with setting for Synapse.
            requests_session:   A custom [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) that this Synapse instance will use
                                when making http requests.
            cache_root_dir:     Root directory for storing cache data.
            silent:             Suppresses message.
            requests_session_async_synapse: The HTTPX Async client for interacting with
                Synapse services.
            requests_session_storage: The HTTPX client for interacting with
                storage providers like AWS S3 and Google Cloud.
            asyncio_event_loop: The event loop that is going to be used while executing
                this code. This is optional and only used when you are manually
                specifying an async HTTPX client.
            cache_client: Whether to cache the Synapse client object in the Synapse module. Defaults to True.
                             When set to True anywhere a `Synapse` object is optional you do not need to pass an
                             instance of `Synapse` to that function, method, or class.
                             When working in a multi-user environment it is
                             recommended to set this to False, or use
                             `Synapse.allow_client_caching(False)`.
            user_agent: Additional values to add to the `User-Agent` header on HTTP
                requests. This should be in the format of
                `"my-project-identifier/1.0.0"`. Only
                [Semantic Versioning](https://semver.org/) is expected.
                This may be a single string or a list of strings to add onto the
                header. If the format is incorrect a `ValueError` exception will be
                raised. These will be appended to the default `User-Agent` header that
                already includes the version of this client that you are using, and the
                HTTP library used to make the request.
            http_timeout_seconds: The timeout in seconds for HTTP requests.
                The default is 70 seconds. You may increase this if you are
                experiencing timeouts when interacting with slow services.

        Raises:
            ValueError: Warn for non-boolean debug value.
        """
        self._requests_session = requests_session or requests.Session()

        # `requests_session_async_synapse` and the thread pools are being stored in
        # a dict based on the current running event loop. This is to ensure that the
        # connection pooling is maintained within the same event loop. This is to
        # prevent the connection pooling from being shared across different event loops.
        if requests_session_async_synapse and asyncio_event_loop:
            self._requests_session_async_synapse = {
                asyncio_event_loop: requests_session_async_synapse
            }
        else:
            self._requests_session_async_synapse = {}

        self._http_timeout_seconds = http_timeout_seconds
        httpx_timeout = httpx.Timeout(http_timeout_seconds, pool=None)
        self._requests_session_storage = requests_session_storage or httpx.Client(
            timeout=httpx_timeout
        )

        cache_root_dir = (
            cache.CACHE_ROOT_DIR if cache_root_dir is None else cache_root_dir
        )

        config_debug = None
        # Check for a config file
        self.configPath = configPath
        if os.path.isfile(configPath):
            config = get_config_file(configPath)
            if config.has_option("cache", "location"):
                cache_root_dir = config.get("cache", "location")
            if config.has_section("debug"):
                config_debug = True

        if debug is None:
            debug = config_debug if config_debug is not None else DEBUG_DEFAULT

        if not isinstance(debug, bool):
            raise ValueError("debug must be set to a bool (either True or False)")
        self.debug = debug

        self.cache = cache.Cache(cache_root_dir)
        self._sts_token_store = sts_transfer.StsTokenStore()

        self.setEndpoints(
            repoEndpoint, authEndpoint, fileHandleEndpoint, portalEndpoint, skip_checks
        )

        self.default_headers = {
            "content-type": "application/json; charset=UTF-8",
            "Accept": "application/json; charset=UTF-8",
        }
        self.credentials = None

        self._validate_user_agent_format(user_agent)
        if isinstance(user_agent, str):
            self.user_agent = [user_agent]
        else:
            self.user_agent = user_agent

        self.silent = silent
        self._init_logger()  # initializes self.logger

        self.skip_checks = skip_checks

        self.table_query_sleep = 0.2  # Sleep for 200ms between table query retries
        self.table_query_backoff = 1.1
        self.table_query_max_sleep = 20
        self.table_query_timeout = 600  # in seconds
        self.multi_threaded = True  # if set to True, multi threaded download will be used for http and https URLs

        transfer_config = get_transfer_config(config_path=self.configPath)
        self.max_threads = transfer_config["max_threads"]
        self._thread_executor = {}
        self._process_executor = {}
        self._parallel_file_transfer_semaphore = {}
        self.use_boto_sts_transfers = transfer_config["use_boto_sts"]
        self._parts_transfered_counter = 0
        if cache_client and Synapse._allow_client_caching:
            Synapse.set_client(synapse_client=self)

    def _validate_user_agent_format(self, agent: Union[str, List[str]]) -> None:
        if not agent:
            return

        if not isinstance(agent, str) and not isinstance(agent, list):
            raise ValueError(
                f"user_agent must be a string or a list of strings to add to the User-Agent header. Current value: {agent}"
            )

        if isinstance(agent, str):
            if not re.match(USER_AGENT_REGEX_PATTERN, agent):
                raise ValueError(
                    f"user_agent must be in the format of 'my-project-identifier/1.0.0'. Current value: {agent}"
                )
        else:
            for value in agent:
                self._validate_user_agent_format(agent=value)

    def _get_requests_session_async_synapse(
        self, asyncio_event_loop: asyncio.AbstractEventLoop
    ) -> httpx.AsyncClient:
        """
        httpx.AsyncClient can only use connection pooling within the same event loop.
        As a result an `atexit` handler is used to close the connection when the event
        loop is closed. It will also delete the attribute from the object to prevent
        it from being reused in the future.

        Further documentation can be found here:
        <https://github.com/encode/httpx/discussions/2959>


        As a result of this issue: It is recommended to use the same event loop for all
        requests. This means to enter into an event loop before making any requests.

        This is expected to be called from within an AsyncIO loop.
        """
        if (
            hasattr(self, "_requests_session_async_synapse")
            and asyncio_event_loop in self._requests_session_async_synapse
            and self._requests_session_async_synapse[asyncio_event_loop] is not None
        ):
            return self._requests_session_async_synapse[asyncio_event_loop]

        async def close_connection() -> None:
            """Close connection when event loop exits"""
            await self._requests_session_async_synapse[asyncio_event_loop].aclose()
            del self._requests_session_async_synapse[asyncio_event_loop]

        httpx_timeout = httpx.Timeout(self._http_timeout_seconds, pool=None)
        self._requests_session_async_synapse.update(
            {
                asyncio_event_loop: httpx.AsyncClient(
                    limits=httpx.Limits(max_connections=5),
                    timeout=httpx_timeout,
                )
            }
        )

        asyncio_atexit.register(close_connection)
        return self._requests_session_async_synapse[asyncio_event_loop]

    def _get_thread_pool_executor(
        self, asyncio_event_loop: asyncio.AbstractEventLoop
    ) -> ThreadPoolExecutor:
        """
        Retrieve the thread pool executor for the Synapse client. Or create a new one if
        it does not exist. This executor is used for concurrent uploads of data to
        storage providers like AWS S3 and Google Cloud Storage.

        This is expected to be called from within an AsyncIO loop.
        """
        if (
            hasattr(self, "_thread_executor")
            and asyncio_event_loop in self._thread_executor
            and self._thread_executor[asyncio_event_loop] is not None
        ):
            return self._thread_executor[asyncio_event_loop]

        def close_pool() -> None:
            """Close pool when event loop exits"""
            self._thread_executor[asyncio_event_loop].shutdown(wait=True)
            del self._thread_executor[asyncio_event_loop]

        self._thread_executor.update(
            {asyncio_event_loop: get_executor(thread_count=self.max_threads)}
        )

        asyncio_atexit.register(close_pool)
        return self._thread_executor[asyncio_event_loop]

    def _get_parallel_file_transfer_semaphore(
        self, asyncio_event_loop: asyncio.AbstractEventLoop
    ) -> asyncio.Semaphore:
        """
        Retrieve the semaphore for the Synapse client. Or create a new one if it does
        not exist. This semaphore is used to limit the number of files that can actively
        enter the uploading/downloading process.

        This is expected to be called from within an AsyncIO loop.

        By default the number of files that can enter the "uploading" state will be
        limited to 2 * max_threads. This is to ensure that the files that are entering
        into the "uploading" state will have priority to finish. Additionally, it means
        that there should be a good spread of files getting up to the "uploading"
        state, entering the "uploading" state, and finishing the "uploading" state.

        If we break these states down into large components they would look like:
        - Before "uploading" state: HTTP rest calls to retrieve what data Synapse has
        - Entering "uploading" state: MD5 calculation and HTTP rest calls to determine
          how/where to upload a file to.
        - During "uploading" state: Uploading the file to a storage provider.
        - After "uploading" state: HTTP rest calls to finalize the upload.

        This has not yet been applied to parallel file downloads. That will take place
        later on.
        """
        if (
            hasattr(self, "_parallel_file_transfer_semaphore")
            and asyncio_event_loop in self._parallel_file_transfer_semaphore
            and self._parallel_file_transfer_semaphore[asyncio_event_loop] is not None
        ):
            return self._parallel_file_transfer_semaphore[asyncio_event_loop]

        self._parallel_file_transfer_semaphore.update(
            {asyncio_event_loop: asyncio.Semaphore(max(self.max_threads * 2, 1))}
        )

        return self._parallel_file_transfer_semaphore[asyncio_event_loop]

    # initialize logging
    def _init_logger(self):
        """
        Initialize logging
        """
        logger_name = (
            SILENT_LOGGER_NAME
            if self.silent
            else DEBUG_LOGGER_NAME if self.debug else DEFAULT_LOGGER_NAME
        )
        self.logger = logging.getLogger(logger_name)
        logging.getLogger("py.warnings").handlers = self.logger.handlers

    @classmethod
    def get_client(cls, synapse_client: typing.Union[None, "Synapse"]) -> "Synapse":
        """
        Convience function to get an instance of 'Synapse'. The latest instance created
        by 'login()' or set via `set_client` will be returned.

        When 'logout()' is called it will delete the instance.

        Arguments:
            synapse_client: An instance of 'Synapse' or None. This is used to simplify logical checks
                    in cases where synapse is passed into them.

        Returns:
            An instance of 'Synapse'.

        Raises:
            SynapseError: No Synapse client instance was provided, and no cached
                instance is available. Ensure that either an instance is passed as the
                `synapse_client` kwarg, or a cached instance is available.
        """
        if synapse_client:
            return synapse_client

        if not cls._synapse_client:
            raise SynapseError(
                "No Synapse client instance was provided, and no cached instance is available. Ensure that either an instance is passed as the `synapse_client` kwarg, or a cached instance is available."
            )
        return cls._synapse_client

    @staticmethod
    def allow_client_caching(allow_client_caching: bool) -> None:
        """Allows for a global setting to enable or disable caching of the Synapse
        client object. **If you are working in a multi-user environment you should set
        this to False to prevent any possibility of picking up another user session.**


        As a consequence of setting this to false you must pass a Synapse class instance
        to any function, method, or class that requires it - If if it is marked as
        `Optional`.
        """
        Synapse._allow_client_caching = allow_client_caching

    @staticmethod
    def enable_open_telemetry(
        enable_open_telemetry_tracing: bool = True,
        enable_open_telemetry_metrics: bool = False,
        *,
        resource_attributes: Optional[Dict[str, Any]] = None,
        include_context: bool = True,
    ) -> None:
        """Enables OpenTelemetry instrumentation for the Synapse client to collect telemetry data
        about your application's performance and behavior. This data can provide insights into
        latency, errors, and other performance metrics.

        Note: This is a one-way operation - once enabled, OpenTelemetry cannot be disabled within
        the same process. To disable it, you must restart your Python interpreter or application.

        When enabled, this method automatically:
        1. Sets up instrumentation for dependent libraries:
            - **Threading** (via `ThreadingInstrumentor`): Ensures proper context propagation
              across threads for maintaining trace continuity in multi-threaded applications
            - **HTTP libraries**:
                - `requests` (via `RequestsInstrumentor`): Captures all HTTP requests, including
                  methods, URLs, status codes, and timing information
                - `httpx` (via `HTTPXClientInstrumentor`): Tracks both synchronous and
                  asynchronous HTTP requests
                - `urllib` (via `URLLibInstrumentor`): Monitors lower-level HTTP operations
            - Each instrumented HTTP library includes custom hooks that extract Synapse entity
              IDs from URLs and add them as span attributes
        2. Configures traces to collect spans across your application:
            - Spans automatically capture operation duration, status, and errors
            - Attributes like `synapse.transfer.direction` and `synapse.operation.category`
              are properly propagated to child spans
            - Trace data is exported via OTLP (OpenTelemetry Protocol)
        3. Adds resource information to your traces, including:
            - Python version
            - OS type
            - Synapse client version
            - Service name and instance ID

        Environment Variable Configuration:
            - `OTEL_SERVICE_NAME`: Defines a unique identifier for your application or service
              (defaults to 'synapseclient'). Set this to a descriptive name that represents your
              specific implementation for easier filtering and analysis.
            - `OTEL_EXPORTER_OTLP_ENDPOINT`: Specifies the destination URL for sending telemetry
              data (defaults to 'http://localhost:4318/v1/traces'). Configure this to direct
              traces to your preferred collector or monitoring service.
            - `OTEL_DEBUG_CONSOLE`: Controls local visibility of telemetry data. Set to 'true' to
              output trace information to the console for development and troubleshooting.
            - `OTEL_SERVICE_INSTANCE_ID`: Distinguishes between multiple instances of the same
              service (e.g., 'prod', 'development', 'local') to identify which specific
              deployment generated particular traces.
            - `OTEL_EXPORTER_OTLP_HEADERS`: Configures authentication and metadata for telemetry
              exports. Use this to add API keys, tokens, or custom metadata when sending traces
              to secured collectors.

        Args:
            enable_open_telemetry_tracing: Whether to enable tracing (defaults to True).
            enable_open_telemetry_metrics: Whether to enable metrics collection (defaults to False).
            resource_attributes: Additional attributes to include with telemetry data, which can
                override environment variables like service name and instance ID.
            include_context: Whether to include runtime environment context (defaults to True).

        Example: Basic usage
            ```python
            import synapseclient

            # Enable OpenTelemetry with default settings
            synapseclient.Synapse.enable_open_telemetry()

            # Get a tracer and create custom spans for your code
            tracer = synapseclient.Synapse.get_tracer()

            # Use the tracer to create spans around your operations
            with tracer.start_as_current_span("my_operation"):
                syn = synapseclient.Synapse()
                syn.login()

                # Create nested spans for more detailed tracing
                with tracer.start_as_current_span("data_processing"):
                    # Your code here
                    pass
            ```

        Example: Custom configuration with resource attributes
            ```python
            import synapseclient
            import os

            # Set environment variables for telemetry configuration
            os.environ["OTEL_SERVICE_NAME"] = "my-synapse-app"
            os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = "https://collector.example.com:4318"

            # Enable with custom resource attributes that override some environment variables
            synapseclient.Synapse.enable_open_telemetry(
                resource_attributes={
                    "deployment.environment": "production",
                    "service.version": "1.2.3",
                    "service.instance.id": "instance-1", # Overrides OTEL_SERVICE_INSTANCE_ID
                    "custom.attribute": "value"
                }
            )

            syn = synapseclient.Synapse()
            syn.login()
            ```
        """
        set_up_telemetry(
            enable_open_telemetry_tracing=enable_open_telemetry_tracing,
            enable_open_telemetry_metrics=enable_open_telemetry_metrics,
            resource_attributes=resource_attributes,
            include_context=include_context,
        )

    @classmethod
    def get_tracer(cls, name: Optional[str] = None) -> trace.Tracer:
        """Returns an OpenTelemetry tracer that can be used to create spans and collect telemetry data.

        The tracer allows you to create custom spans to track specific operations in your code,
        making it easier to analyze performance and troubleshoot issues. You can create spans,
        add attributes, events, and links to provide rich context about your application's behavior.

        Note: OpenTelemetry must be enabled via `Synapse.enable_open_telemetry()` before using this method.

        Args:
            name: Optional name for the tracer. If not provided, the default Synapse tracer is used.
                 Use this to create separate tracers for different components of your application.

        Returns:
            An OpenTelemetry Tracer instance that can be used to create spans.

        Example: Creating spans with the tracer
            ```python
            import synapseclient
            from opentelemetry.trace.status import Status, StatusCode

            # Enable OpenTelemetry first
            synapseclient.Synapse.enable_open_telemetry()
            syn = synapseclient.login()

            # Get a tracer
            tracer = synapseclient.Synapse.get_tracer()

            # Create a parent span
            with tracer.start_as_current_span("my_operation") as span:
                # Add attributes to provide context
                span.set_attribute("library.operation.type", "data_processing")
                span.set_attribute("library.entity.id", "syn123456")

                # Your code here

                # Create a child span for a sub-operation
                with tracer.start_as_current_span("data_validation") as child_span:
                    child_span.set_attribute("library.validation.type", "schema")
                    # More code here

                    # Add an event to mark a significant occurrence
                    child_span.add_event("validation_complete",
                                        {"records_processed": 100})
            ```

        Example: Using multiple named tracers
            ```python
            import synapseclient

            # Enable OpenTelemetry
            synapseclient.Synapse.enable_open_telemetry()

            data_tracer = synapseclient.Synapse.get_tracer("data_operations")
            syn = synapseclient.login()

            with data_tracer.start_as_current_span("data_download"):
                # Data download code
                pass
            ```
        """
        return otel_config_get_tracer(name=name)

    @classmethod
    def set_client(cls, synapse_client) -> None:
        cls._synapse_client = synapse_client

    @property
    def max_threads(self) -> int:
        return self._max_threads

    @max_threads.setter
    def max_threads(self, value: int):
        self._max_threads = min(max(value, 1), MAX_THREADS_CAP)

    @property
    def username(self) -> Union[str, None]:
        # for backwards compatability when username was a part of the Synapse object and not in credentials
        return self.credentials.username if self.credentials is not None else None

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/configuration_services.py::get_config_file",
    )
    @functools.lru_cache()
    def getConfigFile(self, configPath: str) -> configparser.RawConfigParser:
        """
        Retrieves the client configuration information.

        Arguments:
            configPath:  Path to configuration file on local file system

        Returns:
            A RawConfigParser populated with properties from the user's configuration file.
        """

        try:
            config = configparser.RawConfigParser()
            config.read(configPath)  # Does not fail if the file does not exist
            return config
        except configparser.Error as ex:
            raise ValueError(
                "Error parsing Synapse config file: {}".format(configPath)
            ) from ex

    def setEndpoints(
        self,
        repoEndpoint: str = None,
        authEndpoint: str = None,
        fileHandleEndpoint: str = None,
        portalEndpoint: str = None,
        skip_checks: bool = False,
    ) -> None:
        """
        Sets the locations for each of the Synapse services (mostly useful for testing).

        Arguments:
            repoEndpoint:          Location of synapse repository
            authEndpoint:          Location of authentication service
            fileHandleEndpoint:    Location of file service
            portalEndpoint:        Location of the website
            skip_checks:           Skip version and endpoint checks

        Example: Switching endpoints
            To switch between staging and production endpoints

                syn.setEndpoints(**synapseclient.client.STAGING_ENDPOINTS)
                syn.setEndpoints(**synapseclient.client.PRODUCTION_ENDPOINTS)

        """

        endpoints = {
            "repoEndpoint": repoEndpoint,
            "authEndpoint": authEndpoint,
            "fileHandleEndpoint": fileHandleEndpoint,
            "portalEndpoint": portalEndpoint,
        }

        # For unspecified endpoints, first look in the config file
        config = get_config_file(self.configPath)
        for point in endpoints.keys():
            if endpoints[point] is None and config.has_option("endpoints", point):
                endpoints[point] = config.get("endpoints", point)

        # Endpoints default to production
        for point in endpoints.keys():
            if endpoints[point] is None:
                endpoints[point] = PRODUCTION_ENDPOINTS[point]

            # Update endpoints if we get redirected
            if not skip_checks:
                response = with_retry(
                    lambda point=point: self._requests_session.get(
                        endpoints[point],
                        allow_redirects=False,
                        headers=synapseclient.USER_AGENT,
                        timeout=self._http_timeout_seconds,
                    ),
                    verbose=self.debug,
                    **{**STANDARD_RETRY_PARAMS, "retries": 2},
                )
                if response.status_code == 301:
                    endpoints[point] = response.headers["location"]

        self.repoEndpoint = endpoints["repoEndpoint"]
        self.authEndpoint = endpoints["authEndpoint"]
        self.fileHandleEndpoint = endpoints["fileHandleEndpoint"]
        self.portalEndpoint = endpoints["portalEndpoint"]

    def login(
        self,
        email: str = None,
        silent: bool = False,
        authToken: str = None,
        profile: str = "default",
    ) -> None:
        """
        Valid combinations of login() arguments:

        - authToken
        - Profile-based authentication (from .synapseConfig)

        If no login arguments are provided or only username is provided, login() will attempt to log in using
         information from these sources (in order of preference):

        1. .synapseConfig file (supports multiple profiles)(in user home folder unless configured otherwise)
        2. User defined arguments during a CLI session
        3. User's Personal Access Token (aka: Synapse Auth Token)
            from the environment variable: SYNAPSE_AUTH_TOKEN
        4. Retrieves user's authentication token from AWS SSM Parameter store (if configured)

        Arguments:
            email (str): Synapse user name (or an email address associated with a Synapse account)
            authToken (str): A bearer authorization token, e.g. a
                [personal access token](https://python-docs.synapse.org/tutorials/authentication/).
            silent (bool): Defaults to False.  Suppresses the "Welcome ...!" message.
            profile (str): Profile to use from .synapseConfig (default: "default").

        Example: Logging in
        - Logging in using a specific profile:
                import synapseclient
                syn = synapseclient.login(profile="user1)
                > Welcome, username! You are using the user1 profile

        - Logging in with an authentication token:
            import synapseclient
            syn = synapseclient.login(authToken = "your_auth_token"))
            > Welcome, username!
        """
        # Note: the order of the logic below reflects the ordering in the docstring above.

        # Check version before logging in
        if not self.skip_checks:
            version_check(logger=self.logger)

        # Make sure to invalidate the existing session
        self.logout()

        user_login_args = UserLoginArgs(
            profile=profile, username=email, auth_token=authToken
        )
        credential_provider_chain = get_default_credential_chain()
        self.credentials = credential_provider_chain.get_credentials(
            syn=self, user_login_args=user_login_args
        )

        # Final check on login success
        if not self.credentials:
            raise SynapseNoCredentialsError(
                f"No valid authentication credentials provided.\n"
                f"Tried profile: '{profile}', email: '{email or 'N/A'}'.\n"
                "Check your `.synapseConfig` or ensure the provided auth token is valid."
            )

        if not silent:
            display_name = self.credentials.displayname or self.credentials.username
            if (
                not self.credentials.profile_name
                or self.credentials.profile_name.lower()
                == config_file_constants.AUTHENTICATION_SECTION_NAME
            ):
                self.logger.info(f"Welcome, {display_name}!\n")
            else:
                self.logger.info(
                    f"Welcome, {display_name}! You are using the '{self.credentials.profile_name}' profile."
                )

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/configuration_services.py::get_config_section_dict",
    )
    def _get_config_section_dict(self, section_name: str) -> Dict[str, str]:
        """
        Get a profile section in the configuration file with the section name.

        Arguments:
            section_name: The name of the profile section in the configuration file

        Returns:
            A dictionary containing the configuration profile section content
        """
        config = get_config_file(self.configPath)
        try:
            return dict(config.items(section_name))
        except configparser.NoSectionError:
            # section not present
            return {}

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/configuration_services.py::get_config_authentication",
    )
    def _get_config_authentication(self) -> Dict[str, str]:
        """
        Get the authentication section of the configuration file.

        Returns:
            The authentication section of the configuration file
        """
        return get_config_section_dict(
            section_name=config_file_constants.AUTHENTICATION_SECTION_NAME,
            config_path=self.configPath,
        )

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/configuration_services.py::get_client_authenticated_s3_profile",
    )
    def _get_client_authenticated_s3_profile(
        self, endpoint: str, bucket: str
    ) -> Dict[str, str]:
        """
        Get the authenticated S3 profile from the configuration file.

        Arguments:
            endpoint: The location of the target service
            bucket:   AWS S3 bucket name

        Returns:
            The authenticated S3 profile
        """
        config_section = endpoint + "/" + bucket
        return get_config_section_dict(
            section_name=config_section, config_path=self.configPath
        ).get("profile_name", "default")

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/configuration_services.py::get_transfer_config",
    )
    def _get_transfer_config(self) -> Dict[str, str]:
        """
        Get the transfer profile from the configuration file.

        Raises:
            ValueError: Invalid max_threads value. Should be equal or less than 16.
            ValueError: Invalid use_boto_sts value. Should be true or false.

        Returns:
            The transfer profile
        """
        # defaults
        transfer_config = {"max_threads": DEFAULT_NUM_THREADS, "use_boto_sts": False}

        for k, v in get_config_section_dict(
            section_name="transfer", config_path=self.configPath
        ).items():
            if v:
                if k == "max_threads" and v:
                    try:
                        transfer_config["max_threads"] = int(v)
                    except ValueError as cause:
                        raise ValueError(
                            f"Invalid transfer.max_threads config setting {v}"
                        ) from cause

                elif k == "use_boto_sts":
                    lower_v = v.lower()
                    if lower_v not in ("true", "false"):
                        raise ValueError(
                            f"Invalid transfer.use_boto_sts config setting {v}"
                        )

                    transfer_config["use_boto_sts"] = "true" == lower_v

        return transfer_config

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _is_logged_in(self) -> bool:
        """
        Test whether the user is logged in to Synapse.

        Returns:
            Boolean value indicating current user's login status
        """
        # This is a quick sanity check to see if credentials have been
        # configured on the client
        if self.credentials is None:
            return False
        # The public can query this command so there is no need to try catch.
        user = self.restGET("/userProfile")
        if user.get("userName") == "anonymous":
            return False
        return True

    def logout(self) -> None:
        """
        Removes authentication information from the Synapse client.

        Returns:
            None
        """
        self.credentials = None

    @deprecated(
        version="4.0.0",
        reason="deprecated with no replacement. The client does not support API keys for "
        "authentication. Please use a personal access token instead. This method will "
        "be removed in a future release.",
    )
    def invalidateAPIKey(self):
        """
        **Deprecated with no replacement.** The client does not support API keys for
        authentication. Please use a
        [personal access token](https://python-docs.synapse.org/tutorials/authentication/)
        instead. This method will be removed in a future release.


        Invalidates authentication across all clients.

        Returns:
            None
        """

        # Logout globally
        if self._is_logged_in():
            self.restDELETE("/secretKey", endpoint=self.authEndpoint)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `from_username` method on the `from synapseclient.models import UserProfile` class. "
        "Check the docstring for the replacement function example.",
    )
    @functools.lru_cache()
    def get_user_profile_by_username(
        self,
        username: str = None,
        sessionToken: str = None,
    ) -> UserProfile:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the [from_username][synapseclient.models.UserProfile.from_username] method on the `from synapseclient.models import UserProfile` class.

        Get the details about a Synapse user.
        Retrieves information on the current user if 'id' is omitted or is empty string.

        Arguments:
            username:     The userName of a user
            sessionToken: The session token to use to find the user profile

        Returns:
            The user profile for the user of interest.

        Example: Using this function (DEPRECATED)
            Getting your own profile

                my_profile = syn.get_user_profile_by_username()

            Getting another user's profile

                users_profile = syn.get_user_profile_by_username('synapse-service-dpe-team')

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import UserProfile

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get your own profile
            my_profile = UserProfile().get()
            print(f"My profile: {my_profile.username}")

            # Get another user's profile by username
            profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
            print(f"Profile by username: {profile_by_username.username}")
            ```
        """
        is_none = username is None
        is_str = isinstance(username, str)
        if not is_str and not is_none:
            raise TypeError("username must be string or None")
        if is_str:
            principals = self._findPrincipals(username)
            for principal in principals:
                if principal.get("userName", None).lower() == username.lower():
                    id = principal["ownerId"]
                    break
            else:
                raise ValueError(f"Can't find user '{username}'")
        else:
            id = ""
        uri = f"/userProfile/{id}"
        return UserProfile(
            **self.restGET(
                uri, headers={"sessionToken": sessionToken} if sessionToken else None
            )
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `from_id` method on the `from synapseclient.models import UserProfile` class. "
        "Check the docstring for the replacement function example.",
    )
    @functools.lru_cache()
    def get_user_profile_by_id(
        self,
        id: int = None,
        sessionToken: str = None,
    ) -> UserProfile:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.UserProfile.from_id][] instead.

        Get the details about a Synapse user.
        Retrieves information on the current user if 'id' is omitted.

        Arguments:
            id:           The ownerId of a user
            sessionToken: The session token to use to find the user profile

        Returns:
            The user profile for the user of interest.

        Example: Using this function (DEPRECATED)
            Getting your own profile

                my_profile = syn.get_user_profile_by_id()

            Getting another user's profile

                users_profile = syn.get_user_profile_by_id(3485485)

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import UserProfile

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get your own profile
            my_profile = UserProfile().get()
            print(f"My profile: {my_profile.username}")

            # Get another user's profile by ID
            profile_by_id = UserProfile.from_id(user_id=3485485)
            print(f"Profile by id: {profile_by_id.username}")
            ```
        """
        if id:
            if not isinstance(id, int):
                raise TypeError("id must be an 'ownerId' integer")
        else:
            id = ""
        uri = f"/userProfile/{id}"
        return UserProfile(
            **self.restGET(
                uri, headers={"sessionToken": sessionToken} if sessionToken else None
            )
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `from_id` and `from_username` methods on the `from synapseclient.models import UserProfile` class. "
        "Check the docstring for the replacement function example.",
    )
    @functools.lru_cache()
    def getUserProfile(
        self,
        id: Union[str, int, UserProfile, TeamMember] = None,
        sessionToken: str = None,
    ) -> UserProfile:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.protocols.user_protocol.from_id][] instead.

        Get the details about a Synapse user.
        Retrieves information on the current user if 'id' is omitted.

        Arguments:
            id:           The 'userId' (aka 'ownerId') of a user or the userName
            sessionToken: The session token to use to find the user profile

        Returns:
            The user profile for the user of interest.

        Example: Using this function (DEPRECATED)
            Getting your own profile

                my_profile = syn.getUserProfile()

            Getting another user's profile

                users_profile = syn.getUserProfile('synapse-service-dpe-team')

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import UserProfile

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get your own profile
            my_profile = UserProfile().get()
            print(f"My profile: {my_profile.username}")

            # Get another user's profile by username
            profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
            print(f"Profile by username: {profile_by_username.username}")

            # Get another user's profile by ID
            profile_by_id = UserProfile.from_id(user_id=3485485)
            print(f"Profile by id: {profile_by_id.username}")
            ```
        """
        try:
            # if id is unset or a userID, this will succeed
            id = "" if id is None else int(id)
        except (TypeError, ValueError):
            if isinstance(id, collections.abc.Mapping) and "ownerId" in id:
                id = id.ownerId
            elif isinstance(id, TeamMember):
                id = id.member.ownerId
            else:
                principals = self._findPrincipals(id)
                if len(principals) == 1:
                    id = principals[0]["ownerId"]
                else:
                    for principal in principals:
                        if principal.get("userName", None).lower() == id.lower():
                            id = principal["ownerId"]
                            break
                    else:  # no break
                        raise ValueError('Can\'t find user "%s": ' % id)
        uri = "/userProfile/%s" % id
        return UserProfile(
            **self.restGET(
                uri, headers={"sessionToken": sessionToken} if sessionToken else None
            )
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _findPrincipals(self, query_string: str) -> List[UserGroupHeader]:
        """
        Find users or groups by name or email.

        Returns:
            A list of userGroupHeader objects with fields displayName, email, firstName, lastName, isIndividual, ownerId


        Example: Using this function
            Find userGroupHeader objects for test user

                syn._findPrincipals('test')

                [{u'displayName': u'Synapse Test',
                u'email': u'syn...t@sagebase.org',
                u'firstName': u'Synapse',
                u'isIndividual': True,
                u'lastName': u'Test',
                u'ownerId': u'1560002'},
                {u'displayName': ... }]
        """
        uri = "/userGroupHeaders?prefix=%s" % urllib_urlparse.quote(query_string)
        return [UserGroupHeader(**result) for result in self._GET_paginated(uri)]

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _get_certified_passing_record(
        self, userid: int
    ) -> Dict[str, Union[str, int, bool, list]]:
        """
        Retrieve the Passing Record on the User Certification test for the given user.

        Arguments:
            userid: Synapse user Id

        Returns:
            Synapse Passing Record. A record of whether a given user passed a given test.
            <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/quiz/PassingRecord.html>
        """
        response = self.restGET(f"/user/{userid}/certifiedUserPassingRecord")
        return response

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _get_user_bundle(self, userid: int, mask: int) -> Dict[str, Union[str, dict]]:
        """
        Retrieve the user bundle for the given user.

        Arguments:
            userid: Synapse user Id
            mask:   Bit field indicating which components to include in the bundle.

        Returns:
            [Synapse User Bundle](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/UserBundle.html)
        """
        try:
            response = self.restGET(f"/user/{userid}/bundle?mask={mask}")
        except SynapseHTTPError as ex:
            if ex.response.status_code == 404:
                return None
        return response

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `is_certified` method on the `from synapseclient.models import UserProfile` class. "
        "Check the docstring for the replacement function example.",
    )
    def is_certified(self, user: typing.Union[str, int]) -> bool:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.UserProfile.is_certified][] instead.

        Determines whether a Synapse user is a certified user.

        Arguments:
            user: Synapse username or Id

        Returns:
            True if the Synapse user is certified

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import UserProfile

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Check if user is certified by username
            profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
            user_certified = profile_by_username.is_certified()
            print(f"User {profile_by_username.username} is certified: {user_certified}")

            # Check if user is certified by ID
            profile_by_id = UserProfile.from_id(user_id=3485485)
            user_certified = profile_by_id.is_certified()
            print(f"User {profile_by_id.username} is certified: {user_certified}")
            ```
        """
        # Check if userid or username exists
        syn_user = self.getUserProfile(user)
        # Get passing record

        try:
            certification_status = self._get_certified_passing_record(
                syn_user["ownerId"]
            )
            return certification_status["passed"]
        except SynapseHTTPError as ex:
            if ex.response.status_code == 404:
                # user hasn't taken the quiz
                return False
            raise

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import is_synapse_id` instead.",
    )
    def is_synapse_id(self, syn_id: str) -> bool:
        """Checks if given synID is valid (attached to actual entity?)

        Arguments:
            syn_id: A Synapse ID

        Returns:
            True if the Synapse ID is valid
        """
        if isinstance(syn_id, str):
            try:
                self.get(syn_id, downloadFile=False)
            except SynapseFileNotFoundError:
                return False
            except (
                SynapseHTTPError,
                SynapseAuthenticationError,
            ) as err:
                status = (
                    err.__context__.response.status_code or err.response.status_code
                )
                if status in (400, 404):
                    return False
                # Valid ID but user lacks permission or is not logged in
                elif status == 403:
                    return True
            return True
        self.logger.warning("synID must be a string")
        return False

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import onweb` instead.",
    )
    def onweb(self, entity, subpageId=None):
        """Opens up a browser window to the entity page or wiki-subpage.

        Arguments:
            entity:    Either an Entity or a Synapse ID
            subpageId: (Optional) ID of one of the wiki's sub-pages

        Returns:
            None
        """
        if isinstance(entity, str) and os.path.isfile(entity):
            entity = self.get(entity, downloadFile=False)
        synId = id_of(entity)
        if subpageId is None:
            webbrowser.open("%s/Synapse:%s" % (self.portalEndpoint, synId))
        else:
            webbrowser.open(
                "%s/Wiki:%s/ENTITY/%s" % (self.portalEndpoint, synId, subpageId)
            )

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import print_entity` instead.",
    )
    def printEntity(self, entity, ensure_ascii=True) -> None:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.operations.print_entity][] instead.

        Pretty prints an Entity.

        Arguments:
            entity: The entity to be printed.
            ensure_ascii: If True, escapes all non-ASCII characters

        Example: Migration to new function
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.operations import print_entity

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Print an entity by Synapse ID
            print_entity("syn123456")

            # Print an entity object
            from synapseclient.operations import get
            entity = get(synapse_id="syn123456")
            print_entity(entity)

            # Print with unicode characters preserved
            print_entity("syn123456", ensure_ascii=False)
            ```

        Returns:
            None
        """

        if utils.is_synapse_id_str(entity):
            synid, version = utils.get_synid_and_version(entity)
            entity = self._getEntity(synid, version)
        try:
            self.logger.info(
                json.dumps(entity, sort_keys=True, indent=2, ensure_ascii=ensure_ascii)
            )
        except TypeError:
            self.logger.info(str(entity))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _print_transfer_progress(self, *args, **kwargs) -> None:
        """
        Checking synapse if the mode is silent mode.
        If self.silent is True, no need to print out transfer progress.
        """
        if self.silent is not True:
            logger = kwargs.pop("logger", self.logger)
            cumulative_transfer_progress.printTransferProgress(
                *args, logger=logger, **kwargs
            )

    ############################################################
    #                      Service methods                     #
    ############################################################

    _services = {
        "json_schema": "JsonSchemaService",
    }

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. This is a beta feature with no replacement.",
    )
    def get_available_services(self) -> typing.List[str]:
        """Get available Synapse services
        This is a beta feature and is subject to change

        Returns:
            List of available services
        """
        services = self._services.keys()
        return list(services)

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. This is a beta feature with no replacement.",
    )
    def service(self, service_name: str):
        """Get available Synapse services
        This is a beta feature and is subject to change

        Arguments:
            service_name: name of the service
        """
        # This is to avoid circular imports
        # TODO: revisit the import order and method https://stackoverflow.com/a/37126790
        # To move this to the top
        import synapseclient.services

        assert isinstance(service_name, str)
        service_name = service_name.lower().replace(" ", "_")
        assert service_name in self._services, (
            f"Unrecognized service ({service_name}). Run the 'get_available_"
            "services()' method to get a list of available services."
        )
        service_attr = self._services[service_name]
        service_cls = getattr(synapseclient.services, service_attr)
        service = service_cls(self)
        return service

    ############################################################
    #                   Get / Store methods                    #
    ############################################################

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import get` instead.",
    )
    def get(self, entity, **kwargs):
        """
        Gets a Synapse entity from the repository service.

        Arguments:
            entity:           A Synapse ID (e.g. syn123 or syn123.1, with .1 denoting version), a Synapse Entity object,
                              a plain dictionary in which 'id' maps to a Synapse ID or a local file that is stored in
                              Synapse (found by the file MD5)
            version:          The specific version to get.
                                Defaults to the most recent version. If not denoted in the entity input.
            downloadFile:     Whether associated files(s) should be downloaded.
                                Defaults to True.
            downloadLocation: Directory where to download the Synapse File Entity.
                                Defaults to the local cache.
            followLink:       Whether the link returns the target Entity.
                                Defaults to False.
            ifcollision:      Determines how to handle file collisions.
                                May be "overwrite.local", "keep.local", or "keep.both".
                                Defaults to "keep.both".
            limitSearch:      A Synanpse ID used to limit the search in Synapse if entity is specified as a local
                                file.  That is, if the file is stored in multiple locations in Synapse only the ones
                                in the specified folder/project will be returned.
            md5: The MD5 checksum for the file, if known. Otherwise if the file is a
                local file, it will be calculated automatically.

        Returns:
            A new Synapse Entity object of the appropriate type.

        Example: Using this function
            Download file into cache

                entity = syn.get('syn1906479')
                print(entity.name)
                print(entity.path)

            Download file into current working directory

                entity = syn.get('syn1906479', downloadLocation='.')
                print(entity.name)
                print(entity.path)

            Determine the provenance of a locally stored file as indicated in Synapse

                entity = syn.get('/path/to/file.txt', limitSearch='syn12312')
                print(syn.getProvenance(entity))
        """
        return wrap_async_to_sync(self.get_async(entity, **kwargs))

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1623
    async def get_async(self, entity, **kwargs):
        """
        Gets a Synapse entity from the repository service.

        Arguments:
            entity:           A Synapse ID (e.g. syn123 or syn123.1, with .1 denoting version), a Synapse Entity object,
                              a plain dictionary in which 'id' maps to a Synapse ID or a local file that is stored in
                              Synapse (found by the file MD5)
            version:          The specific version to get.
                                Defaults to the most recent version. If not denoted in the entity input.
            downloadFile:     Whether associated files(s) should be downloaded.
                                Defaults to True.
            downloadLocation: Directory where to download the Synapse File Entity.
                                Defaults to the local cache.
            followLink:       Whether the link returns the target Entity.
                                Defaults to False.
            ifcollision:      Determines how to handle file collisions.
                                May be "overwrite.local", "keep.local", or "keep.both".
                                Defaults to "keep.both".
            limitSearch:      A Synanpse ID used to limit the search in Synapse if entity is specified as a local
                                file.  That is, if the file is stored in multiple locations in Synapse only the ones
                                in the specified folder/project will be returned.
            md5: The MD5 checksum for the file, if known. Otherwise if the file is a
                local file, it will be calculated automatically.

        Returns:
            A new Synapse Entity object of the appropriate type.

        Example: Using this function
            Download file into cache

                entity = syn.get('syn1906479')
                print(entity.name)
                print(entity.path)

            Download file into current working directory

                entity = syn.get('syn1906479', downloadLocation='.')
                print(entity.name)
                print(entity.path)

            Determine the provenance of a locally stored file as indicated in Synapse

                entity = syn.get('/path/to/file.txt', limitSearch='syn12312')
                print(syn.getProvenance(entity))
        """
        # If entity is a local file determine the corresponding synapse entity
        if isinstance(entity, str) and os.path.isfile(entity):
            bundle = self._getFromFile(
                entity, kwargs.pop("limitSearch", None), md5=kwargs.get("md5", None)
            )
            kwargs["downloadFile"] = False
            kwargs["path"] = entity

        elif isinstance(entity, str) and not utils.is_synapse_id_str(entity):
            raise SynapseFileNotFoundError(
                (
                    "The parameter %s is neither a local file path "
                    " or a valid entity id" % entity
                )
            )
        # have not been saved entities
        elif isinstance(entity, Entity) and not entity.get("id"):
            raise ValueError(
                "Cannot retrieve entity that has not been saved."
                " Please use syn.store() to save your entity and try again."
            )
        else:
            input_version = kwargs.get("version", None)
            synid_and_version = utils.get_synid_and_version(entity)
            version = (
                input_version if input_version is not None else synid_and_version[1]
            )
            # If ``version`` is None, the arg will be ignored
            bundle = self._getEntityBundle(synid_and_version[0], version)

        # Check and warn for unmet access requirements
        self._check_entity_restrictions(
            bundle, entity, kwargs.get("downloadFile", True)
        )

        return_data = await self._getWithEntityBundle_async(
            entityBundle=bundle, entity=entity, **kwargs
        )
        trace.get_current_span().set_attributes(
            {
                "synapse.id": return_data.get("id", ""),
                "synapse.concrete_type": return_data.get("concreteType", ""),
            }
        )
        return return_data

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _check_entity_restrictions(
        self, bundle: dict, entity: Union[str, Entity, dict], downloadFile: bool
    ) -> None:
        """
        Check and warn for unmet access requirements.

        Arguments:
            bundle: A Synapse entityBundle
            entity: A Synapse ID, a Synapse Entity object, a plain dictionary in which 'id' maps to a
                    Synapse ID or a local file that is stored in Synapse (found by the file MD5)
            downloadFile: Whether associated files(s) should be downloaded.

        Raises:
            SynapseUnmetAccessRestrictions: Warning for unmet access requirements.
        """
        restriction_information = bundle.get("restrictionInformation", None)
        if restriction_information and restriction_information.get(
            "hasUnmetAccessRequirement", None
        ):
            if not self.credentials or not self.credentials._token:
                warning_message = (
                    "You have not provided valid credentials for authentication with Synapse."
                    " Please provide an authentication token and use `synapseclient.login()` before your next attempt."
                    " See https://python-docs.synapse.org/tutorials/authentication/ for more information."
                )
            else:
                warning_message = (
                    "\nThis entity has access restrictions. Please visit the web page for this entity "
                    f'(syn.onweb("{id_of(entity)}")). Look for the "Access" label and the lock icon underneath '
                    'the file name. Click "Request Access", and then review and fulfill the file '
                    "download requirement(s).\n"
                )
            if downloadFile and bundle.get("entityType") not in ("project", "folder"):
                raise SynapseUnmetAccessRestrictions(warning_message)
            self.logger.warning(warning_message)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getFromFile(
        self, filepath: str, limitSearch: str = None, md5: str = None
    ) -> Dict[str, dict]:
        """
        Gets a Synapse entityBundle based on the md5 of a local file.
        See [get][synapseclient.Synapse.get].

        Arguments:
            filepath:    The path to local file
            limitSearch: Limits the places in Synapse where the file is searched for.
            md5: The MD5 checksum for the file, if known. Otherwise if the file is a
                local file, it will be calculated automatically.


        Raises:
            SynapseFileNotFoundError: If the file is not in Synapse.

        Returns:
            A Synapse entityBundle
        """
        results = self.restGET(
            "/entity/md5/%s" % (md5 or utils.md5_for_file(filepath).hexdigest())
        )["results"]
        if limitSearch is not None:
            # Go through and find the path of every entity found
            paths = [self.restGET("/entity/%s/path" % ent["id"]) for ent in results]
            # Filter out all entities whose path does not contain limitSearch
            results = [
                ent
                for ent, path in zip(results, paths)
                if utils.is_in_path(limitSearch, path)
            ]
        if len(results) == 0:  # None found
            raise SynapseFileNotFoundError("File %s not found in Synapse" % (filepath,))
        elif len(results) > 1:
            id_txts = "\n".join(
                ["%s.%i" % (r["id"], r["versionNumber"]) for r in results]
            )
            self.logger.warning(
                "\nThe file %s is associated with many files in Synapse:\n%s\n"
                "You can limit to files in specific project or folder by setting the limitSearch to the"
                " synapse Id of the project or folder.\n"
                "Will use the first one returned: \n"
                "%s version %i\n"
                % (filepath, id_txts, results[0]["id"], results[0]["versionNumber"])
            )
        entity = results[0]

        bundle = self._getEntityBundle(entity, version=entity["versionNumber"])
        self.cache.add(bundle["entity"]["dataFileHandleId"], filepath)

        return bundle

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "This method uses legacy Entity objects. "
        "Use the new dataclass models (File, Folder, Table, etc.) with their `parent_id` attribute and `.store()` method instead. ",
    )
    def move(self, entity, new_parent):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the new dataclass models (File, Folder, Table, etc.) with their `parent_id`
        attribute and `.store()` method instead.

        Move a Synapse entity to a new container.

        Arguments:
            entity:     A Synapse ID, a Synapse Entity object, or a local file that is stored in Synapse
            new_parent: The new parent container (Folder or Project) to which the entity should be moved.

        Returns:
            The Synapse Entity object that has been moved.

        Example: Using this function (DEPRECATED)
            Move a Synapse Entity object to a new parent container

                entity = syn.move('syn456', 'syn123')

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                File, Folder, Table, Dataset, DatasetCollection,
                EntityView, SubmissionView, MaterializedView, VirtualTable
            )

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Moving a File
            file = File(id="syn456", download_file=False).get()
            file.parent_id = "syn123"
            file = file.store()
            print(f"Moved file to: {file.parent_id}")

            # Moving a Folder
            folder = Folder(id="syn789").get()
            folder.parent_id = "syn123"
            folder = folder.store()
            print(f"Moved folder to: {folder.parent_id}")

            # Moving a Table
            table = Table(id="syn101112").get()
            table.parent_id = "syn123"
            table = table.store()
            print(f"Moved table to: {table.parent_id}")

            # Moving a Dataset
            dataset = Dataset(id="syn131415").get()
            dataset.parent_id = "syn123"
            dataset = dataset.store()
            print(f"Moved dataset to: {dataset.parent_id}")

            # Moving a DatasetCollection
            dataset_collection = DatasetCollection(id="syn161718").get()
            dataset_collection.parent_id = "syn123"
            dataset_collection = dataset_collection.store()
            print(f"Moved dataset collection to: {dataset_collection.parent_id}")

            # Moving an EntityView
            entity_view = EntityView(id="syn192021").get()
            entity_view.parent_id = "syn123"
            entity_view = entity_view.store()
            print(f"Moved entity view to: {entity_view.parent_id}")

            # Moving a SubmissionView
            submission_view = SubmissionView(id="syn222324").get()
            submission_view.parent_id = "syn123"
            submission_view = submission_view.store()
            print(f"Moved submission view to: {submission_view.parent_id}")

            # Moving a MaterializedView
            materialized_view = MaterializedView(id="syn252627").get()
            materialized_view.parent_id = "syn123"
            materialized_view = materialized_view.store()
            print(f"Moved materialized view to: {materialized_view.parent_id}")

            # Moving a VirtualTable
            virtual_table = VirtualTable(id="syn282930").get()
            virtual_table.parent_id = "syn123"
            virtual_table = virtual_table.store()
            print(f"Moved virtual table to: {virtual_table.parent_id}")
            ```
        """

        entity = self.get(entity, downloadFile=False)
        entity.parentId = id_of(new_parent)
        entity = self.store(entity, forceVersion=False)
        trace.get_current_span().set_attributes(
            {
                "synapse.id": entity.get("id", ""),
                "synapse.parent_id": entity.get("parentId", ""),
            }
        )

        return entity

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getWithEntityBundle(
        self, entityBundle: dict, entity: Entity = None, **kwargs
    ) -> Entity:
        """
        Creates a [Entity][synapseclient.Entity] from an entity bundle returned by Synapse.
        An existing Entity can be supplied in case we want to refresh a stale Entity.

        Arguments:
            entityBundle: Uses the given dictionary as the meta information of the Entity to get
            entity:       Optional, entity whose local state will be copied into the returned entity
            submission:   Optional, access associated files through a submission rather than through an entity.

        Returns:
            A new Synapse Entity

        Also see:
        - See [get][synapseclient.Synapse.get].
        - See [_getEntityBundle][synapseclient.Synapse._getEntityBundle].
        - See [Entity][synapseclient.Entity].
        """
        return wrap_async_to_sync(
            self._getWithEntityBundle_async(entityBundle, entity, **kwargs)
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    async def _getWithEntityBundle_async(
        self, entityBundle: dict, entity: Entity = None, **kwargs
    ) -> Entity:
        """
        Creates a [Entity][synapseclient.Entity] from an entity bundle returned by Synapse.
        An existing Entity can be supplied in case we want to refresh a stale Entity.

        Arguments:
            entityBundle: Uses the given dictionary as the meta information of the Entity to get
            entity:       Optional, entity whose local state will be copied into the returned entity
            submission:   Optional, access associated files through a submission rather than through an entity.

        Returns:
            A new Synapse Entity

        Also see:
        - See [get][synapseclient.Synapse.get].
        - See [_getEntityBundle][synapseclient.Synapse._getEntityBundle].
        - See [Entity][synapseclient.Entity].
        """
        # Note: This version overrides the version of 'entity' (if the object is Mappable)
        kwargs.pop("version", None)
        downloadFile = kwargs.pop("downloadFile", True)
        downloadLocation = kwargs.pop("downloadLocation", None)
        ifcollision = kwargs.pop("ifcollision", None)
        submission = kwargs.pop("submission", None)
        followLink = kwargs.pop("followLink", False)
        path = kwargs.pop("path", None)

        # If Link, get target ID entity bundle
        if (
            entityBundle["entity"]["concreteType"]
            == "org.sagebionetworks.repo.model.Link"
            and followLink
        ):
            targetId = entityBundle["entity"]["linksTo"]["targetId"]
            targetVersion = entityBundle["entity"]["linksTo"].get("targetVersionNumber")
            entityBundle = self._getEntityBundle(targetId, targetVersion)

        # TODO is it an error to specify both downloadFile=False and downloadLocation?
        # TODO this matters if we want to return already cached files when downloadFile=False

        # Make a fresh copy of the Entity
        local_state = (
            entity.local_state() if entity and isinstance(entity, Entity) else {}
        )
        if path is not None:
            local_state["path"] = path
        properties = entityBundle["entity"]
        annotations = from_synapse_annotations(entityBundle["annotations"])
        entity = Entity.create(properties, annotations, local_state)

        # Handle download of fileEntities
        if isinstance(entity, File):
            # update the entity with FileHandle metadata
            file_handle = next(
                (
                    handle
                    for handle in entityBundle["fileHandles"]
                    if handle["id"] == entity.dataFileHandleId
                ),
                None,
            )
            entity._update_file_handle(file_handle)

            if downloadFile:
                if file_handle:
                    await download_file_entity(
                        download_location=downloadLocation,
                        entity=entity,
                        if_collision=ifcollision,
                        submission=submission,
                        synapse_client=self,
                    )
                else:  # no filehandle means that we do not have DOWNLOAD permission
                    warning_message = (
                        "WARNING: You have READ permission on this file entity but not DOWNLOAD "
                        "permission. The file has NOT been downloaded."
                    )
                    self.logger.warning(
                        "\n"
                        + "!" * len(warning_message)
                        + "\n"
                        + warning_message
                        + "\n"
                        + "!" * len(warning_message)
                        + "\n"
                    )
        return entity

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::ensure_download_location_is_directory",
    )
    def _ensure_download_location_is_directory(self, downloadLocation: str) -> str:
        """
        Check if the download location is a directory

        Arguments:
            downloadLocation: The download location

        Raises:
            ValueError: If the downloadLocation is not a directory

        Returns:
            The download location
        """
        download_dir = os.path.expandvars(os.path.expanduser(downloadLocation))
        if os.path.isfile(download_dir):
            raise ValueError(
                "Parameter 'downloadLocation' should be a directory, not a file."
            )
        return download_dir

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::download_file_entity",
    )
    def _download_file_entity(
        self,
        downloadLocation: str,
        entity: Entity,
        ifcollision: str,
        submission: str,
    ) -> None:
        """
        Download file entity

        Arguments:
            downloadLocation: The download location
            entity:           The Synapse Entity object
            ifcollision:      Determines how to handle file collisions.
                              May be

                - `overwrite.local`
                - `keep.local`
                - `keep.both`

            submission:       Access associated files through a submission rather than through an entity.
        """
        # set the initial local state
        entity.path = None
        entity.files = []
        entity.cacheDir = None

        # check to see if an UNMODIFIED version of the file (since it was last downloaded) already exists
        # this location could be either in .synapseCache or a user specified location to which the user previously
        # downloaded the file
        cached_file_path = self.cache.get(entity.dataFileHandleId, downloadLocation)

        # location in .synapseCache where the file would be corresponding to its FileHandleId
        synapseCache_location = self.cache.get_cache_dir(entity.dataFileHandleId)

        file_name = (
            entity._file_handle.fileName
            if cached_file_path is None
            else os.path.basename(cached_file_path)
        )

        # Decide the best download location for the file
        if downloadLocation is not None:
            # Make sure the specified download location is a fully resolved directory
            downloadLocation = self._ensure_download_location_is_directory(
                downloadLocation
            )
        elif cached_file_path is not None:
            # file already cached so use that as the download location
            downloadLocation = os.path.dirname(cached_file_path)
        else:
            # file not cached and no user-specified location so default to .synapseCache
            downloadLocation = synapseCache_location

        # resolve file path collisions by either overwriting, renaming, or not downloading, depending on the
        # ifcollision value
        downloadPath = self._resolve_download_path_collisions(
            downloadLocation,
            file_name,
            ifcollision,
            synapseCache_location,
            cached_file_path,
        )
        if downloadPath is None:
            return

        if cached_file_path is not None:  # copy from cache
            if downloadPath != cached_file_path:
                # create the foider if it does not exist already
                if not os.path.exists(downloadLocation):
                    os.makedirs(downloadLocation)
                shutil.copy(cached_file_path, downloadPath)

        else:  # download the file from URL (could be a local file)
            objectType = "FileEntity" if submission is None else "SubmissionAttachment"
            objectId = entity["id"] if submission is None else submission

            # reassign downloadPath because if url points to local file (e.g. file://~/someLocalFile.txt)
            # it won't be "downloaded" and, instead, downloadPath will just point to '~/someLocalFile.txt'
            # _downloadFileHandle may also return None to indicate that the download failed
            downloadPath = self._downloadFileHandle(
                entity.dataFileHandleId, objectId, objectType, downloadPath
            )

            if downloadPath is None or not os.path.exists(downloadPath):
                return

        # converts the path format from forward slashes back to backward slashes on Windows
        entity.path = os.path.normpath(downloadPath)
        entity.files = [os.path.basename(downloadPath)]
        entity.cacheDir = os.path.dirname(downloadPath)

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::resolve_download_path_collisions",
    )
    def _resolve_download_path_collisions(
        self,
        downloadLocation: str,
        file_name: str,
        ifcollision: str,
        synapseCache_location: str,
        cached_file_path: str,
    ) -> str:
        """
        Resolve file path collisions

        Arguments:
            downloadLocation:      The download location
            file_name:             The file name
            ifcollision:           Determines how to handle file collisions.
                                   May be "overwrite.local", "keep.local", or "keep.both".
            synapseCache_location: The location in .synapseCache where the file would be
                                   corresponding to its FileHandleId.
            cached_file_path:      The file path of the cached copy

        Raises:
            ValueError: Invalid ifcollision. Should be "overwrite.local", "keep.local", or "keep.both".

        Returns:
            The download file path with collisions resolved
        """
        # always overwrite if we are downloading to .synapseCache
        if utils.normalize_path(downloadLocation) == synapseCache_location:
            if ifcollision is not None and ifcollision != "overwrite.local":
                self.logger.warning(
                    "\n"
                    + "!" * 50
                    + f"\nifcollision={ifcollision} "
                    + "is being IGNORED because the download destination is synapse's cache."
                    ' Instead, the behavior is "overwrite.local". \n' + "!" * 50 + "\n"
                )
            ifcollision = "overwrite.local"
        # if ifcollision not specified, keep.local
        ifcollision = ifcollision or "keep.both"

        downloadPath = utils.normalize_path(os.path.join(downloadLocation, file_name))
        # resolve collison
        if os.path.exists(downloadPath):
            if ifcollision == "overwrite.local":
                pass
            elif ifcollision == "keep.local":
                # Don't want to overwrite the local file.
                return None
            elif ifcollision == "keep.both":
                if downloadPath != cached_file_path:
                    return utils.unique_filename(downloadPath)
            else:
                raise ValueError(
                    'Invalid parameter: "%s" is not a valid value '
                    'for "ifcollision"' % ifcollision
                )
        return downloadPath

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import store` instead.",
    )
    def store(
        self,
        obj,
        *,
        createOrUpdate=True,
        forceVersion=True,
        versionLabel=None,
        isRestricted=False,
        activity=None,
        used=None,
        executed=None,
        activityName=None,
        activityDescription=None,
        set_annotations=True,
    ):
        """
        Creates a new Entity or updates an existing Entity, uploading any files in the process.

        Arguments:
            obj: A Synapse Entity, Evaluation, or Wiki
            used: The Entity, Synapse ID, or URL used to create the object (can also be a list of these)
            executed: The Entity, Synapse ID, or URL representing code executed to create the object
                        (can also be a list of these)
            activity: Activity object specifying the user's provenance.
            activityName: Activity name to be used in conjunction with *used* and *executed*.
            activityDescription: Activity description to be used in conjunction with *used* and *executed*.
            createOrUpdate: Indicates whether the method should automatically perform an update if the 'obj'
                            conflicts with an existing Synapse object.
            forceVersion: Indicates whether the method should increment the version of the object even if nothing
                            has changed.
            versionLabel: Arbitrary string used to label the version.
            isRestricted: If set to true, an email will be sent to the Synapse access control team to start the
                            process of adding terms-of-use or review board approval for this entity.
                            You will be contacted with regards to the specific data being restricted and the
                            requirements of access.
            set_annotations: If True, set the annotations on the entity. If False, do not set the annotations.

        Returns:
            A Synapse Entity, Evaluation, or Wiki

        Example: Using this function
            Creating a new Project:

                from synapseclient import Project

                project = Project('My uniquely named project')
                project = syn.store(project)

            Adding files with [provenance (aka: Activity)][synapseclient.Activity]:

                from synapseclient import File, Activity

            A synapse entity *syn1906480* contains data and an entity *syn1917825* contains code

                activity = Activity(
                    'Fancy Processing',
                    description='No seriously, really fancy processing',
                    used=['syn1906480', 'http://data_r_us.com/fancy/data.txt'],
                    executed='syn1917825')

                test_entity = File('/path/to/data/file.xyz', description='Fancy new data', parent=project)
                test_entity = syn.store(test_entity, activity=activity)

        """
        return wrap_async_to_sync(
            coroutine=self.store_async(
                obj,
                createOrUpdate=createOrUpdate,
                forceVersion=forceVersion,
                versionLabel=versionLabel,
                isRestricted=isRestricted,
                activity=activity,
                used=used,
                executed=executed,
                activityName=activityName,
                activityDescription=activityDescription,
                set_annotations=set_annotations,
            )
        )

    async def store_async(
        self,
        obj,
        *,
        createOrUpdate=True,
        forceVersion=True,
        versionLabel=None,
        isRestricted=False,
        activity=None,
        used=None,
        executed=None,
        activityName=None,
        activityDescription=None,
        set_annotations=True,
    ):
        """
        Creates a new Entity or updates an existing Entity, uploading any files in the process.

        Arguments:
            obj: A Synapse Entity, Evaluation, or Wiki
            used: The Entity, Synapse ID, or URL used to create the object (can also be a list of these)
            executed: The Entity, Synapse ID, or URL representing code executed to create the object
                        (can also be a list of these)
            activity: Activity object specifying the user's provenance.
            activityName: Activity name to be used in conjunction with *used* and *executed*.
            activityDescription: Activity description to be used in conjunction with *used* and *executed*.
            createOrUpdate: Indicates whether the method should automatically perform an update if the 'obj'
                            conflicts with an existing Synapse object.
            forceVersion: Indicates whether the method should increment the version of the object even if nothing
                            has changed.
            versionLabel: Arbitrary string used to label the version.
            isRestricted: If set to true, an email will be sent to the Synapse access control team to start the
                            process of adding terms-of-use or review board approval for this entity.
                            You will be contacted with regards to the specific data being restricted and the
                            requirements of access.
            set_annotations: If True, set the annotations on the entity. If False, do not set the annotations.

        Returns:
            A Synapse Entity, Evaluation, or Wiki

        Example: Using this function
            Creating a new Project:

            ```python
            import asyncio
            from synapseclient import Project, Synapse

            syn = Synapse()
            syn.login()

            async def main():
                project = Project('My uniquely named project')
                project = await syn.store_async(project)

            asyncio.run(main())
            ```

            Adding files with [provenance (aka: Activity)][synapseclient.Activity]:

            A synapse entity *syn1906480* contains data and an entity *syn1917825* contains code

            ```python
            import asyncio
            from synapseclient import File, Activity, Synapse

            syn = Synapse()
            syn.login()


            activity = Activity(
                'Fancy Processing',
                description='No seriously, really fancy processing',
                used=['syn1906480', 'http://data_r_us.com/fancy/data.txt'],
                executed='syn1917825')

            test_entity = File('/path/to/data/file.xyz', description='Fancy new data', parent=project)

            async def main():
                test_entity = await syn.store_async(test_entity, activity=activity)

            asyncio.run(main())
            ```

        """
        trace.get_current_span().set_attributes({"thread.id": threading.get_ident()})
        # SYNPY-1031: activity must be Activity object or code will fail later
        if activity:
            if not isinstance(activity, synapseclient.Activity):
                raise ValueError("activity should be synapseclient.Activity object")
        # _before_store hook
        # give objects a chance to do something before being stored
        if hasattr(obj, "_before_synapse_store"):
            obj._before_synapse_store(self)

        # _synapse_store hook
        # for objects that know how to store themselves
        if hasattr(obj, "_synapse_store_async"):
            return await obj._synapse_store_async(self)
        elif hasattr(obj, "_synapse_store"):
            return obj._synapse_store(self)

        # Handle all non-Entity objects
        if not (isinstance(obj, Entity) or type(obj) == dict):
            if isinstance(obj, Wiki):
                return await self._storeWiki_async(obj, createOrUpdate)

            if "id" in obj:  # If ID is present, update
                trace.get_current_span().set_attributes({"synapse.id": obj["id"]})
                return type(obj)(**self.restPUT(obj.putURI(), obj.json()))

            try:  # If no ID is present, attempt to POST the object
                return type(obj)(**self.restPOST(obj.postURI(), obj.json()))

            except SynapseHTTPError as err:
                # If already present and we want to update attempt to get the object content
                if createOrUpdate and err.response.status_code == 409:
                    newObj = self.restGET(obj.getByNameURI(obj.name))
                    newObj.update(obj)
                    obj = type(obj)(**newObj)
                    trace.get_current_span().set_attributes({"synapse.id": obj["id"]})
                    obj.update(self.restPUT(obj.putURI(), obj.json()))
                    return obj
                raise

        # If the input object is an Entity or a dictionary
        entity = obj
        properties, annotations, local_state = split_entity_namespaces(entity)
        bundle = None
        # Explicitly set an empty versionComment property if none is supplied,
        # otherwise an existing entity bundle's versionComment will be copied to the update.
        properties["versionComment"] = (
            properties["versionComment"] if "versionComment" in properties else None
        )

        # Anything with a path is treated as a cache-able item
        # Only Files are expected in the following logic
        if entity.get("path", False) and not isinstance(obj, Folder):
            local_file_md5_hex = None
            if "concreteType" not in properties:
                properties["concreteType"] = File._synapse_entity_type
            # Make sure the path is fully resolved
            entity["path"] = os.path.expanduser(entity["path"])

            # Check if the File already exists in Synapse by fetching metadata on it
            bundle = self._getEntityBundle(entity)

            if bundle:
                if createOrUpdate:
                    # update our properties from the existing bundle so that we have
                    # enough to process this as an entity update.
                    properties = {**bundle["entity"], **properties}

                # Check if the file should be uploaded
                fileHandle = find_data_file_handle(bundle)
                if (
                    fileHandle
                    and fileHandle["concreteType"]
                    == "org.sagebionetworks.repo.model.file.ExternalFileHandle"
                ):
                    # switching away from ExternalFileHandle or the url was updated
                    needs_upload = entity["synapseStore"] or (
                        fileHandle["externalURL"] != entity["externalURL"]
                    )
                else:
                    synapse_store_flag = entity["synapseStore"] or local_state.get(
                        "synapseStore"
                    )
                    # Check if we need to upload a new version of an existing
                    # file. If the file referred to by entity['path'] has been
                    # modified, we want to upload the new version.
                    # If synapeStore is false then we must upload a ExternalFileHandle
                    needs_upload = not synapse_store_flag or not self.cache.contains(
                        bundle["entity"]["dataFileHandleId"], entity["path"]
                    )

                    md5_stored_in_synapse = local_state.get("_file_handle", {}).get(
                        "contentMd5", None
                    ) or (fileHandle or {}).get("contentMd5", None)

                    # Check if we got an MD5 checksum from Synapse and compare it to the local file
                    if (
                        synapse_store_flag
                        and needs_upload
                        and os.path.isfile(entity["path"])
                        and md5_stored_in_synapse
                        and md5_stored_in_synapse
                        == (
                            local_file_md5_hex := utils.md5_for_file(
                                entity["path"]
                            ).hexdigest()
                        )
                    ):
                        needs_upload = False
            elif entity.get("dataFileHandleId", None) is not None:
                needs_upload = False
            else:
                needs_upload = True

            if needs_upload:
                local_state_fh = local_state.get("_file_handle", {})
                synapseStore = local_state.get("synapseStore", True)

                # parent_id_for_upload is allowing `store` to be called on files that have
                # already been stored to Synapse, but did not specify a parentId in the
                # FileEntity. This is useful as it prevents the need to specify the
                # parentId every time a file is stored to Synapse when the ID is
                # already known.
                parent_id_for_upload = entity.get("parentId", None)
                if not parent_id_for_upload and bundle and bundle.get("entity", None):
                    parent_id_for_upload = bundle["entity"]["parentId"]

                if not parent_id_for_upload:
                    raise SynapseMalformedEntityError(
                        "Entities of type File must have a parentId."
                    )

                fileHandle = await upload_file_handle_async(
                    self,
                    parent_id_for_upload,
                    (
                        local_state["path"]
                        if (synapseStore or local_state_fh.get("externalURL") is None)
                        else local_state_fh.get("externalURL")
                    ),
                    synapse_store=synapseStore,
                    md5=local_file_md5_hex or local_state_fh.get("contentMd5"),
                    file_size=local_state_fh.get("contentSize"),
                    mimetype=local_state_fh.get("contentType"),
                )
                properties["dataFileHandleId"] = fileHandle["id"]
                local_state["_file_handle"] = fileHandle

            elif "dataFileHandleId" not in properties:
                # Handle the case where the Entity lacks an ID
                # But becomes an update() due to conflict
                properties["dataFileHandleId"] = bundle["entity"]["dataFileHandleId"]

            # update the file_handle metadata if the FileEntity's FileHandle id has changed
            local_state_fh_id = local_state.get("_file_handle", {}).get("id")
            if (
                local_state_fh_id
                and properties["dataFileHandleId"] != local_state_fh_id
            ):
                local_state["_file_handle"] = find_data_file_handle(
                    self._getEntityBundle(
                        properties["id"],
                        requestedObjects={
                            "includeEntity": True,
                            "includeFileHandles": True,
                        },
                    )
                )

                # check if we already have the filehandleid cached somewhere
                cached_path = self.cache.get(properties["dataFileHandleId"])
                if cached_path is None:
                    local_state["path"] = None
                    local_state["cacheDir"] = None
                    local_state["files"] = []
                else:
                    local_state["path"] = cached_path
                    local_state["cacheDir"] = os.path.dirname(cached_path)
                    local_state["files"] = [os.path.basename(cached_path)]

        # Create or update Entity in Synapse
        if "id" in properties:
            trace.get_current_span().set_attributes({"synapse.id": properties["id"]})
            properties = self._updateEntity(properties, forceVersion, versionLabel)
        else:
            # If Link, get the target name, version number and concrete type and store in link properties
            if properties["concreteType"] == "org.sagebionetworks.repo.model.Link":
                target_properties = self._getEntity(
                    properties["linksTo"]["targetId"],
                    version=properties["linksTo"].get("targetVersionNumber"),
                )
                if target_properties["parentId"] == properties["parentId"]:
                    raise ValueError(
                        "Cannot create a Link to an entity under the same parent."
                    )
                properties["linksToClassName"] = target_properties["concreteType"]
                if (
                    target_properties.get("versionNumber") is not None
                    and properties["linksTo"].get("targetVersionNumber") is not None
                ):
                    properties["linksTo"]["targetVersionNumber"] = target_properties[
                        "versionNumber"
                    ]
                properties["name"] = target_properties["name"]
            try:
                properties = self._createEntity(properties)
            except SynapseHTTPError as ex:
                if createOrUpdate and ex.response.status_code == 409:
                    # Get the existing Entity's ID via the name and parent
                    existing_entity_id = self.findEntityId(
                        properties["name"], properties.get("parentId", None)
                    )
                    if existing_entity_id is None:
                        raise

                    # get existing properties and annotations
                    if not bundle:
                        bundle = self._getEntityBundle(
                            existing_entity_id,
                            requestedObjects={
                                "includeEntity": True,
                                "includeAnnotations": True,
                            },
                        )

                    properties = {**bundle["entity"], **properties}

                    # we additionally merge the annotations under the assumption that a missing annotation
                    # from a resolved conflict represents an newer annotation that should be preserved
                    # rather than an intentionally deleted annotation.
                    annotations = {
                        **from_synapse_annotations(bundle["annotations"]),
                        **annotations,
                    }

                    properties = self._updateEntity(
                        properties, forceVersion, versionLabel
                    )

                else:
                    raise

        # Deal with access restrictions
        if isRestricted:
            self._createAccessRequirementIfNone(properties)

        # Update annotations
        if set_annotations and (
            (not bundle and annotations)
            or (
                bundle and check_annotations_changed(bundle["annotations"], annotations)
            )
        ):
            annotations = self.set_annotations(
                Annotations(properties["id"], properties["etag"], annotations)
            )
            properties["etag"] = annotations.etag

        # If the parameters 'used' or 'executed' are given, create an Activity object
        if used or executed:
            if activity is not None:
                raise SynapseProvenanceError(
                    "Provenance can be specified as an Activity object or as used/executed"
                    " item(s), but not both."
                )
            activity = Activity(
                name=activityName,
                description=activityDescription,
                used=used,
                executed=executed,
            )

        # If we have an Activity, set it as the Entity's provenance record
        if activity:
            self.setProvenance(properties, activity)

            # 'etag' has changed, so get the new Entity
            properties = self._getEntity(properties)

        # Return the updated Entity object
        entity = Entity.create(properties, annotations, local_state)
        return_data = await self.get_async(entity, downloadFile=False)

        trace.get_current_span().set_attributes(
            {
                "synapse.id": return_data.get("id", ""),
                "synapse.concrete_type": entity.get("concreteType", ""),
            }
        )
        return return_data

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _createAccessRequirementIfNone(self, entity: Union[Entity, str]) -> None:
        """
        Checks to see if the given entity has access requirements. If not, then one is added

        Arguments:
            entity: A Synapse ID or a Synapse Entity object
        """
        existingRestrictions = self.restGET(
            "/entity/%s/accessRequirement?offset=0&limit=1" % id_of(entity)
        )
        if len(existingRestrictions["results"]) <= 0:
            self.restPOST("/entity/%s/lockAccessRequirement" % id_of(entity), body="")

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getEntityBundle(
        self,
        entity: Union[Entity, str],
        version: int = None,
        requestedObjects: Dict[str, bool] = None,
    ) -> Dict[str, Union[dict, str, int, bool]]:
        """
        Gets some information about the Entity.

        Arguments:
            entity:           A Synapse Entity or Synapse ID
            version:          The entity's version. Defaults to None meaning most recent version.
            requestedObjects: A dictionary indicating settings for what to include.

        Default value for requestedObjects is:

            requestedObjects = {'includeEntity': True,
                                'includeAnnotations': True,
                                'includeFileHandles': True,
                                'includeRestrictionInformation': True}

        Keys available for requestedObjects:

            includeEntity
            includeAnnotations
            includePermissions
            includeEntityPath
            includeHasChildren
            includeAccessControlList
            includeFileHandles
            includeTableBundle
            includeRootWikiId
            includeBenefactorACL
            includeDOIAssociation
            includeFileName
            includeThreadCount
            includeRestrictionInformation


        Keys with values set to False may simply be omitted.
        For example, we might ask for an entity bundle containing file handles, annotations, and properties:
            requested_objects = {'includeEntity':True
                                 'includeAnnotations':True,
                                 'includeFileHandles':True}
            bundle = syn._getEntityBundle('syn111111', )

        Returns:
            An EntityBundle with the requested fields or by default Entity header, annotations, unmet access
            requirements, and file handles
        """
        # If 'entity' is given without an ID, try to find it by 'parentId' and 'name'.
        # Use case:
        #     If the user forgets to catch the return value of a syn.store(e)
        #     this allows them to recover by doing: e = syn.get(e)
        if requestedObjects is None:
            requestedObjects = {
                "includeEntity": True,
                "includeAnnotations": True,
                "includeFileHandles": True,
                "includeRestrictionInformation": True,
            }
        if (
            isinstance(entity, collections.abc.Mapping)
            and "id" not in entity
            and "name" in entity
        ):
            entity = self.findEntityId(entity["name"], entity.get("parentId", None))

        # Avoid an exception from finding an ID from a NoneType
        try:
            id_of(entity)
        except ValueError:
            return None

        if version is not None:
            uri = f"/entity/{id_of(entity)}/version/{int(version):d}/bundle2"
        else:
            uri = f"/entity/{id_of(entity)}/bundle2"
        bundle = self.restPOST(uri, body=json.dumps(requestedObjects))

        return bundle

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import delete` instead.",
    )
    def delete(
        self,
        obj,
        version=None,
    ):
        """
        Removes an object from Synapse.

        Arguments:
            obj: An existing object stored on Synapse such as Evaluation, File, Project, or Wiki
            version: For entities, specify a particular version to delete.
        """
        # Handle all strings as the Entity ID for backward compatibility
        if isinstance(obj, str):
            entity_id = id_of(obj)
            trace.get_current_span().set_attributes({"synapse.id": entity_id})
            if version:
                self.restDELETE(uri=f"/entity/{entity_id}/version/{version}")
            else:
                self.restDELETE(uri=f"/entity/{entity_id}")
        elif hasattr(obj, "_synapse_delete"):
            return obj._synapse_delete(self)
        else:
            try:
                if isinstance(obj, Versionable):
                    self.restDELETE(obj.deleteURI(versionNumber=version))
                else:
                    self.restDELETE(obj.deleteURI())
            except AttributeError:
                raise SynapseError(
                    f"Can't delete a {type(obj)}. Please specify a Synapse object or id"
                )

    _user_name_cache = {}

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _get_user_name(self, user_id: str) -> str:
        """
        Get username with ownerId

        Arguments:
            user_id: The ownerId of a user

        Returns:
            A username
        """
        if user_id not in self._user_name_cache:
            self._user_name_cache[user_id] = utils.extract_user_name(
                self.getUserProfile(user_id)
            )
        return self._user_name_cache[user_id]

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _list(
        self,
        parent: str,
        recursive: bool = False,
        long_format: bool = False,
        show_modified: bool = False,
        indent: float = 0,
        out=sys.stdout,
    ) -> None:
        """
        List child objects of the given parent, recursively if requested.

        Arguments:
            parent:        A Synapse ID for folder or project that you want to list child objects for
            recursive:     Whether to show subfolder
            long_format:   Whether to show createdOn, createdBy and version
            show_modified: Whether to show modifiedOn and modifiedBy
            indent:        The left padding of the file tree structure
            out:           The location to write the output.
        """
        fields = ["id", "name", "nodeType"]
        if long_format:
            fields.extend(["createdByPrincipalId", "createdOn", "versionNumber"])
        if show_modified:
            fields.extend(["modifiedByPrincipalId", "modifiedOn"])
        results = self.getChildren(parent)

        results_found = False
        for result in results:
            results_found = True

            fmt_fields = {
                "name": result["name"],
                "id": result["id"],
                "padding": " " * indent,
                "slash_or_not": "/" if is_container(result) else "",
            }
            fmt_string = "{id}"

            if long_format:
                fmt_fields["createdOn"] = utils.iso_to_datetime(
                    result["createdOn"]
                ).strftime("%Y-%m-%d %H:%M")
                fmt_fields["createdBy"] = self._get_user_name(result["createdBy"])[:18]
                fmt_fields["version"] = result["versionNumber"]
                fmt_string += " {version:3}  {createdBy:>18} {createdOn}"
            if show_modified:
                fmt_fields["modifiedOn"] = utils.iso_to_datetime(
                    result["modifiedOn"]
                ).strftime("%Y-%m-%d %H:%M")
                fmt_fields["modifiedBy"] = self._get_user_name(result["modifiedBy"])[
                    :18
                ]
                fmt_string += "  {modifiedBy:>18} {modifiedOn}"

            fmt_string += "  {padding}{name}{slash_or_not}\n"
            out.write(fmt_string.format(**fmt_fields))

            if (indent == 0 or recursive) and is_container(result):
                self._list(
                    result["id"],
                    recursive=recursive,
                    long_format=long_format,
                    show_modified=show_modified,
                    indent=indent + 2,
                    out=out,
                )

        if indent == 0 and not results_found:
            out.write(
                "No results visible to {username} found for id {id}\n".format(
                    username=self.credentials.username, id=id_of(parent)
                )
            )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/upload/upload_functions.py::upload_file_handle_async. "
        "Use `upload_file_handle_async` directly instead.",
    )
    def uploadFileHandle(
        self, path, parent, synapseStore=True, mimetype=None, md5=None, file_size=None
    ):
        """Uploads the file in the provided path (if necessary) to a storage location based on project settings.
        Returns a new FileHandle as a dict to represent the stored file.

        Arguments:
            parent: Parent of the entity to which we upload.
            path:   File path to the file being uploaded
            synapseStore: If False, will not upload the file, but instead create an ExternalFileHandle that references
                            the file on the local machine.
                            If True, will upload the file based on StorageLocation determined by the entity_parent_id
            mimetype: The MIME type metadata for the uploaded file
            md5: The MD5 checksum for the file, if known. Otherwise if the file is a local file, it will be calculated
                    automatically.
            file_size: The size the file, if known. Otherwise if the file is a local file, it will be calculated
                        automatically.
            file_type: The MIME type the file, if known. Otherwise if the file is a local file, it will be calculated
                        automatically.

        Returns:
            A dict of a new FileHandle as a dict that represents the uploaded file

        Example: Migrating from this method to upload_file_handle_async
            **Legacy approach (deprecated):**
            ```python
            # Using the deprecated uploadFileHandle method
            file_handle = syn.uploadFileHandle(
                path="/path/to/file.txt",
                parent="syn12345",
                synapseStore=True,
                mimetype="text/plain"
            )
            ```

            **New approach using upload_file_handle:**
            ```python
            import asyncio
            import synapseclient
            from synapseclient.core.upload.upload_functions_async import upload_file_handle

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # Using the new async function directly
            async def upload_file():
                file_handle = await upload_file_handle(
                    syn=syn,
                    parent_entity_id="syn12345",
                    path="/path/to/file.txt",
                    synapse_store=True,
                    md5=None,
                    file_size=None,
                    mimetype="text/plain"
                )
                return file_handle

            # Run the async function
            file_handle = asyncio.run(upload_file())
            print(f"File handle uploaded: {file_handle}")
            ```
        """
        return wrap_async_to_sync(
            upload_file_handle_async(
                self, parent, path, synapseStore, md5, file_size, mimetype
            )
        )

    ############################################################
    #                  Download List                           #
    ############################################################
    @deprecated(
        version="4.13.0",
        reason=(
            "Use `synapseclient.operations.download_list_clear()` instead. "
            "See synapseclient.operations.download_list_operations for the new interface."
        ),
    )
    def clear_download_list(self):
        """Clear all files from download list

        Example: Migration to new method
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # syn.clear_download_list()

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.operations import download_list_clear

            syn = Synapse()
            syn.login()

            # Clear all files from the download list
            download_list_clear()
            ```
        """
        self.restDELETE("/download/list")

    @deprecated(
        version="4.13.0",
        reason=(
            "Use `synapseclient.operations.download_list_remove(files)` instead. "
            "See synapseclient.operations.download_list_operations for the new interface."
        ),
    )
    def remove_from_download_list(self, list_of_files: typing.List[typing.Dict]) -> int:
        """Remove a batch of files from download list

        Example: Migration to new method
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # syn.remove_from_download_list([
            #     {"fileEntityId": "syn123", "versionNumber": 1},
            # ])

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.operations import download_list_remove, DownloadListItem

            syn = Synapse()
            syn.login()

            # Remove specific file versions from the download list
            download_list_remove([
                DownloadListItem(file_entity_id="syn123", version_number=1),
            ])
            ```

        Arguments:
            list_of_files: Array of files in the format of a mapping {fileEntityId: synid, versionNumber: version}

        Returns:
            Number of files removed from download list
        """
        request_body = {"batchToRemove": list_of_files}
        num_files_removed = self.restPOST(
            "/download/list/remove", body=json.dumps(request_body)
        )
        return num_files_removed

    @deprecated(
        version="4.13.0",
        reason=(
            "Use `synapseclient.operations.download_list_manifest()` instead. "
            "See synapseclient.operations.download_list_operations for the new interface."
        ),
    )
    def _generate_manifest_from_download_list(
        self,
        quoteCharacter: str = '"',
        escapeCharacter: str = "\\",
        lineEnd: str = os.linesep,
        separator: str = ",",
        header: bool = True,
    ):
        """Creates a download list manifest generation request

        Example: Migration to new method
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # manifest_handle = syn._generate_manifest_from_download_list()

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.operations import download_list_manifest

            syn = Synapse()
            syn.login()

            # Generate and download the manifest CSV
            manifest_path = download_list_manifest()
            ```

        Arguments:
            quoteCharacter:  The character to be used for quoted elements in the resulting file.
            escapeCharacter: The escape character to be used for escaping a separator or quote in the resulting file.
            lineEnd:         The line feed terminator to be used for the resulting file.
            separator:       The delimiter to be used for separating entries in the resulting file.
            header:          Is the first line a header?

        Returns:
            Filehandle of download list manifest
        """
        request_body = {
            "concreteType": "org.sagebionetworks.repo.model.download.DownloadListManifestRequest",
            "csvTableDescriptor": {
                "separator": separator,
                "quoteCharacter": quoteCharacter,
                "escapeCharacter": escapeCharacter,
                "lineEnd": lineEnd,
                "isFirstLineHeader": header,
            },
        }
        return self._waitForAsync(
            uri="/download/list/manifest/async", request=request_body
        )

    @deprecated(
        version="4.13.0",
        reason=(
            "Use `synapseclient.operations.download_list_manifest()` instead. "
            "See synapseclient.operations.download_list_operations for the new interface."
        ),
    )
    def get_download_list_manifest(self):
        """Get the path of the download list manifest file

        Example: Migration to new method
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # manifest_path = syn.get_download_list_manifest()

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.operations import download_list_manifest

            syn = Synapse()
            syn.login()

            # Generate and download the manifest CSV
            manifest_path = download_list_manifest()
            ```

        Returns:
            Path of download list manifest file
        """
        manifest = self._generate_manifest_from_download_list()
        # Get file handle download link
        file_result = get_file_handle_for_download(
            file_handle_id=manifest["resultFileHandleId"],
            synapse_id=manifest["resultFileHandleId"],
            entity_type="FileEntity",
            synapse_client=self,
        )
        # Download the manifest
        downloaded_path = self._download_from_URL(
            url=file_result["preSignedURL"],
            destination="./",
            fileHandleId=file_result["fileHandleId"],
            expected_md5=file_result["fileHandle"].get("contentMd5"),
        )
        trace.get_current_span().set_attributes(
            {"synapse.file_handle_id": file_result["fileHandleId"]}
        )
        return downloaded_path

    @deprecated(
        version="4.13.0",
        reason=(
            "Use `synapseclient.operations.download_list_files(download_location=...)` instead. "
            "See synapseclient.operations.download_list_operations for the new interface."
        ),
    )
    def get_download_list(self, downloadLocation: str = None) -> str:
        """Download all files from your Synapse download list

        Example: Migration to new method
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # manifest_path = syn.get_download_list(downloadLocation="./downloads")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.operations import download_list_files

            syn = Synapse()
            syn.login()

            # Download all files in the cart and get the result manifest path
            manifest_path = download_list_files(download_location="./downloads")
            ```

        Arguments:
            downloadLocation: Directory to download files to.

        Returns:
            Manifest file with file paths
        """
        dl_list_path = self.get_download_list_manifest()
        downloaded_files = []
        new_manifest_path = f"manifest_{time.time_ns()}.csv"
        with (
            open(dl_list_path) as manifest_f,
            open(new_manifest_path, "w") as write_obj,
        ):
            reader = csv.DictReader(manifest_f)
            columns = reader.fieldnames
            columns.extend(["path", "error"])
            # Write the downloaded paths to a new manifest file
            writer = csv.DictWriter(write_obj, fieldnames=columns)
            writer.writeheader()

            for row in reader:
                # You can add things to the download list that you don't have access to
                # So there must be a try catch here
                try:
                    entity = self.get(row["ID"], downloadLocation=downloadLocation)
                    # Must include version number because you can have multiple versions of a
                    # file in the download list
                    downloaded_files.append(
                        {
                            "fileEntityId": row["ID"],
                            "versionNumber": row["versionNumber"],
                        }
                    )
                    row["path"] = entity.path
                    row["error"] = ""
                except Exception:
                    row["path"] = ""
                    row["error"] = "DOWNLOAD FAILED"
                    self.logger.exception("Unable to download file")
                writer.writerow(row)

        # Don't want to clear all the download list because you can add things
        # to the download list after initiating this command.
        # Files that failed to download should not be removed from download list
        # Remove all files from download list after the entire download is complete.
        # This is because if download fails midway, we want to return the full manifest
        if downloaded_files:
            # Only want to invoke this if there is a list of files to remove
            # or the API call will error
            self.remove_from_download_list(list_of_files=downloaded_files)
        else:
            self.logger.warning("A manifest was created, but no files were downloaded")

        # Always remove original manifest file
        os.remove(dl_list_path)

        return new_manifest_path

    ############################################################
    #                  Get / Set Annotations                   #
    ############################################################

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getRawAnnotations(
        self, entity: Union[Entity, str], version: int = None
    ) -> Dict[str, Union[str, dict]]:
        """
        Retrieve annotations for an Entity returning them in the native Synapse format.

        Arguments:
            entity:  A Synapse Entity or Synapse ID
            version: The entity's version. Defaults to None meaning most recent version.

        Returns:
            An annotation dictionary
        """
        # Note: Specifying the version results in a zero-ed out etag,
        # even if the version is the most recent.
        # See [PLFM-1874](https://sagebionetworks.jira.com/browse/PLFM-1874) for more details.
        if version:
            uri = f"/entity/{id_of(entity)}/version/{str(version)}/annotations2"
        else:
            uri = f"/entity/{id_of(entity)}/annotations2"
        return self.restGET(uri)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. Use the dataclass model attributes instead. "
        "All dataclass models support annotations: File, Folder, Project, Table, EntityView, Dataset, "
        "DatasetCollection, MaterializedView, SubmissionView, VirtualTable. "
        "Access annotations directly via `instance.annotations` attribute.",
    )
    def get_annotations(
        self, entity: typing.Union[str, Entity], version: typing.Union[str, int] = None
    ) -> Annotations:
        """
        Retrieve annotations for an Entity from the Synapse Repository as a Python dict.

        Note that collapsing annotations from the native Synapse format to a Python dict may involve some loss of
        information. See `_getRawAnnotations` to get annotations in the native format.

        Arguments:
            entity: An Entity or Synapse ID to lookup
            version: The version of the Entity to retrieve.

        Returns:
            A [synapseclient.annotations.Annotations][] object, a dict that also has id and etag attributes

        Example: Migrating from this method to dataclass models
            **Legacy approach (deprecated):**
            ```python
            # Get the File entity first
            file_entity = syn.get("syn123")

            # Get annotations separately
            annotations = syn.get_annotations(file_entity)
            print(annotations)
            ```

            **New approach using dataclass models:**
            ```python
            import synapseclient
            from synapseclient.models import (
                File, Folder, Project, Table, EntityView, Dataset,
                DatasetCollection, MaterializedView, SubmissionView, VirtualTable
            )

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # File - don't download the file content, just get metadata
            file_instance = File(id="syn12345", download_file=False)
            file_instance = file_instance.get()
            print(f"File annotations: {file_instance.annotations}")

            # Folder
            folder_instance = Folder(id="syn11111")
            folder_instance = folder_instance.get()
            print(f"Folder annotations: {folder_instance.annotations}")

            # Project
            project_instance = Project(id="syn22222")
            project_instance = project_instance.get()
            print(f"Project annotations: {project_instance.annotations}")

            # Table
            table_instance = Table(id="syn33333")
            table_instance = table_instance.get()
            print(f"Table annotations: {table_instance.annotations}")

            # EntityView
            view_instance = EntityView(id="syn44444")
            view_instance = view_instance.get()
            print(f"EntityView annotations: {view_instance.annotations}")

            # Dataset
            dataset_instance = Dataset(id="syn55555")
            dataset_instance = dataset_instance.get()
            print(f"Dataset annotations: {dataset_instance.annotations}")

            # DatasetCollection
            collection_instance = DatasetCollection(id="syn66666")
            collection_instance = collection_instance.get()
            print(f"DatasetCollection annotations: {collection_instance.annotations}")

            # MaterializedView
            mat_view_instance = MaterializedView(id="syn77777")
            mat_view_instance = mat_view_instance.get()
            print(f"MaterializedView annotations: {mat_view_instance.annotations}")

            # SubmissionView
            sub_view_instance = SubmissionView(id="syn88888")
            sub_view_instance = sub_view_instance.get()
            print(f"SubmissionView annotations: {sub_view_instance.annotations}")

            # VirtualTable
            virtual_table_instance = VirtualTable(id="syn99999")
            virtual_table_instance = virtual_table_instance.get()
            print(f"VirtualTable annotations: {virtual_table_instance.annotations}")

            # Access specific annotation values
            # annotations is always a dict by default (empty {} if no annotations exist)
            species = file_instance.annotations.get("species", [])
            data_type = file_instance.annotations.get("dataType", [])
            print(f"Species: {species}, Data type: {data_type}")

            # Check if a specific annotation exists
            if species:
                print(f"Species annotation exists: {species}")
            else:
                print("Species annotation not found")

            # Get all annotation keys
            annotation_keys = list(file_instance.annotations.keys())
            print(f"Available annotation keys: {annotation_keys}")
            ```
        """
        return from_synapse_annotations(self._getRawAnnotations(entity, version))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. Use the dataclass model attributes instead. "
        "All dataclass models support annotations: File, Folder, Project, Table, EntityView, Dataset, "
        "DatasetCollection, MaterializedView, SubmissionView, VirtualTable. "
        "Set annotations via `instance.annotations = {...}` then call `instance.store()`.",
    )
    def set_annotations(self, annotations: Annotations):
        """
        Store annotations for an Entity in the Synapse Repository.

        Arguments:
            annotations: A [synapseclient.annotations.Annotations][] of annotation names and values,
                            with the id and etag attribute set

        Returns:
            The updated [synapseclient.annotations.Annotations][] for the entity

        Example: Migrating from this method to dataclass models
            **Legacy approach (deprecated):**
            ```python
            # Get annotations, modify, and set back
            annos = syn.get_annotations('syn12345')
            annos['foo'] = ['bar', 'baz']
            annos['qwerty'] = 'asdf'
            annos = syn.set_annotations(annos)
            print(annos)
            ```

            **New approach using dataclass models:**

            In this example all of these updates are destructive, meaning they will
            overwrite any existing annotations. If you want to merge annotations
            instead, see the merging example below.
            ```python
            import synapseclient
            from synapseclient.models import (
                File, Folder, Project, Table, EntityView, Dataset,
                DatasetCollection, MaterializedView, SubmissionView, VirtualTable
            )

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # File - don't download the file content, just get metadata
            file_instance = File(id="syn12345", download_file=False)
            file_instance = file_instance.get()
            file_instance.annotations = {
                "foo": ["bar", "baz"],
                "qwerty": ["asdf"],
                "species": ["Homo sapiens"]
            }
            file_instance = file_instance.store()
            print(f"File annotations: {file_instance.annotations}")

            # Folder
            folder_instance = Folder(id="syn11111")
            folder_instance = folder_instance.get()
            folder_instance.annotations = {
                "category": ["research"],
                "department": ["biology"]
            }
            folder_instance = folder_instance.store()
            print(f"Folder annotations: {folder_instance.annotations}")

            # Project
            project_instance = Project(id="syn22222")
            project_instance = project_instance.get()
            project_instance.annotations = {
                "funding": ["NIH"],
                "grant_number": ["R01-12345"]
            }
            project_instance = project_instance.store()
            print(f"Project annotations: {project_instance.annotations}")

            # Table
            table_instance = Table(id="syn33333")
            table_instance = table_instance.get()
            table_instance.annotations = {
                "version": ["1.0"],
                "data_type": ["clinical"]
            }
            table_instance = table_instance.store()
            print(f"Table annotations: {table_instance.annotations}")

            # EntityView
            view_instance = EntityView(id="syn44444")
            view_instance = view_instance.get()
            view_instance.annotations = {
                "scope": ["project_wide"],
                "view_type": ["file_view"]
            }
            view_instance = view_instance.store()
            print(f"EntityView annotations: {view_instance.annotations}")

            # Dataset
            dataset_instance = Dataset(id="syn55555")
            dataset_instance = dataset_instance.get()
            dataset_instance.annotations = {
                "dataset_type": ["genomic"],
                "size": ["large"]
            }
            dataset_instance = dataset_instance.store()
            print(f"Dataset annotations: {dataset_instance.annotations}")

            # DatasetCollection
            collection_instance = DatasetCollection(id="syn66666")
            collection_instance = collection_instance.get()
            collection_instance.annotations = {
                "collection_type": ["multi_omics"],
                "studies": ["3"]
            }
            collection_instance = collection_instance.store()
            print(f"DatasetCollection annotations: {collection_instance.annotations}")

            # MaterializedView
            mat_view_instance = MaterializedView(id="syn77777")
            mat_view_instance = mat_view_instance.get()
            mat_view_instance.annotations = {
                "refresh_frequency": ["daily"],
                "data_source": ["clinical_db"]
            }
            mat_view_instance = mat_view_instance.store()
            print(f"MaterializedView annotations: {mat_view_instance.annotations}")

            # SubmissionView
            sub_view_instance = SubmissionView(id="syn88888")
            sub_view_instance = sub_view_instance.get()
            sub_view_instance.annotations = {
                "evaluation_queue": ["challenge_2024"],
                "status": ["active"]
            }
            sub_view_instance = sub_view_instance.store()
            print(f"SubmissionView annotations: {sub_view_instance.annotations}")

            # VirtualTable
            virtual_table_instance = VirtualTable(id="syn99999")
            virtual_table_instance = virtual_table_instance.get()
            virtual_table_instance.annotations = {
                "virtual_type": ["federated"],
                "source_count": ["5"]
            }
            virtual_table_instance = virtual_table_instance.store()
            print(f"VirtualTable annotations: {virtual_table_instance.annotations}")
            ```

            **For merging with existing annotations:**
            ```python
            import synapseclient
            from synapseclient.models import File, Folder

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # Get existing annotations and merge for File
            file_instance = File(id="syn12345", download_file=False)
            file_instance = file_instance.get()

            # Merge with existing annotations (annotations is always a dict by default)
            file_instance.annotations.update({
                "foo": ["bar", "baz"],
                "qwerty": ["asdf"]
            })

            # Store the updated File
            file_instance = file_instance.store()
            print(f"Updated file annotations: {file_instance.annotations}")

            # Same pattern works for all other dataclass models
            folder_instance = Folder(id="syn11111")
            folder_instance = folder_instance.get()
            folder_instance.annotations.update({"new_key": ["new_value"]})
            folder_instance = folder_instance.store()
            print(f"Updated folder annotations: {folder_instance.annotations}")
            ```

            **For updating single annotation values:**
            ```python
            import synapseclient
            from synapseclient.models import File

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # Update a single annotation value while preserving existing annotations
            file_instance = File(id="syn12345", download_file=False)
            file_instance = file_instance.get()

            # annotations is always a dict by default (empty {} if no annotations exist)
            # You can directly access and modify annotation values
            file_instance.annotations["species"] = ["Mus musculus"]
            file_instance.annotations["data_type"] = ["RNA-seq"]

            # Store the updated File
            file_instance = file_instance.store()
            print(f"Updated file annotations: {file_instance.annotations}")
            ```

            **IMPORTANT - Destructive vs Non-destructive updates:**
            ```python
            import synapseclient
            from synapseclient.models import File

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # When you call .get(), existing annotations are loaded into the instance
            file_instance = File(id="syn12345", download_file=False)
            file_instance = file_instance.get()
            # Now file_instance.annotations contains existing annotations from Synapse

            # DESTRUCTIVE UPDATE - This replaces ALL existing annotations
            file_instance.annotations = {
                "new_key": ["new_value"]
            }
            # All previous annotations are lost!

            # NON-DESTRUCTIVE UPDATE - This preserves existing annotations
            # annotations is always a dict by default (empty {} if no annotations exist)
            file_instance.annotations.update({
                "new_key": ["new_value"]
            })
            # OR modify individual keys:
            file_instance.annotations["another_key"] = ["another_value"]
            # Previous annotations are preserved

            # To remove ALL annotations, set to None or empty dict
            file_instance.annotations = None  # Clears all annotations
            # OR
            file_instance.annotations = {}    # Also clears all annotations

            file_instance = file_instance.store()
            ```

        Example: Using this function (DEPRECATED)
            Getting annotations, adding a new annotation, and updating the annotations:

                annos = syn.get_annotations('syn123')

            `annos` will contain the id and etag associated with the entity upon retrieval

                print(annos.id)
                > syn123
                print(annos.etag)
                > 7bdb83e9-a50a-46e4-987a-4962559f090f   (Usually some UUID in the form of a string)

            Returned `annos` object from `get_annotations()` can be used as if it were a dict.
            Set key 'foo' to have value of 'bar' and 'baz'

                annos['foo'] = ['bar', 'baz']

            Single values will automatically be wrapped in a list once stored

                annos['qwerty'] = 'asdf'

            Store the annotations

                annos = syn.set_annotations(annos)

                print(annos)
                > {'foo':['bar','baz], 'qwerty':['asdf']}
        """

        if not isinstance(annotations, Annotations):
            raise TypeError("Expected a synapseclient.Annotations object")

        synapseAnnos = to_synapse_annotations(annotations)

        entity_id = id_of(annotations)
        trace.get_current_span().set_attributes({"synapse.id": entity_id})

        return from_synapse_annotations(
            self.restPUT(
                f"/entity/{entity_id}/annotations2",
                body=json.dumps(synapseAnnos),
            )
        )

    ############################################################
    #                         Querying                         #
    ############################################################

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the new dataclass models `from synapseclient.models import Project, Folder` "
        "with their `sync_from_synapse` method for most use cases, "
        "or the `synapseclient.api.get_children` function for direct API access with sorting and filtering.",
    )
    def getChildren(
        self,
        parent,
        includeTypes=[
            "folder",
            "file",
            "table",
            "link",
            "entityview",
            "dockerrepo",
            "submissionview",
            "dataset",
            "materializedview",
        ],
        sortBy="NAME",
        sortDirection="ASC",
    ):
        """
        Retrieves all of the entities stored within a parent such as folder or project.

        Arguments:
            parent: An id or an object of a Synapse container or None to retrieve all projects
            includeTypes: Must be a list of entity types (ie. ["folder","file"]) which can be found [here](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/EntityType.html)
            sortBy: How results should be sorted. Can be NAME, or CREATED_ON
            sortDirection: The direction of the result sort. Can be ASC, or DESC

        Yields:
            An iterator that shows all the children of the container.

        Also see:

        - [synapseutils.walk][]

        Example: Migrating from this method to new approaches
            &nbsp;

            **Legacy approach (deprecated):**
            ```python
            # Using the deprecated getChildren method
            for child in syn.getChildren("syn12345", includeTypes=["file", "folder"]):
                print(f"Child: {child['name']} (ID: {child['id']})")
            ```

            **New approach using dataclass models with sync_from_synapse:**
            ```python
            import synapseclient
            from synapseclient.models import Project, Folder

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # For projects - get all children automatically (recursive by default)
            project = Project(id="syn12345")
            project = project.sync_from_synapse(download_file=False)

            # Access different types of children
            print(f"Files: {len(project.files)}")
            for file in project.files:
                print(f"  File: {file.name} (ID: {file.id})")

            print(f"Folders: {len(project.folders)}")
            for folder in project.folders:
                print(f"  Folder: {folder.name} (ID: {folder.id})")

            print(f"Tables: {len(project.tables)}")
            for table in project.tables:
                print(f"  Table: {table.name} (ID: {table.id})")

            # For folders - get all children automatically (recursive by default)
            folder = Folder(id="syn67890")
            folder = folder.sync_from_synapse(download_file=False)

            # Access children in the same way
            for file in folder.files:
                print(f"  File: {file.name} (ID: {file.id})")

            # For non-recursive behavior (equivalent to single getChildren call)
            folder = Folder(id="syn67890")
            folder = folder.sync_from_synapse(download_file=False, recursive=False)

            # This will only get immediate children, not subfolders' contents
            for file in folder.files:
                print(f"  File: {file.name} (ID: {file.id})")
            for subfolder in folder.folders:
                print(f"  Subfolder: {subfolder.name} (ID: {subfolder.id})")
                # Note: subfolder.files and subfolder.folders will be empty
                # because recursive=False
            ```

            **New approach using the API directly (for advanced sorting/filtering):**
            ```python
            import asyncio
            import synapseclient
            from synapseclient.api import get_children

            # Create client and login
            syn = synapseclient.Synapse()
            syn.login()

            # Using the new async API function directly
            async def get_sorted_children():
                async for child in get_children(
                    parent="syn12345",
                    include_types=["file", "folder"],
                    sort_by="NAME",
                    sort_direction="ASC"
                ):
                    print(f"Child: {child['name']} (ID: {child['id']}, Type: {child['type']})")

            # Run the async function
            asyncio.run(get_sorted_children())
            ```
        """
        parentId = id_of(parent) if parent is not None else None

        trace.get_current_span().set_attributes({"synapse.parent_id": parentId})
        entityChildrenRequest = {
            "parentId": parentId,
            "includeTypes": includeTypes,
            "sortBy": sortBy,
            "sortDirection": sortDirection,
            "nextPageToken": None,
        }
        entityChildrenResponse = {"nextPageToken": "first"}
        while entityChildrenResponse.get("nextPageToken") is not None:
            entityChildrenResponse = self.restPOST(
                "/entity/children", body=json.dumps(entityChildrenRequest)
            )
            for child in entityChildrenResponse["page"]:
                yield child
            if entityChildrenResponse.get("nextPageToken") is not None:
                entityChildrenRequest["nextPageToken"] = entityChildrenResponse[
                    "nextPageToken"
                ]

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import md5_query` instead.",
    )
    def md5Query(self, md5):
        """
        Find the Entities which have attached file(s) which have the given MD5 hash.

        Arguments:
            md5: The MD5 to query for (hexadecimal string)

        Returns:
            A list of Entity headers
        """

        return self.restGET("/entity/md5/%s" % md5)["results"]

    ############################################################
    #                     ACL manipulation                     #
    ############################################################

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getBenefactor(
        self, entity: Union[Entity, str]
    ) -> Dict[str, Union[str, int, bool]]:
        """
        Get an Entity's benefactor.
        An Entity gets its ACL from its benefactor.

        Arguments:
            entity: A Synapse Entity or Synapse ID

        Returns:
            A dictionary of the Entity's benefactor

        """
        if utils.is_synapse_id_str(entity) or is_synapse_entity(entity):
            synid, _ = utils.get_synid_and_version(entity)
            return self.restGET("/entity/%s/benefactor" % synid)

        return entity

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getACL(
        self, entity: Union[Entity, str], check_benefactor: bool = True
    ) -> Dict[str, Union[str, list]]:
        """
        Get the effective Access Control Lists (ACL) for a Synapse Entity.

        Arguments:
            entity: A Synapse Entity or Synapse ID
            check_benefactor: If True (default), check the benefactor for the entity
                to get the ACL. If False, only check the entity itself.
                This is useful for checking the ACL of an entity that has local sharing
                settings, but you want to check the ACL of the entity itself and not
                the benefactor it may inherit from.

        Returns:
            A dictionary of the Entity's ACL
        """
        if hasattr(entity, "getACLURI"):
            uri = entity.getACLURI()
            return self.restGET(uri)
        else:
            if check_benefactor:
                # Get the ACL from the benefactor (which may be the entity itself)
                benefactor = self._getBenefactor(entity)
                trace.get_current_span().set_attributes(
                    {"synapse.id": benefactor["id"]}
                )
                uri = "/entity/%s/acl" % (benefactor["id"])
                return self.restGET(uri)
            else:
                synid, _ = utils.get_synid_and_version(entity)
                trace.get_current_span().set_attributes({"synapse.id": synid})
                uri = "/entity/%s/acl" % (synid)
                try:
                    return self.restGET(uri)
                except SynapseHTTPError as e:
                    if (
                        "The requested ACL does not exist. This entity inherits its permissions from:"
                        in str(e)
                    ):
                        # If the entity does not have an ACL, return an empty ACL
                        return {"resourceAccess": []}
                    raise e

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _storeACL(
        self, entity: Union[Entity, str], acl: Dict[str, Union[str, list]]
    ) -> Dict[str, Union[str, list]]:
        """
        Create or update the ACL for a Synapse Entity.

        Arguments:
            entity:  A Synapse Entity or Synapse ID
            acl:     An ACl as a dictionary

        The format of acl:

            {'resourceAccess': [
                {'accessType': ['READ'],
                 'principalId': 222222}
            ]}

        Returns:
            The new or updated ACL
        """
        if hasattr(entity, "putACLURI"):
            return self.restPUT(entity.putACLURI(), json.dumps(acl))
        else:
            # Get benefactor. (An entity gets its ACL from its benefactor.)
            entity_id = id_of(entity)
            uri = "/entity/%s/benefactor" % entity_id
            benefactor = self.restGET(uri)

            # Update or create new ACL
            uri = "/entity/%s/acl" % entity_id
            if benefactor["id"] == entity_id:
                return self.restPUT(uri, json.dumps(acl))
            else:
                return self.restPOST(uri, json.dumps(acl))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getUserbyPrincipalIdOrName(self, principalId: str = None) -> int:
        """
        Given either a string, int or None finds the corresponding user where None implies PUBLIC

        Arguments:
            principalId: Identifier of a user or group

        Raises:
            SynapseError: Warn for unknown user principalId

        Returns:
            The integer ID of the user
        """
        if principalId is None or principalId == "PUBLIC":
            return PUBLIC
        try:
            return int(principalId)

        # If principalId is not a number assume it is a name or email
        except ValueError:
            userProfiles = self.restGET("/userGroupHeaders?prefix=%s" % principalId)
            totalResults = len(userProfiles["children"])
            if totalResults == 1:
                return int(userProfiles["children"][0]["ownerId"])
            elif totalResults > 1:
                for profile in userProfiles["children"]:
                    if profile["userName"] == principalId:
                        return int(profile["ownerId"])

            supplementalMessage = (
                "Please be more specific" if totalResults > 1 else "No matches"
            )
            raise SynapseError(
                "Unknown Synapse user (%s).  %s." % (principalId, supplementalMessage)
            )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `get_acl` method on the dataclass models that inherit from `AccessControllable` mixin. "
        "Example: `from synapseclient.models import File; File(id='syn123').get_acl()`",
    )
    def get_acl(
        self,
        entity: Union[Entity, Evaluation, str, collections.abc.Mapping],
        principal_id: str = None,
        check_benefactor: bool = True,
    ) -> typing.List[str]:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `get_acl` method on the dataclass models that inherit from `AccessControllable` mixin instead.

        Get the [ACL](https://rest-docs.synapse.org/rest/org/
        sagebionetworks/repo/model/ACCESS_TYPE.html)
        that a user or group has on an Entity.

        Arguments:
            entity:      An Entity or Synapse ID to lookup
            principal_id: Identifier of a user or group (defaults to PUBLIC users)
            check_benefactor: If True (default), check the benefactor for the entity
                to get the ACL. If False, only check the entity itself.
                This is useful for checking the ACL of an entity that has local sharing
                settings, but you want to check the ACL of the entity itself and not
                the benefactor it may inherit from.

        Returns:
            An array containing some combination of
                ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
                'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
                or an empty array

        Example: Using this function (DEPRECATED)
            Getting ACL permissions for a user on an entity

                permissions = syn.get_acl("syn123", principal_id="12345")

            Getting ACL permissions for the public on an entity

                permissions = syn.get_acl("syn123")

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                File, Folder, Project, Table, EntityView, Dataset,
                DatasetCollection, MaterializedView, SubmissionView, VirtualTable
            )

            # Create client and login
            syn = Synapse()
            syn.login()

            # Get ACL permissions for a specific user on a File
            file_instance = File(id="syn123")
            permissions = file_instance.get_acl(principal_id=12345)
            print(f"User 12345 permissions on File syn123: {permissions}")

            # Get ACL permissions for the public on a File
            file_instance = File(id="syn123")
            permissions = file_instance.get_acl()  # defaults to PUBLIC users
            print(f"Public permissions on File syn123: {permissions}")

            # Get ACL permissions with benefactor check disabled
            file_instance = File(id="syn123")
            permissions = file_instance.get_acl(
                principal_id=12345,
                check_benefactor=False
            )
            print(f"Entity-specific permissions for user 12345 on File syn123: {permissions}")

            # Works with all AccessControllable models:

            # Project
            project = Project(id="syn123")
            permissions = project.get_acl(principal_id=12345)
            print(f"User 12345 permissions on Project syn123: {permissions}")

            # Folder
            folder = Folder(id="syn123")
            permissions = folder.get_acl(principal_id=12345)
            print(f"User 12345 permissions on Folder syn123: {permissions}")

            # Table
            table = Table(id="syn123")
            permissions = table.get_acl(principal_id=12345)
            print(f"User 12345 permissions on Table syn123: {permissions}")

            # EntityView
            entity_view = EntityView(id="syn123")
            permissions = entity_view.get_acl(principal_id=12345)
            print(f"User 12345 permissions on EntityView syn123: {permissions}")

            # Dataset
            dataset = Dataset(id="syn123")
            permissions = dataset.get_acl(principal_id=12345)
            print(f"User 12345 permissions on Dataset syn123: {permissions}")

            # DatasetCollection
            dataset_collection = DatasetCollection(id="syn123")
            permissions = dataset_collection.get_acl(principal_id=12345)
            print(f"User 12345 permissions on DatasetCollection syn123: {permissions}")

            # MaterializedView
            materialized_view = MaterializedView(id="syn123")
            permissions = materialized_view.get_acl(principal_id=12345)
            print(f"User 12345 permissions on MaterializedView syn123: {permissions}")

            # SubmissionView
            submission_view = SubmissionView(id="syn123")
            permissions = submission_view.get_acl(principal_id=12345)
            print(f"User 12345 permissions on SubmissionView syn123: {permissions}")

            # VirtualTable
            virtual_table = VirtualTable(id="syn123")
            permissions = virtual_table.get_acl(principal_id=12345)
            print(f"User 12345 permissions on VirtualTable syn123: {permissions}")

            # Additional functionality available on AccessControllable models:

            # List all ACL entries for an entity
            file_instance = File(id="syn123")
            acl_list = file_instance.list_acl()
            print(f"All ACL entries for File syn123: {acl_list}")

            # Delete the entire ACL for an entity (makes it inherit from benefactor)
            file_instance = File(id="syn123")
            file_instance.delete_permissions()
            print("Successfully deleted entire ACL for File syn123 - now inherits permissions")

            # To remove permissions for a specific user/group, use set_permissions with empty access_type
            file_instance = File(id="syn123")
            file_instance.set_permissions(principal_id=12345, access_type=[])
            print("Successfully removed all permissions for user 12345 on File syn123")

            # Use dry_run to preview what would be deleted without actually deleting
            file_instance = File(id="syn123")
            file_instance.delete_permissions(dry_run=True)
            print("Dry run completed - showed what would be deleted")
            ```
        """

        principal_id = self._getUserbyPrincipalIdOrName(principal_id)

        trace.get_current_span().set_attributes(
            {"synapse.id": id_of(entity), "synapse.principal_id": principal_id}
        )

        acl = self._getACL(entity=entity, check_benefactor=check_benefactor)

        team_list = self._find_teams_for_principal(principal_id)
        team_ids = [int(team.id) for team in team_list]
        effective_permission_set = set()

        # This user_profile_bundle is being used to verify that the principal_id
        #  is a registered user of the system
        user_profile_bundle = self._get_user_bundle(principal_id, 1)

        # Loop over all permissions in the returned ACL and add it to the effective_permission_set
        # if the principalId in the ACL matches
        # 1) the one we are looking for,
        # 2) a team the entity is a member of,
        # 3) PUBLIC
        # 4) A user_profile_bundle exists for the principal_id
        for permissions in acl["resourceAccess"]:
            if "principalId" in permissions and (
                permissions["principalId"] == principal_id
                or permissions["principalId"] in team_ids
                or permissions["principalId"] == PUBLIC
                or (
                    permissions["principalId"] == AUTHENTICATED_USERS
                    and user_profile_bundle is not None
                )
            ):
                effective_permission_set = effective_permission_set.union(
                    permissions["accessType"]
                )
        return list(effective_permission_set)

    @deprecated(
        version="4.0.0",
        reason="deprecated and replaced with synapseclient.Synapse.get_acl",
    )
    def getPermissions(
        self,
        entity: Union[Entity, Evaluation, str, collections.abc.Mapping],
        principal_id: str = None,
    ) -> typing.List[str]:
        """
        **Deprecated** and replaced with [get_acl][synapseclient.Synapse.get_acl].


        Get the permissions that a user or group has on an Entity.

        Arguments:
            entity:      An Entity or Synapse ID to lookup
            principal_id: Identifier of a user or group (defaults to PUBLIC users)

        Returns:
            An array containing some combination of
                ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
                'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
                or an empty array
        """

        return self.get_acl(entity=entity, principal_id=principal_id)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `get_permissions` method on the dataclass models that inherit from `AccessControllable` mixin. "
        "Note: The new `get_permissions` method only returns permissions for the current user. "
        "To get permissions for a specific principal, use the `get_acl` method instead. "
        "Example: `from synapseclient.models import File; File(id='syn123').get_permissions(); File(id='syn123').get_acl(principal_id=12345)`",
    )
    def get_permissions(
        self, entity: Union[Entity, Evaluation, str, collections.abc.Mapping]
    ) -> Permissions:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `get_permissions` method on the dataclass models that inherit from `AccessControllable` mixin instead.

        Get the [permissions](https://rest-docs.synapse.org/rest/org/
        sagebionetworks/repo/model/auth/UserEntityPermissions.html)
        that the caller has on an Entity.

        Arguments:
            entity: An Entity or Synapse ID to lookup

        Returns:
            An Permissions object

        Example: Using this function (DEPRECATED)
            Getting permissions for a Synapse Entity

                permissions = syn.get_permissions(Entity)

            Getting permissions for a Synapse ID

                permissions = syn.get_permissions("syn12345")

            Getting access types list from the Permissions object

                permissions.access_types

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                File, Folder, Project, Table, EntityView, Dataset,
                DatasetCollection, MaterializedView, SubmissionView, VirtualTable
            )

            # Create client and login
            syn = Synapse()
            syn.login()

            # Get permissions for the current user on a File
            file_instance = File(id="syn12345")
            permissions = file_instance.get_permissions()
            print(f"Current user permissions on File syn12345: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # Get permissions for the current user on other entity types:

            # Project
            project = Project(id="syn12345")
            permissions = project.get_permissions()
            print(f"Current user permissions on Project {project.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # Folder
            folder = Folder(id="syn12345")
            permissions = folder.get_permissions()
            print(f"Current user permissions on Folder {folder.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # Table
            table = Table(id="syn12345")
            permissions = table.get_permissions()
            print(f"Current user permissions on Table {table.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # EntityView
            entity_view = EntityView(id="syn12345")
            permissions = entity_view.get_permissions()
            print(f"Current user permissions on EntityView {entity_view.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # Dataset
            dataset = Dataset(id="syn12345")
            permissions = dataset.get_permissions()
            print(f"Current user permissions on Dataset {dataset.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # DatasetCollection
            dataset_collection = DatasetCollection(id="syn12345")
            permissions = dataset_collection.get_permissions()
            print(f"Current user permissions on DatasetCollection {dataset_collection.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # MaterializedView
            materialized_view = MaterializedView(id="syn12345")
            permissions = materialized_view.get_permissions()
            print(f"Current user permissions on MaterializedView {materialized_view.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # SubmissionView
            submission_view = SubmissionView(id="syn12345")
            permissions = submission_view.get_permissions()
            print(f"Current user permissions on SubmissionView {submission_view.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # VirtualTable
            virtual_table = VirtualTable(id="syn12345")
            permissions = virtual_table.get_permissions()
            print(f"Current user permissions on VirtualTable {virtual_table.id}: {permissions}")
            print(f"Current user access types: {permissions.access_types}")

            # To get permissions for a specific user/group, use get_acl instead:
            file_instance = File(id="syn12345")

            # Get ACL permissions for a specific user
            user_permissions = file_instance.get_acl(principal_id=12345)
            print(f"User 12345 permissions on File {file_instance.id}: {user_permissions}")

            # Get ACL permissions for the public
            public_permissions = file_instance.get_acl()  # defaults to PUBLIC users
            print(f"Public permissions on File {file_instance.id}: {public_permissions}")

            # List all ACL entries for an entity
            acl_list = file_instance.list_acl()
            print(f"All ACL entries for File {file_instance.id}: {acl_list}")
            ```
        """

        entity_id = id_of(entity)

        trace.get_current_span().set_attributes({"synapse.id": entity_id})

        url = f"/entity/{entity_id}/permissions"
        data = self.restGET(url)
        return Permissions.from_dict(data)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `set_permissions` method on the dataclass models that inherit from `AccessControllable` mixin. "
        "Example: `from synapseclient.models import File; File(id='syn123').set_permissions(principal_id=12345, access_type=['READ'])`. "
        "To remove permissions for a specific user, use `access_type=[]` or `access_type=None`.",
    )
    def setPermissions(
        self,
        entity,
        principalId=None,
        accessType=["READ", "DOWNLOAD"],
        modify_benefactor=False,
        warn_if_inherits=True,
        overwrite=True,
    ):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `set_permissions` method on the dataclass models that inherit from `AccessControllable` mixin instead.

        Sets permission that a user or group has on an Entity.
        An Entity may have its own ACL or inherit its ACL from a benefactor.

        Arguments:
            entity: An Entity or Synapse ID to modify
            principalId: Identifier of a user or group. '273948' is for all registered Synapse users
                            and '273949' is for public access. None implies public access.
            accessType: Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE,
                            DELETE, CHANGE_PERMISSIONS
            modify_benefactor: Set as True when modifying a benefactor's ACL. The term
                'benefactor' is used to indicate which Entity an Entity inherits its
                ACL from. For example, a newly created Project will be its own
                benefactor, while a new FileEntity's benefactor will start off as its
                containing Project. If the entity already has local sharing settings
                the benefactor would be itself. It may also be the immediate parent,
                somewhere in the parent tree, or the project itself.
            warn_if_inherits: When `modify_benefactor` is True, this does not have any
                effect. When `modify_benefactor` is False, and `warn_if_inherits` is
                True, a warning log message is produced if the benefactor for the
                entity you passed into the function is not itself, i.e., it's the
                parent folder, or another entity in the parent tree.
            overwrite: By default this function overwrites existing permissions for the specified user.
                        Set this flag to False to add new permissions non-destructively.

        Returns:
            An Access Control List object

        Example: Using this function (DEPRECATED)
            Grant all registered users download access

                syn.setPermissions('syn1234','273948',['READ','DOWNLOAD'])

            Grant the public view access

                syn.setPermissions('syn1234','273949',['READ'])

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse, AUTHENTICATED_USERS, PUBLIC
            from synapseclient.models import (
                File, Folder, Project, Table, EntityView, Dataset,
                DatasetCollection, MaterializedView, SubmissionView, VirtualTable
            )

            # Create client and login
            syn = Synapse()
            syn.login()

            # Set permissions for a File
            file_instance = File(id="syn1234")

            # Grant all registered users download access
            file_instance.set_permissions(
                principal_id=AUTHENTICATED_USERS,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully granted READ and DOWNLOAD access to all registered users on File {file_instance.id}")

            # Grant the public view access
            file_instance.set_permissions(
                principal_id=PUBLIC,
                access_type=["READ"]
            )
            print(f"Successfully granted READ access to public users on File {file_instance.id}")

            # Set permissions with additional options
            file_instance.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD", "UPDATE"],
                modify_benefactor=True,
                warn_if_inherits=False,
                overwrite=False  # Add to existing permissions instead of overwriting
            )
            print(f"Successfully added READ, DOWNLOAD, and UPDATE access for user 12345 on File {file_instance.id}")

            # Remove permissions for a specific user/group by setting access_type to empty list
            file_instance.set_permissions(
                principal_id=12345,
                access_type=[]  # Empty list removes all permissions for this principal
            )
            print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

            # Alternative: Remove permissions by setting access_type to None
            file_instance.set_permissions(
                principal_id=12345,
                access_type=None  # None also removes all permissions for this principal
            )
            print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

            # Set permissions for other entity types:

            # Project
            project = Project(id="syn1234")
            project.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Project {project.id}")

            # Folder
            folder = Folder(id="syn1234")
            folder.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Folder {folder.id}")

            # Table
            table = Table(id="syn1234")
            table.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Table {table.id}")

            # EntityView
            entity_view = EntityView(id="syn1234")
            entity_view.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on EntityView {entity_view.id}")

            # Dataset
            dataset = Dataset(id="syn1234")
            dataset.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Dataset {dataset.id}")

            # DatasetCollection
            dataset_collection = DatasetCollection(id="syn1234")
            dataset_collection.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on DatasetCollection {dataset_collection.id}")

            # MaterializedView
            materialized_view = MaterializedView(id="syn1234")
            materialized_view.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on MaterializedView {materialized_view.id}")

            # SubmissionView
            submission_view = SubmissionView(id="syn1234")
            submission_view.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on SubmissionView {submission_view.id}")

            # VirtualTable
            virtual_table = VirtualTable(id="syn1234")
            virtual_table.set_permissions(
                principal_id=12345,
                access_type=["READ", "DOWNLOAD"]
            )
            print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on VirtualTable {virtual_table.id}")

            # Additional functionality available on AccessControllable models:

            # List all ACL entries for an entity
            file_instance = File(id="syn1234")
            acl_list = file_instance.list_acl()
            print(f"All ACL entries for File syn1234: {acl_list}")

            # Delete the entire ACL for an entity (makes it inherit from benefactor)
            file_instance = File(id="syn1234")
            file_instance.delete_permissions()
            print(f"Successfully deleted entire ACL for File {file_instance.id} - now inherits permissions")

            # To remove permissions for a specific user/group, use set_permissions with empty access_type
            file_instance = File(id="syn1234")
            file_instance.set_permissions(principal_id=12345, access_type=[])
            print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

            # Use dry_run to preview what would be deleted without actually deleting
            file_instance = File(id="syn1234")
            file_instance.delete_permissions(dry_run=True)
            print("Dry run completed - showed what would be deleted")
            ```
        """
        entity_id = id_of(entity)
        trace.get_current_span().set_attributes({"synapse.id": entity_id})

        benefactor = self._getBenefactor(entity)
        if benefactor["id"] != entity_id:
            if modify_benefactor:
                entity = benefactor
            elif warn_if_inherits:
                self.logger.warning(
                    "Creating an ACL for entity %s, which formerly inherited access control from a"
                    ' benefactor entity, "%s" (%s).\n'
                    % (entity_id, benefactor["name"], benefactor["id"])
                )

        acl = self._getACL(entity)

        principalId = self._getUserbyPrincipalIdOrName(principalId)

        # Find existing permissions
        permissions_to_update = None
        for permissions in acl["resourceAccess"]:
            if (
                "principalId" in permissions
                and permissions["principalId"] == principalId
            ):
                permissions_to_update = permissions
                break

        if accessType is None or accessType == []:
            # remove permissions
            if permissions_to_update and overwrite:
                acl["resourceAccess"].remove(permissions_to_update)
        else:
            # add a 'resourceAccess' entry, if necessary
            if not permissions_to_update:
                permissions_to_update = {"accessType": [], "principalId": principalId}
                acl["resourceAccess"].append(permissions_to_update)
            if overwrite:
                permissions_to_update["accessType"] = accessType
            else:
                permissions_to_update["accessType"] = list(
                    set(permissions_to_update["accessType"]) | set(accessType)
                )
        return self._storeACL(entity, acl)

    ############################################################
    #                        Provenance                        #
    ############################################################

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `get` method on the `from synapseclient.models import Activity` class. "
        "Check the docstring for the replacement function example.",
    )
    def getProvenance(
        self,
        entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
        version: int = None,
    ) -> Activity:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Activity.get][] instead.

        Retrieve provenance information for a Synapse Entity.

        Arguments:
            entity:  An Entity or Synapse ID to lookup
            version: The version of the Entity to retrieve. Gets the most recent version if omitted

        Returns:
            An Activity object or raises exception if no provenance record exists

        Raises:
            SynapseHTTPError: if no provenance record exists

        Example: Using this function (DEPRECATED)
            Getting provenance for an entity

                activity = syn.getProvenance("syn123")

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Activity

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get the activity associated with the entity
            activity = Activity.get(parent_id="syn123")
            if activity:
                print(f"Activity: {activity.name}")
            else:
                print("No activity found")

            # Get the activity for a specific version
            activity = Activity.get(parent_id="syn123", parent_version_number=2)
            if activity:
                print(f"Activity: {activity.name}")
            else:
                print("No activity found")
            ```
        """
        # Get versionNumber from Entity
        if version is None and "versionNumber" in entity:
            version = entity["versionNumber"]
        entity_id = id_of(entity)
        if version:
            uri = "/entity/%s/version/%d/generatedBy" % (entity_id, version)
        else:
            uri = "/entity/%s/generatedBy" % entity_id

        trace.get_current_span().set_attributes({"synapse.id": entity_id})
        return Activity(data=self.restGET(uri))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `store` method on the `from synapseclient.models import Activity` class. "
        "Check the docstring for the replacement function example.",
    )
    def setProvenance(
        self,
        entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
        activity: Activity,
    ) -> Activity:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Activity.store][] instead.

        Stores a record of the code and data used to derive a Synapse entity.

        Arguments:
            entity:   An Entity or Synapse ID to modify
            activity: A [synapseclient.activity.Activity][]

        Returns:
            An updated [synapseclient.activity.Activity][] object

        Example: Using this function (DEPRECATED)
            Setting provenance for an entity

                activity = Activity(name="Analysis", description="Data processing")
                updated_activity = syn.setProvenance("syn123", activity)

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Activity

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Create an activity
            activity = Activity(
                name="Analysis",
                description="Data processing"
            )

            # Store the activity and associate it with the entity
            stored_activity = activity.store(parent="syn123")
            print(f"Stored activity: {stored_activity.name}")
            ```
        """
        # Assert that the entity was generated by a given Activity.
        activity = self._saveActivity(activity)

        entity_id = id_of(entity)
        # assert that an entity is generated by an activity
        uri = "/entity/%s/generatedBy?generatedBy=%s" % (entity_id, activity["id"])
        activity = Activity(data=self.restPUT(uri))

        trace.get_current_span().set_attributes({"synapse.id": entity_id})
        return activity

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `delete` method on the `from synapseclient.models import Activity` class. "
        "Check the docstring for the replacement function example.",
    )
    def deleteProvenance(
        self,
        entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
    ) -> None:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Activity.delete][] instead.

        Removes provenance information from an Entity and deletes the associated Activity.

        Arguments:
            entity: An Entity or Synapse ID to modify

        Example: Using this function (DEPRECATED)
            Deleting provenance for an entity

                syn.deleteProvenance("syn123")

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Activity

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Delete the activity associated with the entity
            Activity.delete(parent="syn123")
            print("Activity deleted")
            ```
        """
        activity = self.getProvenance(entity)
        if not activity:
            return
        entity_id = id_of(entity)
        trace.get_current_span().set_attributes({"synapse.id": entity_id})

        uri = "/entity/%s/generatedBy" % entity_id
        self.restDELETE(uri)

        # If the activity is shared by more than one entity you recieve an HTTP 400 error:
        # "If you wish to delete this activity, please first delete all Entities generated by this Activity.""
        uri = "/activity/%s" % activity["id"]
        self.restDELETE(uri)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _saveActivity(self, activity: Activity) -> Activity:
        """
        Save the Activity

        Arguments:
            activity: The Activity to be saved

        Returns:
            An Activity object
        """
        if "id" in activity:
            # We're updating provenance
            uri = "/activity/%s" % activity["id"]
            activity = Activity(data=self.restPUT(uri, json.dumps(activity)))
        else:
            activity = self.restPOST("/activity", body=json.dumps(activity))
        return activity

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `store` method on the `from synapseclient.models import Activity` class. "
        "Check the docstring for the replacement function example.",
    )
    def updateActivity(self, activity) -> Activity:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Activity.store][] instead.

        Modifies an existing Activity.

        Arguments:
            activity: The Activity to be updated.

        Returns:
            An updated Activity object

        Example: Using this function (DEPRECATED)
            Updating an existing activity

                activity = syn.getProvenance("syn123")
                activity['name'] = "Updated Analysis"
                updated_activity = syn.updateActivity(activity)

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Activity

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get the existing activity by parent entity
            activity = Activity.get(parent_id="syn123")

            if activity:
                # Update the activity
                activity.name = "Updated Analysis"
                activity.description = "Updated data processing"

                # Store the updated activity
                updated_activity = activity.store()
                print(f"Updated activity: {updated_activity.name}")
            ```
        """
        if "id" not in activity:
            raise ValueError("The activity you want to update must exist on Synapse")
        trace.get_current_span().set_attributes({"synapse.id": activity["id"]})
        return self._saveActivity(activity)

    # TODO: Deprecate this method and point to new functionality - This is used from the CLI only
    def _convertProvenanceList(self, usedList: list, limitSearch: str = None) -> list:
        """
        Convert a list of Synapse IDs, URLs and local files by replacing local files with Synapse IDs

        Arguments:
            usedList:    A list of Synapse IDs, URLs and local files
            limitSearch: Limits the places in Synapse where the file is searched for.

        Returns:
            A converted list with local files being replaced with Synapse IDs
        """
        if usedList is None:
            return None
        usedList = [
            (
                self.get(target, limitSearch=limitSearch)
                if (os.path.isfile(target) if isinstance(target, str) else False)
                else target
            )
            for target in usedList
        ]
        return usedList

    ############################################################
    #                File handle service calls                 #
    ############################################################

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/api/file_services.py::get_file_handle_for_download",
    )
    def _getFileHandleDownload(
        self, fileHandleId: str, objectId: str, objectType: str = None
    ) -> Dict[str, str]:
        """
        Gets the URL and the metadata as filehandle object for a filehandle or fileHandleId

        Arguments:
            fileHandleId:   ID of fileHandle to download
            objectId:       The ID of the object associated with the file e.g. syn234
            objectType:     Type of object associated with a file e.g. FileEntity, TableEntity

        Raises:
            SynapseFileNotFoundError: If the fileHandleId is not found in Synapse.
            SynapseError:             If the user does not have the permission to access the fileHandleId.

        Returns:
            A dictionary with keys: fileHandle, fileHandleId and preSignedURL
        """
        body = {
            "includeFileHandles": True,
            "includePreSignedURLs": True,
            "requestedFiles": [
                {
                    "fileHandleId": fileHandleId,
                    "associateObjectId": objectId,
                    "associateObjectType": objectType or "FileEntity",
                }
            ],
        }
        response = self.restPOST(
            "/fileHandle/batch", body=json.dumps(body), endpoint=self.fileHandleEndpoint
        )
        result = response["requestedFiles"][0]
        failure = result.get("failureCode")
        if failure == "NOT_FOUND":
            raise SynapseFileNotFoundError(
                "The fileHandleId %s could not be found" % fileHandleId
            )
        elif failure == "UNAUTHORIZED":
            raise SynapseError(
                "You are not authorized to access fileHandleId %s associated with the Synapse"
                " %s: %s" % (fileHandleId, objectType, objectId)
            )
        return result

    @staticmethod
    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::is_retryable_download_error",
    )
    def _is_retryable_download_error(ex: Exception) -> bool:
        """
        Check if the download error is retryable

        Arguments:
            ex: An exception

        Returns:
            Boolean value indicating whether the download error is retryable
        """
        # some exceptions caught during download indicate non-recoverable situations that
        # will not be remedied by a repeated download attempt.
        return not (
            (isinstance(ex, OSError) and ex.errno == errno.ENOSPC)
            or isinstance(ex, SynapseMd5MismatchError)  # out of disk space
        )

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::download_by_file_handle",
    )
    def _downloadFileHandle(
        self,
        fileHandleId: str,
        objectId: str,
        objectType: str,
        destination: str,
        retries: int = 5,
    ) -> str:
        """
        Download a file from the given URL to the local file system.

        Arguments:
            fileHandleId: The id of the FileHandle to download
            objectId:     The id of the Synapse object that uses the FileHandle e.g. "syn123"
            objectType:   The type of the Synapse object that uses the FileHandle e.g. "FileEntity"
            destination:  The destination on local file system
            retries:      The Number of download retries attempted before throwing an exception.

        Returns:
            The path to downloaded file
        """
        os.makedirs(os.path.dirname(destination), exist_ok=True)

        while retries > 0:
            try:
                fileResult = self._getFileHandleDownload(
                    fileHandleId, objectId, objectType
                )
                fileHandle = fileResult["fileHandle"]
                concreteType = fileHandle["concreteType"]
                storageLocationId = fileHandle.get("storageLocationId")

                if concreteType == concrete_types.EXTERNAL_OBJECT_STORE_FILE_HANDLE:
                    profile = get_client_authenticated_s3_profile(
                        endpoint=fileHandle["endpointUrl"],
                        bucket=fileHandle["bucket"],
                        config_path=self.configPath,
                    )
                    downloaded_path = S3ClientWrapper.download_file(
                        fileHandle["bucket"],
                        fileHandle["endpointUrl"],
                        fileHandle["fileKey"],
                        destination,
                        profile_name=profile,
                        show_progress=not self.silent,
                    )

                elif (
                    sts_transfer.is_boto_sts_transfer_enabled(self)
                    and sts_transfer.is_storage_location_sts_enabled(
                        self, objectId, storageLocationId
                    )
                    and concreteType == concrete_types.S3_FILE_HANDLE
                ):

                    def download_fn(credentials):
                        return S3ClientWrapper.download_file(
                            fileHandle["bucketName"],
                            None,
                            fileHandle["key"],
                            destination,
                            credentials=credentials,
                            show_progress=not self.silent,
                            # pass through our synapse threading config to boto s3
                            transfer_config_kwargs={
                                "max_concurrency": self.max_threads
                            },
                        )

                    downloaded_path = sts_transfer.with_boto_sts_credentials(
                        download_fn,
                        self,
                        objectId,
                        "read_only",
                    )

                elif (
                    self.multi_threaded
                    and concreteType == concrete_types.S3_FILE_HANDLE
                    and fileHandle.get("contentSize", 0)
                    > multithread_download.SYNAPSE_DEFAULT_DOWNLOAD_PART_SIZE
                ):
                    # run the download multi threaded if the file supports it, we're configured to do so,
                    # and the file is large enough that it would be broken into parts to take advantage of
                    # multiple downloading threads. otherwise it's more efficient to run the download as a simple
                    # single threaded URL download.
                    downloaded_path = self._download_from_url_multi_threaded(
                        fileHandleId,
                        objectId,
                        objectType,
                        destination,
                        expected_md5=fileHandle.get("contentMd5"),
                    )

                else:
                    downloaded_path = self._download_from_URL(
                        fileResult["preSignedURL"],
                        destination,
                        fileHandle["id"],
                        expected_md5=fileHandle.get("contentMd5"),
                    )
                self.cache.add(fileHandle["id"], downloaded_path)
                return downloaded_path

            except Exception as ex:
                if not self._is_retryable_download_error(ex):
                    raise

                exc_info = sys.exc_info()
                ex.progress = 0 if not hasattr(ex, "progress") else ex.progress
                self.logger.debug(
                    "\nRetrying download on error: [%s] after progressing %i bytes"
                    % (exc_info[0], ex.progress),
                    exc_info=True,
                )  # this will include stack trace
                if ex.progress == 0:  # No progress was made reduce remaining retries.
                    retries -= 1
                if retries <= 0:
                    # Re-raise exception
                    raise

        raise Exception("should not reach this line")

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::download_from_url_multi_threaded",
    )
    def _download_from_url_multi_threaded(
        self,
        file_handle_id: str,
        object_id: str,
        object_type: str,
        destination: str,
        *,
        expected_md5: str = None,
    ) -> str:
        """
        Download a file from the given URL using multiple threads.

        Arguments:
            file_handle_id: The id of the FileHandle to download
            object_id:      The id of the Synapse object that uses the FileHandle e.g. "syn123"
            object_type:    The type of the Synapse object that uses the FileHandle e.g. "FileEntity"
            destination:    The destination on local file system
            expected_md5:   The expected MD5
        Raises:
            SynapseMd5MismatchError: If the actual MD5 does not match expected MD5.

        Returns:
            The path to downloaded file
        """
        destination = os.path.abspath(destination)
        temp_destination = utils.temp_download_filename(destination, file_handle_id)

        request = multithread_download.DownloadRequest(
            file_handle_id=int(file_handle_id),
            object_id=object_id,
            object_type=object_type,
            path=temp_destination,
            debug=self.debug,
        )

        multithread_download.download_file(self, request)

        if (
            expected_md5
        ):  # if md5 not set (should be the case for all except http download)
            actual_md5 = utils.md5_for_file(temp_destination).hexdigest()
            # check md5 if given
            if actual_md5 != expected_md5:
                try:
                    os.remove(temp_destination)
                except FileNotFoundError:
                    # file already does not exist. nothing to do
                    pass
                raise SynapseMd5MismatchError(
                    "Downloaded file {filename}'s md5 {md5} does not match expected MD5 of"
                    " {expected_md5}".format(
                        filename=temp_destination,
                        md5=actual_md5,
                        expected_md5=expected_md5,
                    )
                )
        # once download completed, rename to desired destination
        shutil.move(temp_destination, destination)

        return destination

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::is_synapse_uri",
    )
    def _is_synapse_uri(self, uri: str) -> bool:
        """
        Check whether the given uri is hosted at the configured Synapse repo endpoint

        Arguments:
            uri: A given uri

        Returns:
            A boolean value indicating whether the given uri is hosted at the configured Synapse repo endpoint
        """
        uri_domain = urllib_urlparse.urlparse(uri).netloc
        synapse_repo_domain = urllib_urlparse.urlparse(self.repoEndpoint).netloc
        return uri_domain.lower() == synapse_repo_domain.lower()

    @deprecated(
        version="4.4.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient/core/download/download_functions.py::download_from_url",
    )
    def _download_from_URL(
        self,
        url: str,
        destination: str,
        fileHandleId: Optional[str] = None,
        expected_md5: Optional[str] = None,
    ) -> str:
        """
        Download a file from the given URL to the local file system.

        Arguments:
            url:           The source of download
            destination:   The destination on local file system
            fileHandleId:  Optional. If given, the file will be given a temporary name that includes the file
                                    handle id which allows resuming partial downloads of the same file from previous
                                    sessions
            expected_md5:  Optional. If given, check that the MD5 of the downloaded file matches the expected MD5

        Raises:
            IOError:                 If the local file does not exist.
            SynapseError:            If fail to download the file.
            SynapseHTTPError:        If there are too many redirects.
            SynapseMd5MismatchError: If the actual MD5 does not match expected MD5.

        Returns:
            The path to downloaded file
        """
        destination = os.path.abspath(destination)
        actual_md5 = None
        redirect_count = 0
        delete_on_md5_mismatch = True
        self.logger.debug(f"Downloading from {url} to {destination}")
        while redirect_count < REDIRECT_LIMIT:
            redirect_count += 1
            scheme = urllib_urlparse.urlparse(url).scheme
            if scheme == "file":
                delete_on_md5_mismatch = False
                destination = utils.file_url_to_path(url, verify_exists=True)
                if destination is None:
                    raise IOError("Local file (%s) does not exist." % url)
                break
            elif scheme == "sftp":
                username, password = self._getUserCredentials(url)
                destination = SFTPWrapper.download_file(
                    url, destination, username, password, show_progress=not self.silent
                )
                break
            elif scheme == "ftp":
                transfer_start_time = time.time()

                def _ftp_report_hook(
                    block_number: int, read_size: int, total_size: int
                ) -> None:
                    show_progress = not self.silent
                    if show_progress:
                        self._print_transfer_progress(
                            transferred=block_number * read_size,
                            toBeTransferred=total_size,
                            prefix="Downloading ",
                            postfix=os.path.basename(destination),
                            dt=time.time() - transfer_start_time,
                        )

                urllib_request.urlretrieve(
                    url=url, filename=destination, reporthook=_ftp_report_hook
                )
                break
            elif scheme == "http" or scheme == "https":
                # if a partial download exists with the temporary name,
                temp_destination = utils.temp_download_filename(
                    destination, fileHandleId
                )
                range_header = (
                    {
                        "Range": "bytes={start}-".format(
                            start=os.path.getsize(temp_destination)
                        )
                    }
                    if os.path.exists(temp_destination)
                    else {}
                )

                # pass along synapse auth credentials only if downloading directly from synapse
                auth = self.credentials if self._is_synapse_uri(url) else None
                response = with_retry(
                    lambda: self._requests_session.get(
                        url,
                        headers=self._generate_headers(range_header),
                        stream=True,
                        allow_redirects=False,
                        auth=auth,
                    ),
                    verbose=self.debug,
                    **STANDARD_RETRY_PARAMS,
                )
                try:
                    exceptions._raise_for_status(response, verbose=self.debug)
                except SynapseHTTPError as err:
                    if err.response.status_code == 404:
                        raise SynapseError("Could not download the file at %s" % url)
                    elif (
                        err.response.status_code == 416
                    ):  # Requested Range Not Statisfiable
                        # this is a weird error when the client already finished downloading but the loop continues
                        # When this exception occurs, the range we request is guaranteed to be >= file size so we
                        # assume that the file has been fully downloaded, rename it to destination file
                        # and break out of the loop to perform the MD5 check.
                        # If it fails the user can retry with another download.
                        shutil.move(temp_destination, destination)
                        break
                    raise

                # handle redirects
                if response.status_code in [301, 302, 303, 307, 308]:
                    url = response.headers["location"]
                    # don't break, loop again
                else:
                    # get filename from content-disposition, if we don't have it already
                    if os.path.isdir(destination):
                        filename = utils.extract_filename(
                            content_disposition_header=response.headers.get(
                                "content-disposition", None
                            ),
                            default_filename=utils.guess_file_name(url),
                        )
                        destination = os.path.join(destination, filename)
                    # Stream the file to disk
                    if "content-length" in response.headers:
                        toBeTransferred = float(response.headers["content-length"])
                    else:
                        toBeTransferred = -1
                    transferred = 0

                    # Servers that respect the Range header return 206 Partial Content
                    if response.status_code == 206:
                        mode = "ab"
                        previouslyTransferred = os.path.getsize(temp_destination)
                        toBeTransferred += previouslyTransferred
                        transferred += previouslyTransferred
                        sig = utils.md5_for_file(temp_destination)
                    else:
                        mode = "wb"
                        previouslyTransferred = 0
                        sig = hashlib.new("md5", usedforsecurity=False)  # nosec

                    try:
                        with open(temp_destination, mode) as fd:
                            t0 = time.time()
                            for nChunks, chunk in enumerate(
                                response.iter_content(FILE_BUFFER_SIZE)
                            ):
                                fd.write(chunk)
                                sig.update(chunk)

                                # the 'content-length' header gives the total number of bytes that will be transferred
                                # to us len(chunk) cannot be used to track progress because iter_content automatically
                                # decodes the chunks if the response body is encoded so the len(chunk) could be
                                # different from the total number of bytes we've read read from the response body
                                # response.raw.tell() is the total number of response body bytes transferred over the
                                # wire so far
                                transferred = (
                                    response.raw.tell() + previouslyTransferred
                                )
                                self._print_transfer_progress(
                                    transferred,
                                    toBeTransferred,
                                    "Downloading ",
                                    os.path.basename(destination),
                                    dt=time.time() - t0,
                                )
                    except (
                        Exception
                    ) as ex:  # We will add a progress parameter then push it back to retry.
                        ex.progress = transferred - previouslyTransferred
                        raise

                    # verify that the file was completely downloaded and retry if it is not complete
                    if toBeTransferred > 0 and transferred < toBeTransferred:
                        self.logger.warning(
                            "\nRetrying download because the connection ended early.\n"
                        )
                        continue

                    actual_md5 = sig.hexdigest()
                    # rename to final destination
                    shutil.move(temp_destination, destination)
                    break
            else:
                self.logger.error("Unable to download URLs of type %s" % scheme)
                return None

        else:  # didn't break out of loop
            raise SynapseHTTPError("Too many redirects")

        if (
            actual_md5 is None
        ):  # if md5 not set (should be the case for all except http download)
            actual_md5 = utils.md5_for_file(destination).hexdigest()

        # check md5 if given
        if expected_md5 and actual_md5 != expected_md5:
            if delete_on_md5_mismatch and os.path.exists(destination):
                os.remove(destination)
            raise SynapseMd5MismatchError(
                "Downloaded file {filename}'s md5 {md5} does not match expected MD5 of"
                " {expected_md5}".format(
                    filename=destination, md5=actual_md5, expected_md5=expected_md5
                )
            )

        return destination

    def _createExternalFileHandle(
        self,
        externalURL: str,
        mimetype: str = None,
        md5: str = None,
        fileSize: int = None,
    ) -> Dict[str, Union[str, int]]:
        """
        Create a new FileHandle representing an external URL.

        Arguments:
            externalURL: An external URL
            mimetype:    The Mimetype of the file, if known.
            md5:         The file's content MD5.
            fileSize:    The size of the file in bytes.

        Returns:
            A FileHandle for files that are stored externally.
        """
        fileName = externalURL.split("/")[-1]
        externalURL = utils.as_url(externalURL)
        fileHandle = {
            "concreteType": concrete_types.EXTERNAL_FILE_HANDLE,
            "fileName": fileName,
            "externalURL": externalURL,
            "contentMd5": md5,
            "contentSize": fileSize,
        }
        if mimetype is None:
            mimetype, enc = mimetypes.guess_type(externalURL, strict=False)
        if mimetype is not None:
            fileHandle["contentType"] = mimetype
        return self.restPOST(
            "/externalFileHandle", json.dumps(fileHandle), self.fileHandleEndpoint
        )

    def _createExternalObjectStoreFileHandle(
        self,
        s3_file_key,
        file_path: str,
        storage_location_id: int,
        mimetype: str = None,
        md5: str = None,
    ) -> Dict[str, Union[str, int]]:
        """
        Create a new FileHandle representing an external object.

        Arguments:
            s3_file_key:         S3 key of the uploaded object
            file_path:           The local path of the uploaded file
            storage_location_id: The optional storage location descriptor
            mimetype:            The Mimetype of the file, if known.
            md5:                 The file's content MD5, if known.

        Returns:
            A FileHandle for objects that are stored externally.
        """
        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(file_path, strict=False)
        file_handle = {
            "concreteType": concrete_types.EXTERNAL_OBJECT_STORE_FILE_HANDLE,
            "fileKey": s3_file_key,
            "fileName": os.path.basename(file_path),
            "contentMd5": md5 or utils.md5_for_file(file_path).hexdigest(),
            "contentSize": os.stat(file_path).st_size,
            "storageLocationId": storage_location_id,
            "contentType": mimetype,
        }

        return self.restPOST(
            "/externalFileHandle", json.dumps(file_handle), self.fileHandleEndpoint
        )

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.api.post_external_s3_file_handle()` instead.",
    )
    def create_external_s3_file_handle(
        self,
        bucket_name,
        s3_file_key,
        file_path,
        *,
        parent=None,
        storage_location_id=None,
        mimetype=None,
        md5: str = None,
    ):
        """
        Create an external S3 file handle for e.g. a file that has been uploaded directly to
        an external S3 storage location.

        Arguments:
            bucket_name: Name of the S3 bucket
            s3_file_key: S3 key of the uploaded object
            file_path: Local path of the uploaded file
            parent: Parent entity to create the file handle in, the file handle will be created
                    in the default storage location of the parent. Mutually exclusive with
                    storage_location_id
            storage_location_id: Explicit storage location id to create the file handle in, mutually exclusive
                    with parent
            mimetype: Mimetype of the file, if known
            md5: MD5 of the file, if known

        Raises:
            ValueError: If neither parent nor storage_location_id is specified, or if both are specified.
        """

        if storage_location_id:
            if parent:
                raise ValueError("Pass parent or storage_location_id, not both")
        elif not parent:
            raise ValueError("One of parent or storage_location_id is required")
        else:
            upload_destination = self._getDefaultUploadDestination(parent)
            storage_location_id = upload_destination["storageLocationId"]

        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(file_path, strict=False)

        file_handle = {
            "concreteType": concrete_types.S3_FILE_HANDLE,
            "key": s3_file_key,
            "bucketName": bucket_name,
            "fileName": os.path.basename(file_path),
            "contentMd5": md5 or utils.md5_for_file(file_path).hexdigest(),
            "contentSize": os.stat(file_path).st_size,
            "storageLocationId": storage_location_id,
            "contentType": mimetype,
        }

        return self.restPOST(
            "/externalFileHandle/s3",
            json.dumps(file_handle),
            endpoint=self.fileHandleEndpoint,
        )

    def _get_file_handle_as_creator(
        self, fileHandle: Dict[str, Union[str, int]]
    ) -> Dict[str, Union[str, int]]:
        """
        Retrieve a fileHandle from the fileHandle service.
        Note: You must be the creator of the filehandle to use this method. Otherwise, an 403-Forbidden error will be raised.

        Arguments:
            fileHandle: A fileHandle

        Returns:
            A fileHandle retrieved from the fileHandle service.
        """
        uri = "/fileHandle/%s" % (id_of(fileHandle),)
        return self.restGET(uri, endpoint=self.fileHandleEndpoint)

    def _deleteFileHandle(self, fileHandle: Dict[str, Union[str, int]]) -> None:
        """
        Delete the given file handle.

        Note: Only the user that created the FileHandle can delete it. Also, a FileHandle cannot be deleted if it is
        associated with a FileEntity or WikiPage.

        Arguments:
            fileHandle: A fileHandle
        """
        uri = "/fileHandle/%s" % (id_of(fileHandle),)
        self.restDELETE(uri, endpoint=self.fileHandleEndpoint)
        return fileHandle

    ############################################################
    #                    SFTP                                  #
    ############################################################

    def _getDefaultUploadDestination(self, parent_entity):
        return self.restGET(
            "/entity/%s/uploadDestination" % id_of(parent_entity),
            endpoint=self.fileHandleEndpoint,
        )

    def _getUserCredentials(
        self, url: str, username: str = None, password: str = None
    ) -> Tuple[str, str]:
        """
        Get user credentials for a specified URL by either looking in the configFile or querying the user.

        Arguments:
            username: The username on server (optionally specified).
            password: The password for authentication on the server (optionally specified).

        Returns:
            A tuple of username, password.
        """
        # Get authentication information from configFile
        parsedURL = urllib_urlparse.urlparse(url)
        baseURL = parsedURL.scheme + "://" + parsedURL.hostname

        config = get_config_file(self.configPath)
        if username is None and config.has_option(baseURL, "username"):
            username = config.get(baseURL, "username")
        if password is None and config.has_option(baseURL, "password"):
            password = config.get(baseURL, "password")
        # If I still don't have a username and password prompt for it
        if username is None:
            username = getpass.getuser()  # Default to login name
            # Note that if we hit the following line from within nosetests in
            # Python 3, we get "TypeError: bad argument type for built-in operation".
            # Luckily, this case isn't covered in our test suite!
            user = input("Username for %s (%s):" % (baseURL, username))
            username = username if user == "" else user
        if password is None:
            password = getpass.getpass("Password for %s:" % baseURL)
        return username, password

    ############################################
    # Project/Folder storage location settings #
    ############################################

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `StorageLocation(...).store()` from synapseclient.models instead.",
    )
    def createStorageLocationSetting(self, storage_type, **kwargs):
        """
        Creates an IMMUTABLE storage location based on the specified type.

        For each storage_type, the following kwargs should be specified:

        **ExternalObjectStorage**: (S3-like (e.g. AWS S3 or Openstack) bucket not accessed by Synapse)

        - `endpointUrl`: endpoint URL of the S3 service (for example: 'https://s3.amazonaws.com')
        - `bucket`: the name of the bucket to use

        **ExternalS3Storage**: (Amazon S3 bucket accessed by Synapse)

        - `bucket`: the name of the bucket to use

        **ExternalStorage**: (SFTP or FTP storage location not accessed by Synapse)

        - `url`: the base URL for uploading to the external destination
        - `supportsSubfolders(optional)`: does the destination support creating subfolders under the base url
            (default: false)

        **ProxyStorage**: (a proxy server that controls access to a storage)

        - `secretKey`: The encryption key used to sign all pre-signed URLs used to communicate with the proxy.
        - `proxyUrl`: The HTTPS URL of the proxy used for upload and download.

        Arguments:
            storage_type: The type of the StorageLocationSetting to create
            banner: (Optional) The optional banner to show every time a file is uploaded
            description: (Optional) The description to show the user when the user has to choose which upload destination to use
            kwargs: fields necessary for creation of the specified storage_type

        Returns:
            A dict of the created StorageLocationSetting
        """
        upload_type_dict = {
            "ExternalObjectStorage": "S3",
            "ExternalS3Storage": "S3",
            "ExternalStorage": "SFTP",
            "ProxyStorage": "PROXYLOCAL",
        }

        if storage_type not in upload_type_dict:
            raise ValueError("Unknown storage_type: %s", storage_type)

        # ProxyStorageLocationSettings has an extra 's' at the end >:(
        kwargs["concreteType"] = (
            "org.sagebionetworks.repo.model.project."
            + storage_type
            + "LocationSetting"
            + ("s" if storage_type == "ProxyStorage" else "")
        )
        kwargs["uploadType"] = upload_type_dict[storage_type]

        return self.restPOST("/storageLocation", body=json.dumps(kwargs))

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `StorageLocation(storage_location_id=id).get()` from "
        "synapseclient.models instead.",
    )
    def getMyStorageLocationSetting(self, storage_location_id):
        """
        Get a StorageLocationSetting by its id.

        Arguments:
            storage_location_id: id of the StorageLocationSetting to retrieve.
                                    The corresponding StorageLocationSetting must have been created by this user.

        Returns:
            A dict describing the StorageLocationSetting retrieved by its id
        """
        return self.restGET("/storageLocation/%s" % storage_location_id)

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `Folder(id=...).set_storage_location(...)` or "
        "`Project(id=...).set_storage_location(...)` from synapseclient.models instead.",
    )
    def setStorageLocation(self, entity, storage_location_id):
        """
        Sets the storage location for a Project or Folder

        Arguments:
            entity: A Project or Folder to which the StorageLocationSetting is set
            storage_location_id: A StorageLocation id or a list of StorageLocation ids. Pass in None for the default
                                    Synapse storage.

        Returns:
            The created or updated settings as a dict.
        """
        if storage_location_id is None:
            storage_location_id = DEFAULT_STORAGE_LOCATION_ID
        locations = (
            storage_location_id
            if isinstance(storage_location_id, list)
            else [storage_location_id]
        )

        existing_setting = self.getProjectSetting(entity, "upload")
        if existing_setting is not None:
            existing_setting["locations"] = locations
            self.restPUT("/projectSettings", body=json.dumps(existing_setting))
            return self.getProjectSetting(entity, "upload")
        else:
            project_destination = {
                "concreteType": "org.sagebionetworks.repo.model.project.UploadDestinationListSetting",
                "settingsType": "upload",
                "locations": locations,
                "projectId": id_of(entity),
            }

            return self.restPOST(
                "/projectSettings", body=json.dumps(project_destination)
            )

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `Folder(id=...).get_project_setting(...)` or "
        "`Project(id=...).get_project_setting(...)` from synapseclient.models instead.",
    )
    def getProjectSetting(self, project, setting_type):
        """
        Gets the ProjectSetting for a project.

        Arguments:
            project: Project entity or its id as a string
            setting_type: Type of setting. Choose from:

                - `upload`
                - `external_sync`
                - `requester_pays`

        Returns:
            The ProjectSetting as a dict or None if no settings of the specified type exist.
        """
        if setting_type not in {"upload", "external_sync", "requester_pays"}:
            raise ValueError("Invalid project_type: %s" % setting_type)

        response = self.restGET(
            "/projectSettings/{projectId}/type/{type}".format(
                projectId=id_of(project), type=setting_type
            )
        )
        return (
            response if response else None
        )  # if no project setting, a empty string is returned as the response

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use `Folder(id=...).get_sts_storage_token(...)` or "
        "`Project(id=...).get_sts_storage_token(...)` from synapseclient.models instead.",
    )
    def get_sts_storage_token(
        self, entity, permission, *, output_format="json", min_remaining_life=None
    ):
        """Get STS credentials for the given entity_id and permission, outputting it in the given format

        Arguments:
            entity: The entity or entity id whose credentials are being returned
            permission: One of:

                - `read_only`
                - `read_write`

            output_format: One of:

                - `json`: the dictionary returned from the Synapse STS API including expiration
                - `boto`: a dictionary compatible with a boto session (aws_access_key_id, etc)
                - `shell`: output commands for exporting credentials appropriate for the detected shell
                - `bash`: output commands for exporting credentials into a bash shell
                - `cmd`: output commands for exporting credentials into a windows cmd shell
                - `powershell`: output commands for exporting credentials into a windows powershell

            min_remaining_life: The minimum allowable remaining life on a cached token to return. If a cached token
                                has left than this amount of time left a fresh token will be fetched
        """
        return sts_transfer.get_sts_credentials(
            self,
            id_of(entity),
            permission,
            output_format=output_format,
            min_remaining_life=min_remaining_life,
        )

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.StorageLocation` model and its `store()` "
        "method instead. To also create a folder and apply the storage location "
        "as a project setting, use `Folder` together with "
        "`set_storage_location()` on the project/folder.",
    )
    def create_s3_storage_location(
        self,
        *,
        parent=None,
        folder_name=None,
        folder=None,
        bucket_name=None,
        base_key=None,
        sts_enabled=False,
    ) -> Tuple[Folder, Dict[str, str], Dict[str, str]]:
        """
        Create a storage location in the given parent, either in the given folder or by creating a new
        folder in that parent with the given name. This will both create a StorageLocationSetting,
        and a ProjectSetting together, optionally creating a new folder in which to locate it,
        and optionally enabling this storage location for access via STS. If enabling an existing folder for STS,
        it must be empty.

        Deprecated: To be removed in 5.0.0. Use the synapseclient.models.StorageLocation
        model and its store() method to create the storage location, and
        set_storage_location() on a Project or Folder to apply it as a project setting.

        Arguments:
            parent: The parent in which to locate the storage location (mutually exclusive with folder)
            folder_name: The name of a new folder to create (mutually exclusive with folder)
            folder: The existing folder in which to create the storage location (mutually exclusive with folder_name)
            bucket_name: The name of an S3 bucket, if this is an external storage location,
                            if None will use Synapse S3 storage
            base_key: The base key of within the bucket, None to use the bucket root,
                            only applicable if bucket_name is passed
            sts_enabled: Whether this storage location should be STS enabled

        Returns:
            A 3-tuple of the synapse Folder, a the storage location setting, and the project setting dictionaries.

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # folder, storage_setting, project_setting = syn.create_s3_storage_location(
            #     parent="syn123",
            #     folder_name="my-external-storage",
            #     bucket_name="my-bucket",
            # )

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Folder, StorageLocation, StorageLocationType

            syn = Synapse()
            syn.login()

            # Create the storage location backed by your own S3 bucket
            storage = StorageLocation(
                storage_type=StorageLocationType.EXTERNAL_S3,
                bucket="my-bucket",
            ).store()

            # Create a folder to hold the externally stored files
            folder = Folder(name="my-external-storage", parent_id="syn123").store()

            # Apply the storage location as the folder's upload destination
            folder.set_storage_location(storage_location_id=storage.storage_location_id)
            ```
        """
        return wrap_async_to_sync(
            self.create_s3_storage_location_async(
                parent=parent,
                folder_name=folder_name,
                folder=folder,
                bucket_name=bucket_name,
                base_key=base_key,
                sts_enabled=sts_enabled,
            )
        )

    @deprecated(
        version="4.12.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.StorageLocation` model and its "
        "`store_async()` method instead. To also create a folder and apply the "
        "storage location as a project setting, use `Folder` together with "
        "`set_storage_location_async()` on the project/folder.",
    )
    async def create_s3_storage_location_async(
        self,
        *,
        parent=None,
        folder_name=None,
        folder=None,
        bucket_name=None,
        base_key=None,
        sts_enabled=False,
    ) -> Tuple[Folder, Dict[str, str], Dict[str, str]]:
        """
        async version of create_s3_storage_location

        Deprecated: To be removed in 5.0.0. Use the synapseclient.models.StorageLocation
        model and its store_async() method to create the storage location, and
        set_storage_location_async() on a Project or Folder to apply it as a project
        setting.
        """
        if folder_name and parent:
            if folder:
                raise ValueError(
                    "folder and  folder_name are mutually exclusive, only one should be passed"
                )

            folder = await self.store_async(Folder(name=folder_name, parent=parent))

        elif not folder:
            raise ValueError("either folder or folder_name should be required")

        storage_location_kwargs = {
            "uploadType": "S3",
            "stsEnabled": sts_enabled,
        }

        if bucket_name:
            storage_location_kwargs["concreteType"] = (
                concrete_types.EXTERNAL_S3_STORAGE_LOCATION_SETTING
            )
            storage_location_kwargs["bucket"] = bucket_name
            if base_key:
                storage_location_kwargs["baseKey"] = base_key
        else:
            storage_location_kwargs["concreteType"] = (
                concrete_types.SYNAPSE_S3_STORAGE_LOCATION_SETTING
            )

        storage_location_setting = self.restPOST(
            "/storageLocation", json.dumps(storage_location_kwargs)
        )

        storage_location_id = storage_location_setting["storageLocationId"]
        project_setting = self.setStorageLocation(
            folder,
            storage_location_id,
        )

        return folder, storage_location_setting, project_setting

    ############################################################
    #                   CRUD for Evaluations                   #
    ############################################################

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Evaluation` model instead, e.g. "
        "`Evaluation(id=...).get()`.",
    )
    def getEvaluation(self, id):
        """
        Gets an Evaluation object from Synapse.

        Arguments:
            id: The ID of the [synapseclient.evaluation.Evaluation][] to return.

        Returns:
            An [synapseclient.evaluation.Evaluation][] object

        Example: Using this function
            Creating an Evaluation instance

                evaluation = syn.getEvaluation(2005090)

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # evaluation = syn.getEvaluation(2005090)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Evaluation

            syn = Synapse()
            syn.login()

            evaluation = Evaluation(id="2005090").get()
            ```
        """

        evaluation_id = id_of(id)
        uri = Evaluation.getURI(evaluation_id)
        return Evaluation(**self.restGET(uri))

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Evaluation` model instead, e.g. "
        "`Evaluation(name=...).get()`.",
    )
    def getEvaluationByName(self, name):
        """
        Gets an Evaluation object from Synapse.

        Arguments:
            Name: The name of the [synapseclient.evaluation.Evaluation][] to return.

        Returns:
            An [synapseclient.evaluation.Evaluation][] object

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # evaluation = syn.getEvaluationByName("My Evaluation")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Evaluation

            syn = Synapse()
            syn.login()

            evaluation = Evaluation(name="My Evaluation").get()
            ```
        """
        uri = Evaluation.getByNameURI(name)
        return Evaluation(**self.restGET(uri))

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.models.Evaluation.get_evaluations_by_project()` instead.",
    )
    def getEvaluationByContentSource(self, entity):
        """
        Returns a generator over evaluations that derive their content from the given entity

        Arguments:
            entity: The [synapseclient.entity.Project][] whose Evaluations are to be fetched.

        Yields:
            A generator over [synapseclient.evaluation.Evaluation][] objects for the given [synapseclient.entity.Project][].

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # evaluations = syn.getEvaluationByContentSource("syn123")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Evaluation

            syn = Synapse()
            syn.login()

            evaluations = Evaluation.get_evaluations_by_project(project_id="syn123")
            ```
        """

        entityId = id_of(entity)
        url = "/entity/%s/evaluation" % entityId

        for result in self._GET_paginated(url):
            yield Evaluation(**result)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _findTeam(self, name: str) -> typing.Iterator[Team]:
        """
        Retrieve a Teams matching the supplied name fragment

        Arguments:
            name: A team name

        Yields:
            A generator that yields objects of type [Team][synapseclient.team.Team]
        """
        for result in self._GET_paginated("/teams?fragment=%s" % name):
            yield Team(**result)

    def _find_teams_for_principal(self, principal_id: str) -> typing.Iterator[Team]:
        """
        Retrieve a list of teams for the matching principal ID. If the principalId that is passed in is a team itself,
        or not found, this will return a generator that yields no results.

        Arguments:
            principal_id: Identifier of a user or group.

        Yields:
            A generator that yields objects of type [Team][synapseclient.team.Team]
        """
        for result in self._GET_paginated(f"/user/{principal_id}/team"):
            yield Team(**result)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `create` method on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def create_team(
        self,
        name: str,
        description: str = None,
        icon: str = None,
        can_public_join: bool = False,
        can_request_membership: bool = True,
    ) -> Team:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.create][] instead.

        Creates a new team.

        Arguments:
            name: The name of the team to create.
            description: A description of the team.
            icon: The FileHandleID of the icon to be used for the team.
            canPublicJoin: Whether the team can be joined by anyone. Defaults to False.
            canRequestMembership: Whether the team can request membership. Defaults to True.

        Returns:
            An object of type [synapseclient.team.Team][]

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Create a new team
            new_team = Team(
                name="My Team",
                description="A sample team",
                can_public_join=False,
                can_request_membership=True
            )
            created_team = new_team.create()
            print(f"Created team: {created_team.name}")
            ```
        """
        request_body = {
            "name": name,
            "description": description,
            "icon": icon,
            "canPublicJoin": can_public_join,
            "canRequestMembership": can_request_membership,
        }
        return Team(
            **self.restPOST(
                "/team",
                json.dumps(request_body),
            )
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `delete` method on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def delete_team(self, id: int) -> None:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.delete][] instead.

        Deletes a team.

        Arguments:
            id: The ID of the team to delete.

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Delete a team
            team = Team(id=12345)
            team.delete()
            ```

        """
        return self.restDELETE(f"/team/{id}")

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `get`, `from_id`, and `from_name` methods on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def getTeam(self, id: Union[int, str]) -> Team:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.from_id][] or [synapseclient.models.Team.from_name][] instead.

        Finds a team with a given ID or name.

        Arguments:
            id: The ID or name of the team or a Team object to retrieve.

        Returns:
            An object of type [synapseclient.team.Team][]

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get a team by ID
            team_by_id = Team.from_id(id=12345)
            print(f"Team by ID: {team_by_id.name}")

            # Get a team by name
            team_by_name = Team.from_name(name="My Team")
            print(f"Team by name: {team_by_name.name}")
            ```
        """
        # Retrieves team id
        teamid = id_of(id)
        try:
            int(teamid)
        except (TypeError, ValueError):
            if isinstance(id, str):
                for team in self._findTeam(id):
                    if team.name == id:
                        teamid = team.id
                        break
                else:
                    raise ValueError('Can\'t find team "{}"'.format(teamid))
            else:
                raise ValueError('Can\'t find team "{}"'.format(teamid))
        return Team(**self.restGET("/team/%s" % teamid))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `members` method on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def getTeamMembers(
        self, team: Union[Team, int, str]
    ) -> typing.Generator[TeamMember, None, None]:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.members][] instead.

        Lists the members of the given team.

        Arguments:
            team: A [synapseclient.team.Team][] object or a team's ID.

        Yields:
            A generator over [synapseclient.team.TeamMember][] objects.

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get team members
            team = Team.from_id(id=12345)
            members = team.members()
            for member in members:
                print(f"Member: {member.member.user_name}")
            ```

        """
        for result in self._GET_paginated("/teamMembers/{id}".format(id=id_of(team))):
            yield TeamMember(**result)

    def _get_docker_digest(
        self, entity: Union[Entity, str], docker_tag: str = "latest"
    ) -> str:
        """
        Get matching Docker sha-digest of a DockerRepository given a Docker tag

        Arguments:
            entity:      Synapse ID or Entity of Docker repository
            docker_tag:  Docker tag

        Returns:
            Docker digest matching Docker tag
        """
        entityid = id_of(entity)
        uri = "/entity/{entityId}/dockerTag".format(entityId=entityid)

        docker_commits = self._GET_paginated(uri)
        docker_digest = None
        for commit in docker_commits:
            if docker_tag == commit["tag"]:
                docker_digest = commit["digest"]
        if docker_digest is None:
            raise ValueError(
                "Docker tag {docker_tag} not found.  Please specify a "
                "docker tag that exists. 'latest' is used as "
                "default.".format(docker_tag=docker_tag)
            )
        return docker_digest

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `open_invitations` method on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def get_team_open_invitations(
        self, team: Union[Team, int, str]
    ) -> typing.Generator[dict, None, None]:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.open_invitations][] instead.

        Retrieve the open requests submitted to a Team
        <https://rest-docs.synapse.org/rest/GET/team/id/openInvitation.html>

        Arguments:
            team: A [synapseclient.team.Team][] object or a team's ID.

        Yields:
            Generator of MembershipRequest dictionaries

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get open invitations for a team
            team = Team.from_id(id=12345)
            invitations = team.open_invitations()
            for invitation in invitations:
                print(f"Invitation: {invitation}")
            ```
        """
        teamid = id_of(team)
        request = "/team/{team}/openInvitation".format(team=teamid)
        open_requests = self._GET_paginated(request)
        return open_requests

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `get_user_membership_status` method on the `Team` class from `synapseclient.models` instead. "
        "Check the docstring for the replacement function example.",
    )
    def get_membership_status(self, userid, team):
        """Retrieve a user's Team Membership Status bundle.
        <https://rest-docs.synapse.org/rest/GET/team/id/member/principalId/membershipStatus.html>

        Arguments:
            user: Synapse user ID
            team: A [synapseclient.team.Team][] object or a team's ID.

        Returns:
            dict of TeamMembershipStatus

        Example: Using this function (DEPRECATED)
            &nbsp;
            Getting a user's membership status for a team

            ```python
            from synapseclient import Synapse

            # Login to Synapse
            syn = Synapse()
            syn.login()

            status = syn.get_membership_status(userid="12345", team="67890")
            print(status)
            ```


        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Use synchronous version (recommended for most use cases)
            team = Team.from_id(id="67890")
            status = team.get_user_membership_status(
                user_id="12345",
            )
            print(status)
            ```
        """
        teamid = id_of(team)
        request = "/team/{team}/member/{user}/membershipStatus".format(
            team=teamid, user=userid
        )
        membership_status = self.restGET(request)
        return membership_status

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _delete_membership_invitation(self, invitationid: str) -> None:
        """
        Delete an invitation Note: The client must be an administrator of the
        Team referenced by the invitation or the invitee to make this request.

        Arguments:
            invitationid: Open invitation id
        """
        self.restDELETE("/membershipInvitation/{id}".format(id=invitationid))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to synapseclient.api.team_services.send_membership_invitation. "
        "Check the docstring for the replacement function example.",
    )
    def send_membership_invitation(
        self, teamId, inviteeId=None, inviteeEmail=None, message=None
    ):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.api.team_services.send_membership_invitation][] instead.

        Create a membership invitation and send an email notification
        to the invitee.

        Arguments:
            teamId: Synapse teamId
            inviteeId: Synapse username or profile id of user
            inviteeEmail: Email of user
            message: Additional message for the user getting invited to the
                     team.

        Returns:
            MembershipInvitation

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.api.team_services import send_membership_invitation

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Send invitation by user ID
            invitation = asyncio.run(send_membership_invitation(
                team_id=12345,
                invitee_id="username_or_user_id",
                message="Welcome to our team!"
            ))
            print(f"Invitation sent: {invitation}")

            # Send invitation by email
            invitation = asyncio.run(send_membership_invitation(
                team_id=12345,
                invitee_email="user@example.com",
                message="Join our team!"
            ))
            print(f"Invitation sent: {invitation}")
            ```
        """

        invite_request = {"teamId": str(teamId), "message": message}
        if inviteeEmail is not None:
            invite_request["inviteeEmail"] = str(inviteeEmail)
        if inviteeId is not None:
            invite_request["inviteeId"] = str(inviteeId)

        response = self.restPOST(
            "/membershipInvitation", body=json.dumps(invite_request)
        )
        return response

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `invite` method on the `from synapseclient.models import Team` class. "
        "Check the docstring for the replacement function example.",
    )
    def invite_to_team(
        self,
        team: Union[Team, int, str],
        user: str = None,
        inviteeEmail: str = None,
        message: str = None,
        force: bool = False,
    ):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use [synapseclient.models.Team.invite][] instead.

        Invite user to a Synapse team via Synapse username or email
        (choose one or the other)

        Arguments:
            syn: Synapse object
            team: A [synapseclient.team.Team][] object or a team's ID.
            user: Synapse username or profile id of user
            inviteeEmail: Email of user
            message: Additional message for the user getting invited to the team.
            force: If an open invitation exists for the invitee, the old invite will be cancelled.

        Returns:
            MembershipInvitation or None if user is already a member

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Team

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Invite a user to a team
            team = Team.from_id(id=12345)
            invitation = team.invite(
                user="username",
                message="Welcome to the team!",
                force=True
            )
            print(f"Invitation sent: {invitation}")
            ```
        """
        # Throw error if both user and email is specified and if both not
        # specified
        id_email_specified = inviteeEmail is not None and user is not None
        id_email_notspecified = inviteeEmail is None and user is None
        if id_email_specified or id_email_notspecified:
            raise ValueError("Must specify either 'user' or 'inviteeEmail'")

        teamid = id_of(team)
        is_member = False
        open_invitations = self.get_team_open_invitations(teamid)

        if user is not None:
            inviteeId = self.getUserProfile(user)["ownerId"]
            membership_status = self.get_membership_status(inviteeId, teamid)
            is_member = membership_status["isMember"]
            open_invites_to_user = [
                invitation
                for invitation in open_invitations
                if invitation.get("inviteeId") == inviteeId
            ]
        else:
            inviteeId = None
            open_invites_to_user = [
                invitation
                for invitation in open_invitations
                if invitation.get("inviteeEmail") == inviteeEmail
            ]
        # Only invite if the invitee is not a member and
        # if invitee doesn't have an open invitation unless force=True
        if not is_member and (not open_invites_to_user or force):
            # Delete all old invitations
            for invite in open_invites_to_user:
                self._delete_membership_invitation(invite["id"])
            return self.send_membership_invitation(
                teamid,
                inviteeId=inviteeId,
                inviteeEmail=inviteeEmail,
                message=message,
            )
        if is_member:
            not_sent_reason = "invitee is already a member"
        else:
            not_sent_reason = (
                "invitee already has an open invitation "
                "Set force=True to send new invite."
            )

        self.logger.warning("No invitation sent: {}".format(not_sent_reason))
        # Return None if no invite is sent.
        return None

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Submission` model instead, e.g. "
        "`Submission(...).store()`.",
    )
    def submit(
        self,
        evaluation,
        entity,
        name=None,
        team=None,
        silent=False,
        submitterAlias=None,
        teamName=None,
        dockerTag="latest",
    ):
        """
        Submit an Entity for [evaluation][synapseclient.evaluation.Evaluation].

        Arguments:
            evalation: Evaluation queue to submit to
            entity: The Entity containing the Submissions
            name: A name for this submission. In the absent of this parameter, the entity name will be used.
                    (Optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
            team: (optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
            silent: Set to True to suppress output.
            submitterAlias: (optional) A nickname, possibly for display in leaderboards in place of the submitter's name
            teamName: (deprecated) A synonym for submitterAlias
            dockerTag: (optional) The Docker tag must be specified if the entity is a DockerRepository.

        Returns:
            A [synapseclient.evaluation.Submission][] object


        In the case of challenges, a team can optionally be provided to give credit to members of the team that
        contributed to the submission. The team must be registered for the challenge with which the given evaluation is
        associated. The caller must be a member of the submitting team.

        Example: Using this function
            Getting and submitting an evaluation

                evaluation = syn.getEvaluation(123)
                entity = syn.get('syn456')
                submission = syn.submit(evaluation, entity, name='Our Final Answer', team='Blue Team')

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # submission = syn.submit(9614543, "syn456", name="Our Final Answer")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Submission

            syn = Synapse()
            syn.login()

            submission = Submission(
                evaluation_id="9614543",
                entity_id="syn456",
                name="Our Final Answer",
            ).store()
            ```
        """
        return wrap_async_to_sync(
            self.submit_async(
                evaluation,
                entity,
                name=name,
                team=team,
                silent=silent,
                submitterAlias=submitterAlias,
                teamName=teamName,
                dockerTag=dockerTag,
            )
        )

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Submission` model instead, e.g. "
        "`await Submission(...).store_async()`.",
    )
    async def submit_async(
        self,
        evaluation,
        entity,
        name=None,
        team=None,
        silent=False,
        submitterAlias=None,
        teamName=None,
        dockerTag="latest",
    ):
        """
        Submit an Entity for [evaluation][synapseclient.evaluation.Evaluation].

        Arguments:
            evalation: Evaluation queue to submit to
            entity: The Entity containing the Submissions
            name: A name for this submission. In the absent of this parameter, the entity name will be used.
                    (Optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
            team: (optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
            silent: Set to True to suppress output.
            submitterAlias: (optional) A nickname, possibly for display in leaderboards in place of the submitter's name
            teamName: (deprecated) A synonym for submitterAlias
            dockerTag: (optional) The Docker tag must be specified if the entity is a DockerRepository.

        Returns:
            A [synapseclient.evaluation.Submission][] object


        In the case of challenges, a team can optionally be provided to give credit to members of the team that
        contributed to the submission. The team must be registered for the challenge with which the given evaluation is
        associated. The caller must be a member of the submitting team.

        Example: Using this function
            Getting and submitting an evaluation

                evaluation = syn.getEvaluation(123)
                entity = syn.get('syn456')
                submission = syn.submit(evaluation, entity, name='Our Final Answer', team='Blue Team')

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # submission = await syn.submit_async(9614543, "syn456", name="Our Final Answer")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Submission

            syn = Synapse()
            syn.login()

            submission = await Submission(
                evaluation_id="9614543",
                entity_id="syn456",
                name="Our Final Answer",
            ).store_async()
            ```
        """

        require_param(evaluation, "evaluation")
        require_param(entity, "entity")

        evaluation_id = id_of(evaluation)

        entity_id = id_of(entity)
        if isinstance(entity, synapseclient.DockerRepository):
            # Edge case if dockerTag is specified as None
            if dockerTag is None:
                raise ValueError(
                    "A dockerTag is required to submit a DockerEntity. Cannot be None"
                )
            docker_repository = entity["repositoryName"]
        else:
            docker_repository = None

        # Some hacks to make sure that new OOP models will also work with this interface
        entity_is_dataclass = is_dataclass(entity)
        if entity_is_dataclass:
            if not entity.version_number:
                if hasattr(entity, "download_file"):
                    entity.download_file = False
                entity.get(synapse_client=self)
            entity_version = entity.version_number
        else:
            if "versionNumber" not in entity:
                entity = await self.get_async(entity, downloadFile=False)
            # version defaults to 1 to hack around required version field and allow submission of files/folders
            entity_version = entity.get("versionNumber", 1)

        # default name of submission to name of entity
        if name is None:
            if entity_is_dataclass:
                name = entity.name
            elif "name" in entity:
                name = entity["name"]

        team_id = None
        if team:
            team = self.getTeam(team)
            team_id = id_of(team)

        contributors, eligibility_hash = self._get_contributors(evaluation_id, team)

        # for backward compatible until we remove supports for teamName
        if not submitterAlias:
            if teamName:
                submitterAlias = teamName
            elif team and "name" in team:
                submitterAlias = team["name"]

        if isinstance(entity, synapseclient.DockerRepository):
            docker_digest = self._get_docker_digest(entity, dockerTag)
        else:
            docker_digest = None

        submission = {
            "evaluationId": evaluation_id,
            "name": name,
            "entityId": entity_id,
            "versionNumber": entity_version,
            "dockerDigest": docker_digest,
            "dockerRepositoryName": docker_repository,
            "teamId": team_id,
            "contributors": contributors,
            "submitterAlias": submitterAlias,
        }

        if entity_is_dataclass:
            entity_etag = entity.etag
        else:
            entity_etag = entity["etag"]
        submitted = self._submit(submission, entity_etag, eligibility_hash)

        # if we want to display the receipt message, we need the full object
        if not silent:
            if not (isinstance(evaluation, Evaluation)):
                evaluation = self.getEvaluation(evaluation_id)
            if "submissionReceiptMessage" in evaluation:
                self.logger.info(evaluation["submissionReceiptMessage"])

        return Submission(**submitted)

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1590
    def _submit(self, submission, entity_etag, eligibility_hash):
        require_param(submission, "submission")
        require_param(entity_etag, "entity_etag")
        # URI requires the etag of the entity and, in the case of a team submission, requires an eligibilityStateHash
        uri = "/evaluation/submission?etag=%s" % entity_etag
        if eligibility_hash:
            uri += "&submissionEligibilityHash={0}".format(eligibility_hash)
        submitted = self.restPOST(uri, json.dumps(submission))
        return submitted

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1590
    def _get_contributors(self, evaluation_id, team):
        if not evaluation_id or not team:
            return None, None

        team_id = id_of(team)
        # see <https://rest-docs.synapse.org/rest/GET/evaluation/evalId/team/id/submissionEligibility.html>
        eligibility = self.restGET(
            "/evaluation/{evalId}/team/{id}/submissionEligibility".format(
                evalId=evaluation_id, id=team_id
            )
        )

        if not eligibility["teamEligibility"]["isEligible"]:
            # Check team eligibility and raise an exception if not eligible
            if not eligibility["teamEligibility"]["isRegistered"]:
                raise SynapseError(
                    'Team "{team}" is not registered.'.format(team=team.name)
                )
            if eligibility["teamEligibility"]["isQuotaFilled"]:
                raise SynapseError(
                    'Team "{team}" has already submitted the full quota of submissions.'.format(
                        team=team.name
                    )
                )
            raise SynapseError('Team "{team}" is not eligible.'.format(team=team.name))

        # Include all team members who are eligible.
        contributors = [
            {"principalId": member["principalId"]}
            for member in eligibility["membersEligibility"]
            if member["isEligible"] and not member["hasConflictingSubmission"]
        ]
        return contributors, eligibility["eligibilityStateHash"]

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1590
    def _allowParticipation(
        self,
        evaluation: Union[Evaluation, str],
        user: str,
        rights: list = ["READ", "PARTICIPATE", "SUBMIT", "UPDATE_SUBMISSION"],
    ) -> Dict[str, Union[str, list]]:
        """
        Grants the given user the minimal access rights to join and submit to an Evaluation.
        Note: The specification of this method has not been decided yet, so the method is likely to change in future.

        Arguments:
            evaluation: An Evaluation object or Evaluation ID
            user:       Either a user group or the principal ID of a user to grant rights to.

                - To allow all users, use "PUBLIC".
                - To allow authenticated users, use "AUTHENTICATED_USERS".

            rights:     The access rights to give to the users.

                - `READ`
                - `PARTICIPATE`
                - `SUBMIT`
                - `UPDATE_SUBMISSION`

        Raises:
            SynapseError: If the user does not exist

        Returns:
            The new or updated ACL
        """
        # Check to see if the user is an ID or group
        userId = -1
        try:
            # TODO: is there a better way to differentiate between a userID and a group name?
            # What if a group is named with just numbers?
            userId = int(user)

            # Verify that the user exists
            try:
                self.getUserProfile(userId)
            except SynapseHTTPError as err:
                if err.response.status_code == 404:
                    raise SynapseError("The user (%s) does not exist" % str(userId))
                raise

        except ValueError:
            # Fetch the ID of the user group
            userId = self._getUserbyPrincipalIdOrName(user)

        if not isinstance(evaluation, Evaluation):
            evaluation = self.getEvaluation(id_of(evaluation))

        self.setPermissions(evaluation, userId, accessType=rights, overwrite=False)

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.models.Submission.get_evaluation_submissions()` (or "
        "`get_user_submissions()` for your own submissions) instead.",
    )
    def getSubmissions(self, evaluation, status=None, myOwn=False, limit=20, offset=0):
        """
        Arguments:
            evaluation: Evaluation to get submissions from.
            status: Optionally filter submissions for a specific status.
                    One of:

                - `OPEN`
                - `CLOSED`
                - `SCORED`
                - `INVALID`
                - `VALIDATED`
                - `EVALUATION_IN_PROGRESS`
                - `RECEIVED`
                - `REJECTED`
                - `ACCEPTED`

            myOwn: Determines if only your Submissions should be fetched.
                     Defaults to False (all Submissions)
            limit: Limits the number of submissions in a single response.
                        Because this method returns a generator and repeatedly
                        fetches submissions, this argument is limiting the
                        size of a single request and NOT the number of sub-
                        missions returned in total.
            offset: Start iterating at a submission offset from the first submission.

        Yields:
            A generator over [synapseclient.evaluation.Submission][] objects for an Evaluation

        Example: Using this function
            Print submissions

                for submission in syn.getSubmissions(1234567):
                    print(submission['entityId'])

        See:

        - [synapseclient.evaluation][]

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # for submission in syn.getSubmissions(1234567):
            #     print(submission)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Submission

            syn = Synapse()
            syn.login()

            # All submissions for an evaluation
            for submission in Submission.get_evaluation_submissions(evaluation_id="1234567"):
                print(submission)

            # Only your own submissions (equivalent to myOwn=True)
            for submission in Submission.get_user_submissions(evaluation_id="1234567"):
                print(submission)
            ```
        """

        evaluation_id = id_of(evaluation)
        uri = "/evaluation/%s/submission%s" % (evaluation_id, "" if myOwn else "/all")

        if status is not None:
            uri += "?status=%s" % status

        for result in self._GET_paginated(uri, limit=limit, offset=offset):
            yield Submission(**result)

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1590
    def _getSubmissionBundles(
        self,
        evaluation: Union[Evaluation, str],
        status: str = None,
        myOwn: bool = False,
        limit: int = 20,
        offset: int = 0,
    ) -> typing.Iterator[Dict[str, Union[Submission, dict]]]:
        """
        Gets the requesting user's bundled Submissions and SubmissionStatuses to a specified Evaluation.

        Arguments:
            evaluation: Evaluation to get submissions from.
            status:     Optionally filter submissions for a specific status.
                        One of {OPEN, CLOSED, SCORED, INVALID}
            myOwn:      Determines if only your Submissions should be fetched.
                        Defaults to False (all Submissions)
            limit:      Limits the number of submissions coming back from the
                        service in a single response.
            offset:     Start iterating at a submission offset from the first
                        submission.

        Returns:
            A generator over dictionaries with keys 'submission' and 'submissionStatus'.

        Example:

            for sb in syn._getSubmissionBundles(1234567):
                print(sb['submission']['name'],
                      sb['submission']['submitterAlias'],
                      sb['submissionStatus']['status'],
                      sb['submissionStatus']['score'])

        This may later be changed to return objects, pending some thought on how submissions along with related status
        and annotations should be represented in the clients.

        See: [synapseclient.evaluation][]
        """

        evaluation_id = id_of(evaluation)
        url = "/evaluation/%s/submission/bundle%s" % (
            evaluation_id,
            "" if myOwn else "/all",
        )
        if status is not None:
            url += "?status=%s" % status

        return self._GET_paginated(url, limit=limit, offset=offset)

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.models.SubmissionBundle.get_evaluation_submission_bundles()` "
        "(or `get_user_submission_bundles()` for your own) instead.",
    )
    def getSubmissionBundles(
        self, evaluation, status=None, myOwn=False, limit=20, offset=0
    ):
        """
        Retrieve submission bundles (submission and submissions status) for an evaluation queue, optionally filtered by
        submission status and/or owner.

        Arguments:
            evaluation: Evaluation to get submissions from.
            status:     Optionally filter submissions for a specific status.
                        One of:

                - `OPEN`
                - `CLOSED`
                - `SCORED`
                - `INVALID`

            myOwn:      Determines if only your Submissions should be fetched.
                        Defaults to False (all Submissions)
            limit:      Limits the number of submissions coming back from the
                        service in a single response.
            offset:     Start iterating at a submission offset from the first submission.

        Yields:
            A generator over tuples containing a [synapseclient.evaluation.Submission][] and a [synapseclient.evaluation.SubmissionStatus][].

        Example: Using this function
            Loop over submissions

                for submission, status in syn.getSubmissionBundles(evaluation):
                    print(submission.name,
                          submission.submitterAlias,
                          status.status,
                          status.score)

        This may later be changed to return objects, pending some thought on how submissions along with related status
        and annotations should be represented in the clients.

        See:
        - [synapseclient.evaluation][]

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # for submission, status in syn.getSubmissionBundles(1234567):
            #     print(submission, status)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import SubmissionBundle

            syn = Synapse()
            syn.login()

            # All submission bundles for an evaluation
            for bundle in SubmissionBundle.get_evaluation_submission_bundles(evaluation_id="1234567"):
                print(bundle.submission, bundle.submission_status)

            # Only your own submission bundles (equivalent to myOwn=True)
            for bundle in SubmissionBundle.get_user_submission_bundles(evaluation_id="1234567"):
                print(bundle.submission, bundle.submission_status)
            ```
        """
        for bundle in self._getSubmissionBundles(
            evaluation, status=status, myOwn=myOwn, limit=limit, offset=offset
        ):
            yield (
                Submission(**bundle["submission"]),
                SubmissionStatus(**bundle["submissionStatus"]),
            )

    def _GET_paginated(self, uri: str, limit: int = 20, offset: int = 0):
        """
        Get paginated results

        Arguments:
            uri:     A URI that returns paginated results
            limit:   How many records should be returned per request
            offset:  At what record offset from the first should iteration start

        Returns:
            A generator over some paginated results

        The limit parameter is set at 20 by default. Using a larger limit results in fewer calls to the service, but if
        responses are large enough to be a burden on the service they may be truncated.
        """
        prev_num_results = sys.maxsize
        while prev_num_results > 0:
            uri = utils._limit_and_offset(uri, limit=limit, offset=offset)
            page = self.restGET(uri)
            results = page["results"] if "results" in page else page["children"]
            prev_num_results = len(results)

            for result in results:
                offset += 1
                yield result

    def _POST_paginated(self, uri: str, body, **kwargs):
        """
        Get paginated results

        Arguments:
            uri:     A URI that returns paginated results
            body:    POST request payload

        Returns:
            A generator over some paginated results
        """

        next_page_token = None
        while True:
            body["nextPageToken"] = next_page_token
            response = self.restPOST(uri, body=json.dumps(body), **kwargs)
            next_page_token = response.get("nextPageToken")
            for item in response["page"]:
                yield item
            if next_page_token is None:
                break

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Submission` model instead, e.g. "
        "`Submission(id=...).get()`.",
    )
    def getSubmission(
        self, id: typing.Union[str, int, collections.abc.Mapping], **kwargs
    ) -> Submission:
        """
        Gets a [synapseclient.evaluation.Submission][] object based on a given ID
        or previous [synapseclient.evaluation.Submission][] object.

        Arguments:
            id: The ID of the submission to retrieve or a [synapseclient.evaluation.Submission][] object

        Returns:
            A [synapseclient.evaluation.Submission][] object

        See:

        - [synapseclient.Synapse.get][] for information
             on the *downloadFile*, *downloadLocation*, and *ifcollision* parameters

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # submission = syn.getSubmission(9700123)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Submission

            syn = Synapse()
            syn.login()

            submission = Submission(id="9700123").get()
            ```
        """
        return wrap_async_to_sync(self.getSubmission_async(id=id, **kwargs))

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.Submission` model instead, e.g. "
        "`await Submission(id=...).get_async()`.",
    )
    async def getSubmission_async(
        self, id: typing.Union[str, int, collections.abc.Mapping], **kwargs
    ) -> Submission:
        """
        Gets a [synapseclient.evaluation.Submission][] object based on a given ID
        or previous [synapseclient.evaluation.Submission][] object.

        Arguments:
            id: The ID of the submission to retrieve or a [synapseclient.evaluation.Submission][] object

        Returns:
            A [synapseclient.evaluation.Submission][] object

        See:

        - [synapseclient.Synapse.get][] for information
             on the *downloadFile*, *downloadLocation*, and *ifcollision* parameters

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # submission = await syn.getSubmission_async(9700123)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import Submission

            syn = Synapse()
            syn.login()

            submission = await Submission(id="9700123").get_async()
            ```
        """

        submission_id = validate_submission_id(id)
        uri = Submission.getURI(submission_id)
        submission = Submission(**self.restGET(uri))

        # Pre-fetch the Entity tied to the Submission, if there is one
        if "entityId" in submission and submission["entityId"] is not None:
            entityBundleJSON = json.loads(submission["entityBundleJSON"])

            # getWithEntityBundle expects a bundle services v2 style
            # annotations dict, but the evaluations API may return
            # an older format annotations object in the encoded JSON
            # depending on when the original submission was made.
            annotations = entityBundleJSON.get("annotations")
            if annotations:
                entityBundleJSON["annotations"] = convert_old_annotation_json(
                    annotations
                )

            related = await self._getWithEntityBundle_async(
                entityBundle=entityBundleJSON,
                entity=submission["entityId"],
                submission=submission_id,
                **kwargs,
            )
            submission.entity = related
            submission.filePath = related.get("path", None)

        return submission

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.SubmissionStatus` model instead, e.g. "
        "`SubmissionStatus(id=...).get()`.",
    )
    def getSubmissionStatus(
        self, submission: typing.Union[str, int, collections.abc.Mapping]
    ) -> SubmissionStatus:
        """
        Downloads the status of a Submission given its ID or previous [synapseclient.evaluation.Submission][] object.

        Arguments:
            submission: The submission to lookup (ID or [synapseclient.evaluation.Submission][] object)

        Returns:
            A [synapseclient.evaluation.SubmissionStatus][] object

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # status = syn.getSubmissionStatus(9700123)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import SubmissionStatus

            syn = Synapse()
            syn.login()

            status = SubmissionStatus(id="9700123").get()
            ```
        """

        submission_id = validate_submission_id(submission)
        uri = SubmissionStatus.getURI(submission_id)
        val = self.restGET(uri)
        return SubmissionStatus(**val)

    ############################################################
    #                      CRUD for Wikis                      #
    ############################################################

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.WikiPage` model instead, e.g. "
        "`WikiPage(owner_id=..., id=...).get()`.",
    )
    def getWiki(self, owner, subpageId=None, version=None):
        """
        Get a [synapseclient.wiki.Wiki][] object from Synapse. Uses wiki2 API which supports versioning.

        Arguments:
            owner: The entity to which the Wiki is attached
            subpageId: The id of the specific sub-page or None to get the root Wiki page
            version: The version of the page to retrieve or None to retrieve the latest

        Returns:
            A [synapseclient.wiki.Wiki][] object

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # wiki = syn.getWiki("syn123", subpageId="456")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import WikiPage

            syn = Synapse()
            syn.login()

            wiki = WikiPage(owner_id="syn123", id="456").get()
            ```
        """
        return wrap_async_to_sync(
            self.getWiki_async(owner, subpageId=subpageId, version=version)
        )

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use the `synapseclient.models.WikiPage` model instead, e.g. "
        "`await WikiPage(owner_id=..., id=...).get_async()`.",
    )
    async def getWiki_async(self, owner, subpageId=None, version=None):
        """
        Get a [synapseclient.wiki.Wiki][] object from Synapse. Uses wiki2 API which supports versioning.

        Arguments:
            owner: The entity to which the Wiki is attached
            subpageId: The id of the specific sub-page or None to get the root Wiki page
            version: The version of the page to retrieve or None to retrieve the latest

        Returns:
            A [synapseclient.wiki.Wiki][] object

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # wiki = await syn.getWiki_async("syn123", subpageId="456")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import WikiPage

            syn = Synapse()
            syn.login()

            wiki = await WikiPage(owner_id="syn123", id="456").get_async()
            ```
        """
        uri = "/entity/{ownerId}/wiki2".format(ownerId=id_of(owner))
        if subpageId is not None:
            uri += "/{wikiId}".format(wikiId=subpageId)
        if version is not None:
            uri += "?wikiVersion={version}".format(version=version)

        wiki = self.restGET(uri)
        wiki["owner"] = owner
        wiki = Wiki(**wiki)

        path = self.cache.get(wiki.markdownFileHandleId)
        if not path:
            cache_dir = self.cache.get_cache_dir(wiki.markdownFileHandleId)
            if not os.path.exists(cache_dir):
                os.makedirs(cache_dir)
            path = await download_by_file_handle(
                file_handle_id=wiki["markdownFileHandleId"],
                synapse_id=wiki["id"],
                entity_type="WikiMarkdown",
                destination=os.path.join(
                    cache_dir, str(wiki.markdownFileHandleId) + ".md"
                ),
                synapse_client=self,
            )
        try:
            import gzip

            with gzip.open(path) as f:
                markdown = f.read().decode("utf-8")
        except IOError:
            with open(path) as f:
                markdown = f.read().decode("utf-8")

        wiki.markdown = markdown
        wiki.markdown_path = path

        return wiki

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.models.WikiHeader.get(owner_id=...)` instead.",
    )
    def getWikiHeaders(self, owner):
        """
        Retrieves the headers of all Wikis belonging to the owner (the entity to which the Wiki is attached).

        Arguments:
            owner: An Entity

        Returns:
            A list of Objects with three fields: id, title and parentId.

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # headers = syn.getWikiHeaders("syn123")

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import WikiHeader

            syn = Synapse()
            syn.login()

            for header in WikiHeader.get(owner_id="syn123"):
                print(header)
            ```
        """

        uri = "/entity/%s/wikiheadertree" % id_of(owner)
        return [DictObject(**header) for header in self._GET_paginated(uri)]

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1351
    def _storeWiki(self, wiki: Wiki, createOrUpdate: bool) -> Wiki:
        """
        Stores or updates the given Wiki.

        Arguments:
            wiki:           A Wiki object
            createOrUpdate: Indicates whether the method should automatically perform an update if the 'obj'
                            conflicts with an existing Synapse object.

        Returns:
            An updated Wiki object
        """
        return wrap_async_to_sync(self._storeWiki_async(wiki, createOrUpdate))

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1351
    async def _storeWiki_async(self, wiki: Wiki, createOrUpdate: bool) -> Wiki:
        """
        Stores or updates the given Wiki.

        Arguments:
            wiki:           A Wiki object
            createOrUpdate: Indicates whether the method should automatically perform an update if the 'obj'
                            conflicts with an existing Synapse object.

        Returns:
            An updated Wiki object
        """
        # Make sure the file handle field is a list
        if "attachmentFileHandleIds" not in wiki:
            wiki["attachmentFileHandleIds"] = []

        # Convert all attachments into file handles
        if wiki.get("attachments") is not None:
            for attachment in wiki["attachments"]:
                fileHandle = await upload_synapse_s3(self, attachment)
                wiki["attachmentFileHandleIds"].append(fileHandle["id"])
            del wiki["attachments"]

        # Perform an update if the Wiki has an ID
        if "id" in wiki:
            updated_wiki = Wiki(
                owner=wiki.ownerId, **self.restPUT(wiki.putURI(), wiki.json())
            )

        # Perform a create if the Wiki has no ID
        else:
            try:
                updated_wiki = Wiki(
                    owner=wiki.ownerId, **self.restPOST(wiki.postURI(), wiki.json())
                )
            except SynapseHTTPError as err:
                # If already present we get an unhelpful SQL error
                if createOrUpdate and (
                    (
                        err.response.status_code == 400
                        and "DuplicateKeyException" in err.response.text
                    )
                    or err.response.status_code == 409
                ):
                    existing_wiki = await self.getWiki_async(wiki.ownerId)

                    # overwrite everything except for the etag (this will keep unmodified fields in the existing wiki)
                    etag = existing_wiki["etag"]
                    existing_wiki.update(wiki)
                    existing_wiki.etag = etag

                    updated_wiki = Wiki(
                        owner=wiki.ownerId,
                        **self.restPUT(existing_wiki.putURI(), existing_wiki.json()),
                    )
                else:
                    raise
        return updated_wiki

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. "
        "Use `synapseclient.models.WikiPage.get_attachment_handles()` on the WikiPage "
        "instead.",
    )
    def getWikiAttachments(self, wiki):
        """
        Retrieve the attachments to a wiki page.

        Arguments:
            wiki: The Wiki object for which the attachments are to be returned.

        Returns:
            A list of file handles for the files attached to the Wiki.

        Example: Migration to the object-oriented model
            &nbsp;

            ```python
            # Old approach (DEPRECATED)
            # attachments = syn.getWikiAttachments(wiki)

            # New approach (RECOMMENDED)
            from synapseclient import Synapse
            from synapseclient.models import WikiPage

            syn = Synapse()
            syn.login()

            attachments = WikiPage(owner_id="syn123", id="456").get_attachment_handles()
            ```
        """
        uri = "/entity/%s/wiki/%s/attachmenthandles" % (wiki.ownerId, wiki.id)
        results = self.restGET(uri)
        file_handles = list(WikiAttachment(**fh) for fh in results["list"])
        return file_handles

    ############################################################
    #                      Tables                              #
    ############################################################

    @tracer.start_as_current_span("Synapse::_waitForAsync")
    def _waitForAsync(self, uri, request, endpoint=None):
        if endpoint is None:
            endpoint = self.repoEndpoint
        async_job_id = self.restPOST(
            uri + "/start", body=json.dumps(request), endpoint=endpoint
        )

        # https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/asynch/AsynchronousJobStatus.html
        sleep = self.table_query_sleep
        start_time = time.time()
        lastMessage, lastProgress, lastTotal = "", 0, 1
        progress_bar = create_progress_bar(total=None, desc=uri, synapse_client=self)
        while time.time() - start_time < self.table_query_timeout:
            result = self.restGET(
                uri + "/get/%s" % async_job_id["token"], endpoint=endpoint
            )
            if result.get("jobState", None) == "PROCESSING":
                message = result.get("progressMessage", lastMessage)
                progress = result.get("progressCurrent", lastProgress)
                total = result.get("progressTotal", lastTotal)
                if total and progress_bar.total != total:
                    progress_bar.total = total
                    progress_bar.refresh()

                if message != "":
                    progress_bar.desc = message
                    progress_bar.refresh()

                # Reset the time if we made progress (fix SYNPY-214)
                if message != lastMessage or lastProgress != progress:
                    progress_bar.update(progress)
                    start_time = time.time()
                    lastMessage, lastProgress, lastTotal = message, progress, total
                sleep = min(
                    self.table_query_max_sleep, sleep * self.table_query_backoff
                )
                doze(sleep, trace_span_name="Synapse::doze_for_async")
            else:
                break
        else:
            raise SynapseTimeoutError(
                "Timeout waiting for query results: %0.1f seconds "
                % (time.time() - start_time)
            )
        if result.get("jobState", None) == "FAILED":
            raise SynapseError(
                result.get("errorMessage", None)
                + "\n"
                + result.get("errorDetails", None),
                asynchronousJobStatus=result,
            )
        if progress_bar.total and progress_bar.n:
            progress_bar.update(progress_bar.total - progress_bar.n)
        progress_bar.refresh()
        progress_bar.close()
        return result

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `Column.get()` method instead. "
        "Check the docstring for the replacement function example.",
    )
    def getColumn(self, id):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `Column.get()` method instead.

        Gets a Column object from Synapse by ID.

        See: [synapseclient.table.Column][]

        Arguments:
            id: The ID of the column to retrieve

        Returns:
            An object of type [synapseclient.table.Column][]

        Example: Using this function (DEPRECATED)
            Getting a column

                column = syn.getColumn(123)

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Column

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Get a column by ID
            column = Column(id="123").get()
            print(f"Column name: {column.name}")
            print(f"Column type: {column.column_type}")
            print(f"Column ID: {column.id}")
            ```
        """
        return Column(**self.restGET(Column.getURI(id)))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "For table columns, use the `.columns` attribute on Table, EntityView, SubmissionView, or Dataset classes after calling `.get(include_columns=True)`. "
        "For column listing and prefix filtering, use the `Column.list()` method. "
        "Check the docstring for the replacement function example.",
    )
    def getColumns(self, x, limit=100, offset=0):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `.columns` attribute on table classes or `Column.list()` method instead.

        Get the columns defined in Synapse either (1) corresponding to a set of column headers, (2) those for a given
        schema, or (3) those whose names start with a given prefix.

        Arguments:
            x: A list of column headers, a Table Entity object (Schema/EntityViewSchema), a Table's Synapse ID, or a
                string prefix
            limit: Number of columns to retrieve per request to Synapse (pagination parameter).
                The function will continue retrieving results until all matching columns are returned.
            offset: the index of the first column to return (pagination parameter)

        Yields:
            A generator over [synapseclient.table.Column][] objects

        Example: Using this function (DEPRECATED)
            Getting columns for a table

                for column in syn.getColumns("syn12345"):
                    print(column.name)

            Getting columns with a prefix

                for column in syn.getColumns("my_prefix"):
                    print(column.name)

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Column, Table, EntityView, SubmissionView, Dataset, DatasetCollection

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # For getting columns of a specific table/view/dataset
            table = Table(id="syn12345")
            table = table.get(include_columns=True)
            for column_name, column in table.columns.items():
                print(f"Table column: {column_name}, Type: {column.column_type}")

            # For EntityView
            view = EntityView(id="syn67890")
            view = view.get(include_columns=True)
            for column_name, column in view.columns.items():
                print(f"EntityView column: {column_name}, Type: {column.column_type}")

            # For SubmissionView
            submission_view = SubmissionView(id="syn11111")
            submission_view = submission_view.get(include_columns=True)
            for column_name, column in submission_view.columns.items():
                print(f"SubmissionView column: {column_name}, Type: {column.column_type}")

            # For Dataset
            dataset = Dataset(id="syn22222")
            dataset = dataset.get(include_columns=True)
            for column_name, column in dataset.columns.items():
                print(f"Dataset column: {column_name}, Type: {column.column_type}")

            # For DatasetCollection
            dataset_collection = DatasetCollection(id="syn33333")
            dataset_collection = dataset_collection.get(include_columns=True)
            for column_name, column in dataset_collection.columns.items():
                print(f"DatasetCollection column: {column_name}, Type: {column.column_type}")

            # For listing all columns with a prefix
            for column in Column.list(prefix="my_prefix"):
                print(f"Prefixed column: {column.name}, Type: {column.column_type}")

            # For listing all columns
            for column in Column.list():
                print(f"All columns: {column.name}, Type: {column.column_type}")

            ```
        """
        if x is None:
            uri = "/column"
            for result in self._GET_paginated(uri, limit=limit, offset=offset):
                yield Column(**result)
        elif isinstance(x, (list, tuple)):
            for header in x:
                try:
                    # if header is an integer, it's a columnID, otherwise it's an aggregate column, like "AVG(Foo)"
                    int(header)
                    yield self.getColumn(header)
                except ValueError:
                    # ignore aggregate column
                    pass
        elif isinstance(x, SchemaBase) or utils.is_synapse_id_str(x):
            for col in self.getTableColumns(x):
                yield col
        elif isinstance(x, str):
            uri = "/column?prefix=" + x
            for result in self._GET_paginated(uri, limit=limit, offset=offset):
                yield Column(**result)
        else:
            ValueError("Can't get columns for a %s" % type(x))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `.snapshot()` method on the `Table`, `EntityView`, `SubmissionView`, or `Dataset` classes instead. "
        "Check the docstring for the replacement function example.",
    )
    def create_snapshot_version(
        self,
        table: typing.Union[
            EntityViewSchema, Schema, str, SubmissionViewSchema, Dataset
        ],
        comment: str = None,
        label: str = None,
        activity: typing.Union[Activity, str] = None,
        wait: bool = True,
    ) -> int:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `.snapshot()` method on the `Table`, `EntityView`, `SubmissionView`, or `Dataset` classes instead.

        Create a new Table Version, new View version, or new Dataset version.

        Arguments:
            table: The schema of the Table/View, or its ID.
            comment: Optional snapshot comment.
            label: Optional snapshot label.
            activity: Optional activity ID applied to snapshot version.
            wait: True if this method should return the snapshot version after waiting for any necessary
                    asynchronous table updates to complete. If False this method will return
                    as soon as any updates are initiated.

        Returns:
            The snapshot version number if wait=True, None if wait=False

        Example: Using this function (DEPRECATED)
            Creating a snapshot of a table

                table_id = "syn1234"
                snapshot_version = syn.create_snapshot_version(
                    table_id,
                    comment="This is a snapshot",
                    label="v1.0",
                    activity=my_activity
                )

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Table, EntityView, SubmissionView, Dataset

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # For Tables
            table = Table(id="syn1234")
            snapshot_response = table.snapshot(
                comment="This is a snapshot",
                label="v1.0",
                include_activity=True,
                associate_activity_to_new_version=True
            )
            print(f"Snapshot version: {snapshot_response['snapshotVersionNumber']}")

            # For Entity Views
            view = EntityView(id="syn5678")
            snapshot_transaction = view.snapshot(
                comment="This is a snapshot",
                label="v1.0",
                include_activity=True,
                associate_activity_to_new_version=True
            )
            print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

            # For Submission Views
            submission_view = SubmissionView(id="syn9012")
            snapshot_transaction = submission_view.snapshot(
                comment="This is a snapshot",
                label="v1.0",
                include_activity=True,
                associate_activity_to_new_version=True
            )
            print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

            # For Datasets
            dataset = Dataset(id="syn3456")
            snapshot_transaction = dataset.snapshot(
                comment="This is a snapshot",
                label="v1.0",
                include_activity=True,
                associate_activity_to_new_version=True
            )
            print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")
            ```
        """
        ent = self.get(id_of(table), downloadFile=False)
        if isinstance(ent, (EntityViewSchema, SubmissionViewSchema, Dataset)):
            result = self._async_table_update(
                table,
                create_snapshot=True,
                comment=comment,
                label=label,
                activity=activity,
                wait=wait,
            )
        elif isinstance(ent, Schema):
            result = self._create_table_snapshot(
                table,
                comment=comment,
                label=label,
                activity=activity,
            )
        else:
            raise ValueError(
                "This function only accepts Synapse ids of Tables or Views"
            )

        # for consistency we return nothing if wait=False since we can't
        # supply the snapshot version on an async table update without waiting
        return result["snapshotVersionNumber"] if wait else None

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _create_table_snapshot(
        self,
        table: typing.Union[Schema, str],
        comment: str = None,
        label: str = None,
        activity: typing.Union[Activity, str] = None,
    ) -> dict:
        """
        Creates Table snapshot

        Arguments:
            table:  The schema of the Table
            comment:  Optional snapshot comment.
            label:  Optional snapshot label.
            activity:  Optional activity ID or activity instance applied to snapshot version.

        Returns:
            Snapshot Response
        """

        # check the activity id or object is provided
        activity_id = None
        if isinstance(activity, collections.abc.Mapping):
            if "id" not in activity:
                activity = self._saveActivity(activity)
            activity_id = activity["id"]
        elif activity is not None:
            activity_id = str(activity)

        snapshot_body = {
            "snapshotComment": comment,
            "snapshotLabel": label,
            "snapshotActivityId": activity_id,
        }
        new_body = {
            key: value for key, value in snapshot_body.items() if value is not None
        }
        snapshot = self.restPOST(
            "/entity/{}/table/snapshot".format(id_of(table)), body=json.dumps(new_body)
        )
        return snapshot

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _async_table_update(
        self,
        table: typing.Union[EntityViewSchema, Schema, str, SubmissionViewSchema],
        changes: typing.List[dict] = [],
        create_snapshot: bool = False,
        comment: str = None,
        label: str = None,
        activity: str = None,
        wait: bool = True,
    ) -> dict:
        """
        Creates view updates and snapshots

        Arguments:
            table:           The schema of the EntityView or its ID.
            changes:         Array of Table changes
            create_snapshot: Create snapshot
            comment:         Optional snapshot comment.
            label:           Optional snapshot label.
            activity:        Optional activity ID applied to snapshot version.
            wait:            True to wait for async table update to complete

        Returns:
            A Snapshot Response
        """
        snapshot_options = {
            "snapshotComment": comment,
            "snapshotLabel": label,
            "snapshotActivityId": activity,
        }
        new_snapshot = {
            key: value for key, value in snapshot_options.items() if value is not None
        }
        table_update_body = {
            "changes": changes,
            "createSnapshot": create_snapshot,
            "snapshotOptions": new_snapshot,
        }

        uri = "/entity/{}/table/transaction/async".format(id_of(table))

        if wait:
            result = self._waitForAsync(uri, table_update_body)

        else:
            result = self.restPOST(
                "{}/start".format(uri), body=json.dumps(table_update_body)
            )

        return result

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Moved to the `columns` attribute on the `from synapseclient.models import Table` class. "
        "Check the docstring for the replacement function example.",
    )
    def getTableColumns(self, table):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `columns` attribute on [synapseclient.models.Table][] instead.

        Retrieve the column models used in the given table schema.

        Arguments:
            table: The schema of the Table whose columns are to be retrieved

        Yields:
            A Generator over the Table's [columns][synapseclient.table.Column]

        Example: Using this function (DEPRECATED)
            Getting columns from a table schema:

                columns = list(syn.getTableColumns("syn123"))

        Example: Migration to new method
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Table, Dataset, DatasetCollection, EntityView, SubmissionView

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # For Tables
            table = Table(id="syn123").get()
            columns = list(table.columns.values())
            print("Columns in table:", columns)
            # Access individual columns by name
            my_table_column = table.columns["my_column_name"]

            # For Datasets
            dataset = Dataset(id="syn456").get()
            columns = list(dataset.columns.values())
            print("Columns in dataset:", columns)
            # Access individual columns by name
            my_dataset_column = dataset.columns["my_column_name"]

            # For Dataset Collections
            dataset_collection = DatasetCollection(id="syn789").get()
            columns = list(dataset_collection.columns.values())
            print("Columns in dataset collection:", columns)
            # Access individual columns by name
            my_collection_column = dataset_collection.columns["my_column_name"]

            # For Entity Views
            entity_view = EntityView(id="syn012").get()
            columns = list(entity_view.columns.values())
            print("Columns in entity view:", columns)
            # Access individual columns by name
            my_view_column = entity_view.columns["my_column_name"]

            # For Submission Views
            submission_view = SubmissionView(id="syn345").get()
            columns = list(submission_view.columns.values())
            print("Columns in submission view:", columns)
            # Access individual columns by name
            my_submission_column = submission_view.columns["my_column_name"]
            ```
        """
        uri = "/entity/{id}/column".format(id=id_of(table))
        # The returned object type for this service, PaginatedColumnModels, is a misnomer.
        # This service always returns the full list of results so the pagination does not not actually matter.
        for result in self.restGET(uri)["results"]:
            yield Column(**result)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `query` functions from `synapseclient.models.Table` instead. "
        "Check the docstring for the replacement function example.",
    )
    def tableQuery(self, query: str, resultsAs: str = "csv", **kwargs):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `query` or `query_async` functions from [synapseclient.models.Table][] instead.

        Query a Synapse Table.

        You can receive query results either as a generator over rows or as a CSV file. For smallish tables, either
        method will work equally well. Use of a "rowset" generator allows rows to be processed one at a time and
        processing may be stopped before downloading the entire table.

        Optional keyword arguments differ for the two return types of `rowset` or `csv`

        Arguments:
            query: Query string in a [SQL-like syntax](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html), for example: `"SELECT * from syn12345"`
            resultsAs: select whether results are returned as a CSV file ("csv") or incrementally downloaded as sets of rows ("rowset")
            limit: (rowset only) Specify the maximum number of rows to be returned, defaults to None
            offset: (rowset only) Don't return the first n rows, defaults to None
            quoteCharacter: (csv only) default double quote
            escapeCharacter: (csv only) default backslash
            lineEnd: (csv only) defaults to os.linesep
            separator: (csv only) defaults to comma
            header: (csv only) True by default
            includeRowIdAndRowVersion: (csv only) True by default
            downloadLocation: (csv only) directory path to download the CSV file to

        Returns:
            A [TableQueryResult][synapseclient.table.TableQueryResult] or [CsvFileTable][synapseclient.table.CsvFileTable] object

        NOTE:
            When performing queries on frequently updated tables, the table can be inaccessible for a period leading
              to a timeout of the query.  Since the results are guaranteed to eventually be returned you can change the
              max timeout by setting the table_query_timeout variable of the Synapse object:

                  # Sets the max timeout to 5 minutes.
                  syn.table_query_timeout = 300

        Example: Using this function (DEPRECATED)
            Getting query results as a DataFrame:

                results = syn.tableQuery("SELECT * FROM syn12345")
                df = results.asDataFrame()

            Getting query results as a CSV file:

                results = syn.tableQuery("SELECT * FROM syn12345", resultsAs="csv", downloadLocation="./my_data/")

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import query, query_async

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Synchronous query (recommended for most use cases)
            results = query(query="SELECT * FROM syn12345")
            print(results)

            # Query with specific options
            results = query(
                query="SELECT * FROM syn12345",
                include_row_id_and_row_version=True,
                convert_to_datetime=True
            )
            print(results)

            # Download query results to a CSV file
            file_path = query(
                query="SELECT * FROM syn12345",
                download_location="./my_data/",
                separator=",",
                quote_character='"',
                header=True
            )
            print(f"Results downloaded to: {file_path}")

            # Asynchronous query (for advanced use cases)
            async def async_query_example():
                results = await query_async(query="SELECT * FROM syn12345")
                print(results)

                # Download query results to a CSV file asynchronously
                file_path = await query_async(
                    query="SELECT * FROM syn12345",
                    download_location="./my_data/",
                    separator=",",
                    quote_character='"',
                    header=True
                )
                print(f"Results downloaded to: {file_path}")

            # Run the async example
            asyncio.run(async_query_example())
            ```

        """
        if resultsAs.lower() == "rowset":
            return TableQueryResult(self, query, **kwargs)
        elif resultsAs.lower() == "csv":
            # TODO: remove isConsistent because it has now been deprecated
            # from the backend
            if kwargs.get("isConsistent") is not None:
                kwargs.pop("isConsistent")
            return CsvFileTable.from_table_query(self, query, **kwargs)
        else:
            raise ValueError(
                "Unknown return type requested from tableQuery: " + str(resultsAs)
            )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `query_part_mask` methods on the `Table`, `EntityView`, `SubmissionView`, `MaterializedView`, or `Dataset` classes instead.",
    )
    def _queryTable(
        self,
        query: str,
        limit: int = None,
        offset: int = None,
        isConsistent: bool = True,
        partMask=None,
    ) -> TableQueryResult:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `query_part_mask` or `query_part_mask_async` methods on the `Table`, `EntityView`, `SubmissionView`, `MaterializedView`, or `Dataset` classes instead.

        Query a table and return the first page of results as a [QueryResultBundle](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryResultBundle.html).
        If the result contains a *nextPageToken*, following pages a retrieved by calling [_queryTableNext][].

        Arguments:
            query:        A sql query
            limit:        The optional limit to the results
            offset:       The optional offset into the results
            isConsistent: Whether the index is inconsistent with the true state of the table
            partMask:     Optional, default all. The 'partsMask' is a bit field for requesting
                          different elements in the resulting JSON bundle.
                          Query Results (queryResults) = 0x1
                          Query Count (queryCount) = 0x2
                          Select Columns (selectColumns) = 0x4
                          Max Rows Per Page (maxRowsPerPage) = 0x8

        Returns:
            The first page of results as a QueryResultBundle

        Example: Using this function (DEPRECATED)
            Query a table with part mask:

                result = syn._queryTable(
                    query="SELECT * FROM syn123",
                    partMask=0x1
                )

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Table

            # Login to Synapse
            syn = Synapse()
            syn.login()

            table = Table(id="syn123")
            result = table.query_part_mask(
                query="SELECT * FROM syn123",
                part_mask=0x1  # QUERY_RESULTS
            )

            # Or using the async version
            async def async_query_example():
                table = Table(id="syn123")
                result = await table.query_part_mask_async(
                    query="SELECT * FROM syn123",
                    part_mask=0x1  # QUERY_RESULTS
                )
                print(result)

            # Run the async example
            asyncio.run(async_query_example())
            ```

        """
        # See: <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/QueryBundleRequest.html>
        query_bundle_request = {
            "concreteType": "org.sagebionetworks.repo.model.table.QueryBundleRequest",
            "query": {
                "sql": query,
                "isConsistent": isConsistent,
                "includeEntityEtag": True,
            },
        }

        if partMask:
            query_bundle_request["partMask"] = partMask
        if limit is not None:
            query_bundle_request["query"]["limit"] = limit
        if offset is not None:
            query_bundle_request["query"]["offset"] = offset
        query_bundle_request["query"]["isConsistent"] = isConsistent

        uri = "/entity/{id}/table/query/async".format(
            id=extract_synapse_id_from_query(query)
        )

        return self._waitForAsync(uri=uri, request=query_bundle_request)

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `query_part_mask` method on the `Table`, `EntityView`, `SubmissionView`, `MaterializedView`, or `Dataset` classes instead.",
    )
    def _queryTableNext(self, nextPageToken: str, tableId: str) -> TableQueryResult:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `query_part_mask` or `query_part_mask_async` methods on the `Table`, `EntityView`, `SubmissionView`, `MaterializedView`, or `Dataset` classes instead.

        Retrieve following pages if the result contains a *nextPageToken*

        Arguments:
            nextPageToken: Forward this token to get the next page of results.
            tableId:       The Synapse ID of the table

        Returns:
            The following page of results as a QueryResultBundle

        Example: Using this function (DEPRECATED)
            Get the next page of results:

                result = syn._queryTableNext(
                    nextPageToken="some_token",
                    tableId="syn123"
                )

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Table

            # Login to Synapse
            syn = Synapse()
            syn.login()

            table = Table(id="syn123")

            # For pagination, use LIMIT and OFFSET directly in the SQL query instead of nextPageToken.
            # LIMIT controls the number of rows returned per page, OFFSET skips the specified number of rows.
            # For example: LIMIT 100 OFFSET 100 returns rows 101-200, LIMIT 100 OFFSET 200 returns rows 201-300, etc.
            result = table.query_part_mask(
                query="SELECT * FROM syn123 LIMIT 100 OFFSET 100",
                part_mask=0x1  # QUERY_RESULTS
            )

            # Or using the async version
            async def async_query_example():
                table = Table(id="syn123")
                result = await table.query_part_mask_async(
                    query="SELECT * FROM syn123 LIMIT 100 OFFSET 100",
                    part_mask=0x1  # QUERY_RESULTS
                )
                print(result)

            # Run the async example
            asyncio.run(async_query_example())
            ```
        """
        uri = "/entity/{id}/table/query/nextPage/async".format(id=tableId)
        return self._waitForAsync(uri=uri, request=nextPageToken)

    def _uploadCsv(
        self,
        filepath: str,
        schema: Union[Entity, str],
        updateEtag: str = None,
        quoteCharacter: str = '"',
        escapeCharacter: str = "\\",
        lineEnd: str = os.linesep,
        separator: str = ",",
        header: bool = True,
        linesToSkip: int = 0,
    ) -> dict:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `_chunk_and_upload_csv` method on [synapseclient.models.Table][] instead for efficient CSV processing.

        Send an [UploadToTableRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/UploadToTableRequest.html) to Synapse.

        Arguments:
            filepath:        Path of a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values) file.
            schema:          A table entity or its Synapse ID.
            updateEtag:      Any RowSet returned from Synapse will contain the current etag of the change set.
                             To update any rows from a RowSet the etag must be provided with the POST.
            quoteCharacter:  Quotation character
            escapeCharacter: Escape character
            lineEnd:         The string used to separate lines
            separator:       Separator character
            header:          Whether to set the first line as header.
            linesToSkip:     The number of lines to skip from the start of the file.
                             The default value of 0 will be used if this is not provided by the caller.

        Returns:
            [UploadToTableResult](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/UploadToTableResult.html)

        Example: Using this function (DEPRECATED)
            Uploading a CSV file to an existing table:

                response = syn._uploadCsv(
                    filepath='/path/to/table.csv',
                    schema='syn123'
                )

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import Table, CsvTableDescriptor

            TABLE_ID ="syn123"  # Replace with your table ID
            PATH = "/path/to/table.csv"

            # Login to Synapse
            # syn = Synapse()
            # syn.login()

            # Create CSV table descriptor with your settings
            csv_descriptor = CsvTableDescriptor(
                is_first_line_header=True,
                separator=",",  # or your custom separator
                quote_character='"',  # or your custom quote character
                escape_character="\\",  # or your custom escape character
            )

            # Define an async function to upload CSV with chunk method
            async def upload_csv_with_chunk_method(table_id, path):
                table = await Table(id=table_id).get_async(include_columns=True)
                await table._chunk_and_upload_csv(
                    path_to_csv=path,
                    insert_size_bytes=900 * 1024 * 1024,  # 900MB chunks
                    csv_table_descriptor=csv_descriptor,
                    schema_change_request=None,  # Add schema changes if needed
                    client=syn,
                    job_timeout=600,
                    additional_changes=None  # Add additional changes if needed
                )

            # Run the async function
            asyncio.run(upload_csv_with_chunk_method(table_id=TABLE_ID, path=PATH))
            ```
        """
        return wrap_async_to_sync(
            self._uploadCsv_async(
                filepath,
                schema,
                updateEtag,
                quoteCharacter,
                escapeCharacter,
                lineEnd,
                separator,
                header,
                linesToSkip,
            )
        )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `_chunk_and_upload_csv` method on the `from synapseclient.models import Table` class instead. "
        "Check the docstring for the replacement function example.",
    )
    async def _uploadCsv_async(
        self,
        filepath: str,
        schema: Union[Entity, str],
        updateEtag: str = None,
        quoteCharacter: str = '"',
        escapeCharacter: str = "\\",
        lineEnd: str = os.linesep,
        separator: str = ",",
        header: bool = True,
        linesToSkip: int = 0,
    ) -> dict:
        """
        Async version of [_uploadCsv][]
        """

        fileHandleId = await multipart_upload_file_async(
            self, filepath, content_type="text/csv"
        )

        uploadRequest = {
            "concreteType": "org.sagebionetworks.repo.model.table.UploadToTableRequest",
            "csvTableDescriptor": {
                "isFirstLineHeader": header,
                "quoteCharacter": quoteCharacter,
                "escapeCharacter": escapeCharacter,
                "lineEnd": lineEnd,
                "separator": separator,
            },
            "linesToSkip": linesToSkip,
            "tableId": id_of(schema),
            "uploadFileHandleId": fileHandleId,
        }

        if updateEtag:
            uploadRequest["updateEtag"] = updateEtag

        response = self._async_table_update(schema, changes=[uploadRequest], wait=True)
        self._check_table_transaction_response(response)

        return response

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _check_table_transaction_response(self, response):
        for result in response["results"]:
            result_type = result["concreteType"]

            if result_type in {
                concrete_types.ROW_REFERENCE_SET_RESULTS,
                concrete_types.TABLE_SCHEMA_CHANGE_RESPONSE,
                concrete_types.UPLOAD_TO_TABLE_RESULT,
            }:
                # if these fail, it we would have gotten an HttpError before the results came back
                pass
            elif result_type == concrete_types.ENTITY_UPDATE_RESULTS:
                # TODO: output full response to error file when the logging JIRA issue gets pulled in
                successful_updates = []
                failed_updates = []
                for update_result in result["updateResults"]:
                    failure_code = update_result.get("failureCode")
                    failure_message = update_result.get("failureMessage")
                    entity_id = update_result.get("entityId")
                    if failure_code or failure_message:
                        failed_updates.append(update_result)
                    else:
                        successful_updates.append(entity_id)

                if failed_updates:
                    raise SynapseError(
                        "Not all of the entities were updated."
                        " Successful updates: %s.  Failed updates: %s"
                        % (successful_updates, failed_updates)
                    )

            else:
                warnings.warn(
                    "Unexpected result from a table transaction of type [%s]."
                    " Please check the result to make sure it is correct. %s"
                    % (result_type, result)
                )

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `query` or `query_async` functions from `synapseclient.models.Table` with `download_location` parameter instead. "
        "Check the docstring for the replacement function example.",
    )
    def _queryTableCsv(
        self,
        query: str,
        quoteCharacter: str = '"',
        escapeCharacter: str = "\\",
        lineEnd: str = os.linesep,
        separator: str = ",",
        header: bool = True,
        includeRowIdAndRowVersion: bool = True,
        downloadLocation: str = None,
    ) -> Tuple:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `query` or `query_async` functions from [synapseclient.models.Table][] with `download_location` parameter instead.

        Query a Synapse Table and download a CSV file containing the results.

        Sends a [DownloadFromTableRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/DownloadFromTableRequest.html) to Synapse.

        Arguments:
            query:                     A sql query
            quoteCharacter:            Quotation character
            escapeCharacter:           Escape character
            lineEnd:                   The string used to separate lines
            separator:                 Separator character
            header:                    Whether to set the first line as header.
            includeRowIdAndRowVersion: Whether to set the first two columns contains the row ID and row version.
            downloadLocation:          The download location

        Returns:
            A tuple containing a [DownloadFromTableResult](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/table/DownloadFromTableResult.html)

        Example: Using this function (DEPRECATED)
            Query a table and download CSV:

                result, csv_path = syn._queryTableCsv(
                    query="SELECT * FROM syn123",
                    downloadLocation="/path/to/download",
                    quoteCharacter='"',
                    separator=","
                )

        Example: Migration to new method
            &nbsp;

            ```python
            import asyncio
            from synapseclient import Synapse
            from synapseclient.models import query, query_async

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Synchronous query with CSV download
            csv_path = query(
                query="SELECT * FROM syn123",
                download_location="/path/to/download",
                quote_character='"',
                separator=",",
                header=True,
                include_row_id_and_row_version=True
            )
            print(f"CSV downloaded to: {csv_path}")

            # Asynchronous query with CSV download
            async def async_csv_download():
                csv_path = await query_async(
                    query="SELECT * FROM syn123",
                    download_location="/path/to/download",
                    quote_character='"',
                    separator=",",
                    header=True,
                    include_row_id_and_row_version=True
                )
                print(f"CSV downloaded to: {csv_path}")

            # Run the async example
            asyncio.run(async_csv_download())
            ```

        The DownloadFromTableResult object contains these fields:
         * headers:             ARRAY<STRING>, The list of ColumnModel IDs that describes the rows of this set.
         * resultsFileHandleId: STRING, The resulting file handle ID can be used to download the CSV file created by
                                this query.
         * concreteType:        STRING
         * etag:                STRING, Any RowSet returned from Synapse will contain the current etag of the change
                                set.
                                To update any rows from a RowSet the etag must be provided with the POST.
         * tableId:             STRING, The ID of the table identified in the from clause of the table query.
        """
        download_from_table_request = {
            "concreteType": "org.sagebionetworks.repo.model.table.DownloadFromTableRequest",
            "csvTableDescriptor": {
                "isFirstLineHeader": header,
                "quoteCharacter": quoteCharacter,
                "escapeCharacter": escapeCharacter,
                "lineEnd": lineEnd,
                "separator": separator,
            },
            "sql": query,
            "writeHeader": header,
            "includeRowIdAndRowVersion": includeRowIdAndRowVersion,
            "includeEntityEtag": True,
        }

        uri = "/entity/{id}/table/download/csv/async".format(
            id=extract_synapse_id_from_query(query)
        )
        download_from_table_result = self._waitForAsync(
            uri=uri, request=download_from_table_request
        )
        file_handle_id = download_from_table_result["resultsFileHandleId"]
        cached_file_path = self.cache.get(
            file_handle_id=file_handle_id, path=downloadLocation
        )
        if cached_file_path is not None:
            return download_from_table_result, cached_file_path

        if downloadLocation:
            download_dir = ensure_download_location_is_directory(
                download_location=downloadLocation
            )
        else:
            download_dir = self.cache.get_cache_dir(file_handle_id=file_handle_id)

        os.makedirs(download_dir, exist_ok=True)
        filename = f"SYNAPSE_TABLE_QUERY_{file_handle_id}.csv"
        path = wrap_async_to_sync(
            coroutine=download_by_file_handle(
                file_handle_id=file_handle_id,
                synapse_id=extract_synapse_id_from_query(query),
                entity_type="TableEntity",
                destination=os.path.join(download_dir, filename),
                synapse_client=self,
            )
        )

        return download_from_table_result, path

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `.columns` attribute on table-like classes or the `add_column` method to store columns during the storage of these table-like classes. "
        "For individual column operations, use the synapseclient.api.table_services.post_columns function. "
        "Check the docstring for the replacement function example.",
    )
    def createColumn(
        self,
        name,
        columnType,
        maximumSize=None,
        defaultValue=None,
        enumValues=None,
    ):
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `.columns` attribute on table-like classes or `add_column` method to store columns during the storage of these table-like classes.

        Creates a new [synapseclient.table.Column][] in Synapse.

        Arguments:
            name: The name of the column
            columnType: The column type
            maximumSize: The maximum size of the column
            defaultValue: The default value of the column
            enumValues: The enum values of the column

        Returns:
            A [synapseclient.table.Column][] object

        Example: Using this function (DEPRECATED)
            Creating a column

                column = syn.createColumn(
                    name="my_column",
                    columnType="STRING",
                    maximumSize=100
                )

        Example: Migration to new methods
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Column, ColumnType, Table
            from synapseclient.api.table_services import post_columns
            import asyncio

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Method 1: Create column and add to table using ColumnMixin
            column = Column(
                name="my_column",
                column_type=ColumnType.STRING,
                maximum_size=100
            )

            # Get an existing table and add the column
            table = Table(id="syn1234").get(include_columns=True)
            table.add_column(column)
            table.store()

            # Method 2: Create a new table with columns
            table = Table(
                name="My Table",
                parent_id="syn5678",
                columns=[
                    Column(name="column1", column_type=ColumnType.STRING),
                    Column(name="column2", column_type=ColumnType.INTEGER),
                ]
            )
            table.store()

            # Method 3: Use the async post_columns function directly
            async def create_columns():
                columns = [
                    Column(name="my_column", column_type=ColumnType.STRING, maximum_size=100)
                ]
                created_columns = await post_columns(columns)
                return created_columns

            # Run the async function
            created_columns = asyncio.run(create_columns())
            ```
        """
        columnModel = Column(
            name=name,
            columnType=columnType,
            maximumSize=maximumSize,
            defaultValue=defaultValue,
            enumValue=enumValues,
        )
        return Column(**self.restPOST("/column", json.dumps(columnModel)))

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. "
        "Use the `.columns` attribute on table-like classes or the `add_column` method to store columns during the storage of these table-like classes. "
        "For batch column operations, use the synapseclient.api.table_services.post_columns function. "
        "Check the docstring for the replacement function example.",
    )
    def createColumns(self, columns: typing.List[Column]) -> typing.List[Column]:
        """
        **Deprecated with replacement.** This method will be removed in 5.0.0.
        Use the `.columns` attribute on table-like classes or the `add_column` method to store columns during the storage of these table-like classes.

        Creates a batch of [synapseclient.table.Column][]'s within a single request.

        Arguments:
            columns: A list of [synapseclient.table.Column][]'s

        Returns:
            A list of [synapseclient.table.Column][]'s that have been created in Synapse

        Example: Using this function (DEPRECATED)
            Creating multiple columns

                columns = [
                    Column(name="col1", columnType="STRING"),
                    Column(name="col2", columnType="INTEGER")
                ]
                created_columns = syn.createColumns(columns)

        Example: Migration to new methods
            &nbsp;

            ```python
            from synapseclient import Synapse
            from synapseclient.models import Column, ColumnType, Table
            from synapseclient.api.table_services import post_columns
            import asyncio

            # Login to Synapse
            syn = Synapse()
            syn.login()

            # Method 1: Create columns and add to table using ColumnMixin
            columns = [
                Column(name="col1", column_type=ColumnType.STRING),
                Column(name="col2", column_type=ColumnType.INTEGER)
            ]

            # Get an existing table and add the columns
            table = Table(id="syn1234").get(include_columns=True)
            table.add_column(columns)
            table.store()

            # Method 2: Create a new table with columns
            table = Table(
                name="My Table",
                parent_id="syn5678",
                columns=[
                    Column(name="col1", column_type=ColumnType.STRING),
                    Column(name="col2", column_type=ColumnType.INTEGER),
                ]
            )
            table.store()

            # Method 3: Use the async post_columns function directly
            async def create_columns():
                columns = [
                    Column(name="col1", column_type=ColumnType.STRING),
                    Column(name="col2", column_type=ColumnType.INTEGER)
                ]
                created_columns = await post_columns(columns)
                return created_columns

            # Run the async function
            created_columns = asyncio.run(create_columns())
            ```
        """
        request_body = {
            "concreteType": "org.sagebionetworks.repo.model.ListWrapper",
            "list": list(columns),
        }
        response = self.restPOST("/column/batch", json.dumps(request_body))
        return [Column(**col) for col in response["list"]]

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _getColumnByName(self, schema: Schema, column_name: str) -> Column:
        """
        Given a schema and a column name, get the corresponding [Column][synapseclient.table.Column] object.

        Arguments:
            schema: The Schema is an [Entity][synapseclient.entity.Entity] that defines a set of columns in a table.
            column_name: The column name

        Returns:
            A Column object
        """
        for column in self.getColumns(schema):
            if column.name == column_name:
                return column
        return None

    @deprecated(
        version="4.14.0",
        reason="To be removed in 5.0.0. This function has no replacement.",
    )
    def downloadTableColumns(self, table, columns, downloadLocation=None, **kwargs):
        """
        Bulk download of table-associated files.

        Arguments:
            table: Table query result
            columns: A list of column names as strings
            downloadLocation: Directory into which to download the files

        Returns:
            A dictionary from file handle ID to path in the local file system.

        For example, consider a Synapse table whose ID is "syn12345" with two columns of type FILEHANDLEID named 'foo'
        and 'bar'. The associated files are JSON encoded, so we might retrieve the files from Synapse and load for the
        second 100 of those rows as shown here:

            import json

            results = syn.tableQuery('SELECT * FROM syn12345 LIMIT 100 OFFSET 100')
            file_map = syn.downloadTableColumns(results, ['foo', 'bar'])

            for file_handle_id, path in file_map.items():
                with open(path) as f:
                    data[file_handle_id] = f.read()

        """
        return wrap_async_to_sync(
            self.downloadTableColumns_async(table, columns, downloadLocation, **kwargs)
        )

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1632
    async def downloadTableColumns_async(
        self, table, columns, downloadLocation=None, **kwargs
    ):
        """Async version of downloadTableColumns."""
        RETRIABLE_FAILURE_CODES = ["EXCEEDS_SIZE_LIMIT"]
        MAX_DOWNLOAD_TRIES = 100
        max_files_per_request = kwargs.get("max_files_per_request", 2500)
        # Rowset tableQuery result not allowed
        if isinstance(table, TableQueryResult):
            raise ValueError(
                "downloadTableColumn doesn't work with rowsets. Please use default tableQuery settings."
            )
        if isinstance(columns, str):
            columns = [columns]
        if not isinstance(columns, collections.abc.Iterable):
            raise TypeError("Columns parameter requires a list of column names")

        (
            file_handle_associations,
            file_handle_to_path_map,
        ) = self._build_table_download_file_handle_list(
            table,
            columns,
            downloadLocation,
        )

        self.logger.info(
            "Downloading %d files, %d cached locally"
            % (len(file_handle_associations), len(file_handle_to_path_map))
        )

        permanent_failures = collections.OrderedDict()

        attempts = 0
        while len(file_handle_associations) > 0 and attempts < MAX_DOWNLOAD_TRIES:
            attempts += 1

            file_handle_associations_batch = file_handle_associations[
                :max_files_per_request
            ]

            # ------------------------------------------------------------
            # call async service to build zip file
            # ------------------------------------------------------------

            # returns a BulkFileDownloadResponse:
            #   <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/file/BulkFileDownloadResponse.html>
            request = dict(
                concreteType="org.sagebionetworks.repo.model.file.BulkFileDownloadRequest",
                requestedFiles=file_handle_associations_batch,
            )
            response = self._waitForAsync(
                uri="/file/bulk/async",
                request=request,
                endpoint=self.fileHandleEndpoint,
            )

            # ------------------------------------------------------------
            # download zip file
            # ------------------------------------------------------------

            temp_dir = tempfile.mkdtemp()
            zipfilepath = os.path.join(temp_dir, "table_file_download.zip")
            try:
                zipfilepath = await download_by_file_handle(
                    file_handle_id=response["resultZipFileHandleId"],
                    synapse_id=table.tableId,
                    entity_type="TableEntity",
                    destination=zipfilepath,
                )
                # TODO handle case when no zip file is returned
                # TODO test case when we give it partial or all bad file handles
                # TODO test case with deleted fileHandleID
                # TODO return null for permanent failures

                # ------------------------------------------------------------
                # unzip into cache
                # ------------------------------------------------------------

                if downloadLocation:
                    download_dir = ensure_download_location_is_directory(
                        downloadLocation
                    )

                with zipfile.ZipFile(zipfilepath) as zf:
                    # the directory structure within the zip follows that of the cache:
                    # {fileHandleId modulo 1000}/{fileHandleId}/{fileName}
                    for summary in response["fileSummary"]:
                        if summary["status"] == "SUCCESS":
                            if not downloadLocation:
                                download_dir = self.cache.get_cache_dir(
                                    summary["fileHandleId"]
                                )

                            filepath = extract_zip_file_to_directory(
                                zf, summary["zipEntryName"], download_dir
                            )
                            self.cache.add(summary["fileHandleId"], filepath)
                            file_handle_to_path_map[summary["fileHandleId"]] = filepath
                        elif summary["failureCode"] not in RETRIABLE_FAILURE_CODES:
                            permanent_failures[summary["fileHandleId"]] = summary
            finally:
                if os.path.exists(zipfilepath):
                    os.remove(zipfilepath)

            # Do we have remaining files to download?
            file_handle_associations = [
                fha
                for fha in file_handle_associations
                if fha["fileHandleId"] not in file_handle_to_path_map
                and fha["fileHandleId"] not in permanent_failures.keys()
            ]

        # TODO if there are files we still haven't downloaded

        return file_handle_to_path_map

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _build_table_download_file_handle_list(self, table, columns, downloadLocation):
        # ------------------------------------------------------------
        # build list of file handles to download
        # ------------------------------------------------------------
        cols_not_found = [
            c for c in columns if c not in [h.name for h in table.headers]
        ]
        if len(cols_not_found) > 0:
            raise ValueError(
                "Columns not found: "
                + ", ".join('"' + col + '"' for col in cols_not_found)
            )
        col_indices = [i for i, h in enumerate(table.headers) if h.name in columns]
        # see: <https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/file/BulkFileDownloadRequest.html>
        file_handle_associations = []
        file_handle_to_path_map = collections.OrderedDict()
        seen_file_handle_ids = (
            set()
        )  # ensure not sending duplicate requests for the same FileHandle IDs
        for row in table:
            for col_index in col_indices:
                file_handle_id = row[col_index]
                if is_integer(file_handle_id):
                    path_to_cached_file = self.cache.get(
                        file_handle_id, path=downloadLocation
                    )
                    if path_to_cached_file:
                        file_handle_to_path_map[file_handle_id] = path_to_cached_file
                    elif file_handle_id not in seen_file_handle_ids:
                        file_handle_associations.append(
                            dict(
                                associateObjectType="TableEntity",
                                fileHandleId=file_handle_id,
                                associateObjectId=table.tableId,
                            )
                        )
                    seen_file_handle_ids.add(file_handle_id)
                else:
                    warnings.warn("Weird file handle: %s" % file_handle_id)
        return file_handle_associations, file_handle_to_path_map

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _get_default_view_columns(self, view_type, view_type_mask=None):
        """Get default view columns"""
        uri = f"/column/tableview/defaults?viewEntityType={view_type}"
        if view_type_mask:
            uri += f"&viewTypeMask={view_type_mask}"
        return [Column(**col) for col in self.restGET(uri)["list"]]

    @deprecated(
        version="4.9.0",
        reason="To be removed in 5.0.0. This is a private function and has no direct replacement.",
    )
    def _get_annotation_view_columns(
        self, scope_ids: list, view_type: str, view_type_mask: str = None
    ) -> list:
        """
        Get all the columns of a submission of entity view based on existing annotations

        Arguments:
            scope_ids:      List of Evaluation Queue or Project/Folder Ids
            view_type:      The submissionview or entityview
            view_type_mask: Bit mask representing the types to include in the view.

        Returns:
            The list of columns
        """
        columns = []
        next_page_token = None
        while True:
            view_scope = {
                "concreteType": "org.sagebionetworks.repo.model.table.ViewColumnModelRequest",
                "viewScope": {
                    "scope": scope_ids,
                    "viewEntityType": view_type,
                    "viewTypeMask": view_type_mask,
                },
            }
            if next_page_token:
                view_scope["nextPageToken"] = next_page_token
            response = self._waitForAsync(
                uri="/column/view/scope/async", request=view_scope
            )
            columns.extend(Column(**column) for column in response["results"])
            next_page_token = response.get("nextPageToken")
            if next_page_token is None:
                break
        return columns

    ############################################################
    #              CRUD for Entities (properties)              #
    ############################################################

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1623
    def _getEntity(
        self, entity: Union[str, dict, Entity], version: int = None
    ) -> Dict[str, Union[str, bool]]:
        """
        Get an entity from Synapse.

        Arguments:
            entity:  A Synapse ID, a dictionary representing an Entity, or a Synapse Entity object
            version: The version number to fetch

        Returns:
            A dictionary containing an Entity's properties
        """

        uri = "/entity/" + id_of(entity)
        if version:
            uri += "/version/%d" % version
        return self.restGET(uri)

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1623
    def _createEntity(self, entity: Union[dict, Entity]) -> Dict[str, Union[str, bool]]:
        """
        Create a new entity in Synapse.

        Arguments:
            entity: A dictionary representing an Entity or a Synapse Entity object

        Returns:
            A dictionary containing an Entity's properties
        """

        return self.restPOST(uri="/entity", body=json.dumps(get_properties(entity)))

    # TODO: Deprecate method in https://sagebionetworks.jira.com/browse/SYNPY-1623
    def _updateEntity(
        self,
        entity: Union[dict, Entity],
        incrementVersion: bool = True,
        versionLabel: str = None,
    ) -> Dict[str, Union[str, bool]]:
        """
        Update an existing entity in Synapse.

        Arguments:
            entity:           A dictionary representing an Entity or a Synapse Entity object
            incrementVersion: Whether to increment the entity version (if Versionable)
            versionLabel:     A label for the entity version (if Versionable)

        Returns:
            A dictionary containing an Entity's properties
        """

        uri = "/entity/%s" % id_of(entity)

        params = {}
        if is_versionable(entity):
            if versionLabel:
                # a versionLabel implicitly implies incrementing
                incrementVersion = True
            elif incrementVersion and "versionNumber" in entity:
                versionLabel = str(entity["versionNumber"] + 1)

            if incrementVersion:
                entity["versionLabel"] = versionLabel
                params["newVersion"] = "true"

        return self.restPUT(uri, body=json.dumps(get_properties(entity)), params=params)

    @deprecated(
        version="4.11.0",
        reason="To be removed in 5.0.0. "
        "Use `from synapseclient.operations import find_entity_id` instead.",
    )
    def findEntityId(self, name, parent=None):
        """
        Find an Entity given its name and parent.

        Arguments:
            name: Name of the entity to find
            parent: An Entity object or the Id of an entity as a string. Omit if searching for a Project by name

        Returns:
            The Entity ID or None if not found
        """
        # when we want to search for a project by name. set parentId as None instead of ROOT_ENTITY
        entity_lookup_request = {
            "parentId": id_of(parent) if parent else None,
            "entityName": name,
        }
        try:
            return self.restPOST(
                "/entity/child", body=json.dumps(entity_lookup_request)
            ).get("id")
        except SynapseHTTPError as e:
            if (
                e.response.status_code == 404
            ):  # a 404 error is raised if the entity does not exist
                return None
            raise

    ############################################################
    #                       Send Message                       #
    ############################################################
    def sendMessage(
        self, userIds, messageSubject, messageBody, contentType="text/plain"
    ):
        """
        send a message via Synapse.

        Arguments:
            userIds: A list of user IDs to which the message is to be sent
            messageSubject: The subject for the message
            messageBody: The body of the message
            contentType: optional contentType of message body (default="text/plain")
                            Should be one of "text/plain" or "text/html"

        Returns:
            The metadata of the created message
        """
        return wrap_async_to_sync(
            self.sendMessage_async(
                userIds=userIds,
                messageSubject=messageSubject,
                messageBody=messageBody,
                contentType=contentType,
            )
        )

    async def sendMessage_async(
        self, userIds, messageSubject, messageBody, contentType="text/plain"
    ):
        """Async version of sendMessage."""

        fileHandleId = await multipart_upload_string_async(
            self, messageBody, content_type=contentType
        )
        message = dict(
            recipients=userIds, subject=messageSubject, fileHandleId=fileHandleId
        )
        return self.restPOST(uri="/message", body=json.dumps(message))

    ############################################################
    #                   Low level Rest calls                   #
    ############################################################

    def _generate_headers(
        self, headers: Dict[str, str] = None, is_httpx: bool = False
    ) -> Dict[str, str]:
        """
        Generate headers (auth headers produced separately by credentials object)

        """
        if headers is None:
            headers = dict(self.default_headers)

        # Replace the `requests` package's default user-agent with the httpx user agent
        if is_httpx:
            httpx_agent = f"{httpx.__title__}/{httpx.__version__}"
            requests_agent = requests.utils.default_user_agent()
            agent = deepcopy(synapseclient.USER_AGENT)
            agent["User-Agent"] = agent["User-Agent"].replace(
                requests_agent, httpx_agent
            )
            headers.update(agent)
        else:
            headers.update(synapseclient.USER_AGENT)

        if self.user_agent:
            headers["User-Agent"] = (
                headers["User-Agent"] + " " + " ".join(self.user_agent)
            )

        return headers

    def _handle_synapse_http_error(self, response):
        """Raise errors as appropriate for returned Synapse http status codes"""

        try:
            exceptions._raise_for_status(response, verbose=self.debug)
        except exceptions.SynapseHTTPError as ex:
            # if we get a unauthenticated or forbidden error and the user is not logged in
            # then we raise it as an authentication error.
            # we can't know for certain that logging in to their particular account will grant them
            # access to this resource but more than likely it's the cause of this error.
            if response.status_code in (401, 403) and not self.credentials:
                raise SynapseAuthenticationError(
                    "You are not logged in and do not have access to a requested resource."
                ) from ex

            raise

    def _handle_httpx_synapse_http_error(self, response: httpx.Response) -> None:
        """Raise errors as appropriate for the HTTPX library returned Synapse http
        status codes

        Arguments:
            response: The HTTPX response object
        """

        try:
            exceptions._raise_for_status_httpx(
                response=response, verbose=self.debug, logger=self.logger
            )
        except exceptions.SynapseHTTPError as ex:
            # if we get a unauthenticated or forbidden error and the user is not logged in
            # then we raise it as an authentication error.
            # we can't know for certain that logging in to their particular account will grant them
            # access to this resource but more than likely it's the cause of this error.
            if response.status_code in (401, 403) and not self.credentials:
                raise SynapseAuthenticationError(
                    "You are not logged in and do not have access to a requested resource."
                ) from ex

            raise

    def _rest_call(
        self,
        method,
        uri,
        data,
        endpoint,
        headers,
        retryPolicy,
        requests_session,
        **kwargs,
    ):
        """
        Sends an HTTP request to the Synapse server.

        Arguments:
            method:           The method to implement Create, Read, Update, Delete operations.
                              Should be post, get, put, delete.
            uri:              URI on which the method is performed
            endpoint:         Server endpoint, defaults to self.repoEndpoint
            headers:          Dictionary of headers to use rather than the API-key-signed default set of headers
            retryPolicy:      A retry policy
            requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
            kwargs:           Any other arguments taken by a
                              [request](http://docs.python-requests.org/en/latest/) method

        Returns:
            JSON encoding of response
        """
        self.logger.debug(f"Sending {method} request to {uri}")
        uri, headers = self._build_uri_and_headers(
            uri, endpoint=endpoint, headers=headers
        )

        retryPolicy = self._build_retry_policy(retryPolicy)
        requests_session = requests_session or self._requests_session

        auth = kwargs.pop("auth", self.credentials)
        requests_method_fn = getattr(requests_session, method)
        timeout = kwargs.pop("timeout", self._http_timeout_seconds)
        response = with_retry(
            lambda: requests_method_fn(
                uri,
                data=data,
                headers=headers,
                auth=auth,
                timeout=timeout,
                **kwargs,
            ),
            verbose=self.debug,
            **retryPolicy,
        )
        self._handle_synapse_http_error(response)
        return response

    def restGET(
        self,
        uri,
        endpoint=None,
        headers=None,
        retryPolicy={},
        requests_session=None,
        **kwargs,
    ):
        """
        Sends an HTTP GET request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use rather than the API-key-signed default set of headers
            requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
            kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

        Returns:
            JSON encoding of response
        """
        response = self._rest_call(
            "get", uri, None, endpoint, headers, retryPolicy, requests_session, **kwargs
        )
        return self._return_rest_body(response)

    def restPOST(
        self,
        uri,
        body,
        endpoint=None,
        headers=None,
        retryPolicy={},
        requests_session=None,
        **kwargs,
    ):
        """
        Sends an HTTP POST request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            endpoint: Server endpoint, defaults to self.repoEndpoint
            body: The payload to be delivered
            headers: Dictionary of headers to use rather than the API-key-signed default set of headers
            requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
            kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

        Returns:
            JSON encoding of response
        """
        response = self._rest_call(
            "post",
            uri,
            body,
            endpoint,
            headers,
            retryPolicy,
            requests_session,
            **kwargs,
        )
        return self._return_rest_body(response)

    def restPUT(
        self,
        uri,
        body=None,
        endpoint=None,
        headers=None,
        retryPolicy={},
        requests_session=None,
        **kwargs,
    ):
        """
        Sends an HTTP PUT request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            endpoint: Server endpoint, defaults to self.repoEndpoint
            body: The payload to be delivered
            headers: Dictionary of headers to use rather than the API-key-signed default set of headers
            requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
            kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

        Returns
            JSON encoding of response
        """
        response = self._rest_call(
            "put",
            uri,
            body,
            endpoint,
            headers,
            retryPolicy,
            requests_session,
            **kwargs,
        )
        return self._return_rest_body(response)

    def restDELETE(
        self,
        uri,
        endpoint=None,
        headers=None,
        retryPolicy={},
        requests_session=None,
        **kwargs,
    ):
        """
        Sends an HTTP DELETE request to the Synapse server.

        Arguments:
            uri: URI of resource to be deleted
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use rather than the API-key-signed default set of headers
            requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
            kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

        """
        self._rest_call(
            "delete",
            uri,
            None,
            endpoint,
            headers,
            retryPolicy,
            requests_session,
            **kwargs,
        )

    def _build_uri_and_headers(
        self,
        uri: str,
        endpoint: str = None,
        headers: Dict[str, str] = None,
        is_httpx: bool = False,
    ) -> Tuple[str, Dict[str, str]]:
        """Returns a tuple of the URI and headers to request with."""

        if endpoint is None:
            endpoint = self.repoEndpoint

        trace.get_current_span().set_attributes({"server.address": endpoint})

        # Check to see if the URI is incomplete (i.e. a Synapse URL)
        # In that case, append a Synapse endpoint to the URI
        parsedURL = urllib_urlparse.urlparse(uri)
        if parsedURL.netloc == "":
            uri = endpoint + uri

        if headers is None:
            headers = self._generate_headers(is_httpx=is_httpx)
        return uri, headers

    def _build_retry_policy(self, retryPolicy={}):
        """Returns a retry policy to be passed onto _with_retry."""

        defaults = dict(STANDARD_RETRY_PARAMS)
        defaults.update(retryPolicy)
        return defaults

    def _build_retry_policy_async(
        self, retry_policy: Dict[str, Any] = {}
    ) -> Dict[str, Any]:
        """Returns a retry policy to be passed onto with_retry_time_based_async."""

        defaults = dict(STANDARD_RETRY_ASYNC_PARAMS)
        defaults.update(retry_policy)
        return defaults

    def _return_rest_body(self, response) -> Union[Dict[str, Any], str]:
        """Returns either a dictionary or a string depending on the 'content-type' of the response."""
        if is_json(response.headers.get("content-type", None)):
            return response.json()
        return response.text

    async def _rest_call_async(
        self,
        method: str,
        uri: str,
        data: Any,
        endpoint: str,
        headers: Dict[str, str],
        retry_policy: Dict[str, Any],
        requests_session_async_synapse: httpx.AsyncClient,
        **kwargs,
    ) -> Union[httpx.Response, None]:
        """
        Sends an HTTP request to the Synapse server.

        Arguments:
            method: The method to implement Create, Read, Update, Delete operations.
                Should be post, get, put, delete.
            uri: URI on which the method is performed.
            data: The payload to be delivered.
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use.
            retry_policy: A retry policy that matches the arguments of
                [synapseclient.core.retry.with_retry_time_based_async][].
            requests_session_async_synapse: The async client to use when making this
                specific call.
            kwargs: Any other arguments taken by a
                [request](https://www.python-httpx.org/api/) method

        Returns:
            JSON encoding of response
        """
        self.logger.debug(f"Sending {method} request to {uri}")
        uri, headers = self._build_uri_and_headers(
            uri, endpoint=endpoint, headers=headers, is_httpx=True
        )

        retry_policy = self._build_retry_policy_async(retry_policy)
        requests_session = (
            requests_session_async_synapse
            or self._get_requests_session_async_synapse(
                asyncio_event_loop=asyncio.get_running_loop()
            )
        )

        auth = kwargs.pop("auth", self.credentials)
        requests_method_fn = getattr(requests_session, method)
        if data:
            response = await with_retry_time_based_async(
                lambda: requests_method_fn(
                    uri,
                    content=data,
                    headers=headers,
                    auth=auth,
                    **kwargs,
                ),
                verbose=self.debug,
                **retry_policy,
            )
        else:
            response = await with_retry_time_based_async(
                lambda: requests_method_fn(
                    uri,
                    headers=headers,
                    auth=auth,
                    **kwargs,
                ),
                verbose=self.debug,
                **retry_policy,
            )

        self._handle_httpx_synapse_http_error(response)

        return response

    async def rest_get_async(
        self,
        uri: str,
        endpoint: str = None,
        headers: httpx.Headers = None,
        retry_policy: Dict[str, Any] = {},
        requests_session_async_synapse: httpx.AsyncClient = None,
        **kwargs,
    ) -> Union[Dict[str, Any], str, None]:
        """
        Sends an HTTP GET request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use.
            retry_policy: A retry policy that matches the arguments of
                [synapseclient.core.retry.with_retry_time_based_async][].
            requests_session_async_synapse: The async client to use when making this
                specific call.
            kwargs: Any other arguments taken by a
                [request](https://www.python-httpx.org/api/) method

        Returns:
            JSON encoding of response
        """
        response = await self._rest_call_async(
            "get",
            uri,
            None,
            endpoint,
            headers,
            retry_policy,
            requests_session_async_synapse,
            **kwargs,
        )
        return self._return_rest_body(response)

    async def rest_post_async(
        self,
        uri: str,
        body: Any = None,
        endpoint: str = None,
        headers: httpx.Headers = None,
        retry_policy: Dict[str, Any] = {},
        requests_session_async_synapse: httpx.AsyncClient = None,
        **kwargs,
    ) -> Union[Dict[str, Any], str]:
        """
        Sends an HTTP POST request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            body: The payload to be delivered
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use.
            retry_policy: A retry policy that matches the arguments of
                [synapseclient.core.retry.with_retry_time_based_async][].
            requests_session_async_synapse: The async client to use when making this
                specific call.
            kwargs: Any other arguments taken by a
                [request](https://www.python-httpx.org/api/) method

        Returns:
            JSON encoding of response
        """
        response = await self._rest_call_async(
            "post",
            uri,
            body,
            endpoint,
            headers,
            retry_policy,
            requests_session_async_synapse,
            **kwargs,
        )
        return self._return_rest_body(response)

    async def rest_put_async(
        self,
        uri: str,
        body: Any = None,
        endpoint: str = None,
        headers: httpx.Headers = None,
        retry_policy: Dict[str, Any] = {},
        requests_session_async_synapse: httpx.AsyncClient = None,
        **kwargs,
    ) -> Union[Dict[str, Any], str]:
        """
        Sends an HTTP PUT request to the Synapse server.

        Arguments:
            uri: URI on which get is performed
            body: The payload to be delivered.
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use.
            retry_policy: A retry policy that matches the arguments of
                [synapseclient.core.retry.with_retry_time_based_async][].
            requests_session_async_synapse: The async client to use when making this
                specific call.
            kwargs: Any other arguments taken by a
                [request](https://www.python-httpx.org/api/) method

        Returns
            JSON encoding of response
        """
        response = await self._rest_call_async(
            "put",
            uri,
            body,
            endpoint,
            headers,
            retry_policy,
            requests_session_async_synapse,
            **kwargs,
        )
        return self._return_rest_body(response)

    async def rest_delete_async(
        self,
        uri: str,
        endpoint: str = None,
        headers: httpx.Headers = None,
        retry_policy: Dict[str, Any] = {},
        requests_session_async_synapse: httpx.AsyncClient = None,
        **kwargs,
    ) -> None:
        """
        Sends an HTTP DELETE request to the Synapse server.

        Arguments:
            uri: URI of resource to be deleted
            endpoint: Server endpoint, defaults to self.repoEndpoint
            headers: Dictionary of headers to use.
            retry_policy: A retry policy that matches the arguments of
                [synapseclient.core.retry.with_retry_time_based_async][].
            requests_session_async_synapse: The async client to use when making this
                specific call
            kwargs: Any other arguments taken by a [request](https://www.python-httpx.org/api/) method

        """
        await self._rest_call_async(
            "delete",
            uri,
            None,
            endpoint,
            headers,
            retry_policy,
            requests_session_async_synapse,
            **kwargs,
        )

Methods:

login

login(email: str = None, silent: bool = False, authToken: str = None, profile: str = 'default') -> None

Valid combinations of login() arguments:

  • authToken
  • Profile-based authentication (from .synapseConfig)

If no login arguments are provided or only username is provided, login() will attempt to log in using information from these sources (in order of preference):

  1. .synapseConfig file (supports multiple profiles)(in user home folder unless configured otherwise)
  2. User defined arguments during a CLI session
  3. User's Personal Access Token (aka: Synapse Auth Token) from the environment variable: SYNAPSE_AUTH_TOKEN
  4. Retrieves user's authentication token from AWS SSM Parameter store (if configured)
PARAMETER DESCRIPTION
email

Synapse user name (or an email address associated with a Synapse account)

TYPE: str DEFAULT: None

authToken

A bearer authorization token, e.g. a personal access token.

TYPE: str DEFAULT: None

silent

Defaults to False. Suppresses the "Welcome ...!" message.

TYPE: bool DEFAULT: False

profile

Profile to use from .synapseConfig (default: "default").

TYPE: str DEFAULT: 'default'

Example: Logging in - Logging in using a specific profile: import synapseclient syn = synapseclient.login(profile="user1) > Welcome, username! You are using the user1 profile

  • Logging in with an authentication token: import synapseclient syn = synapseclient.login(authToken = "your_auth_token")) > Welcome, username!
Source code in synapseclient/client.py
 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
def login(
    self,
    email: str = None,
    silent: bool = False,
    authToken: str = None,
    profile: str = "default",
) -> None:
    """
    Valid combinations of login() arguments:

    - authToken
    - Profile-based authentication (from .synapseConfig)

    If no login arguments are provided or only username is provided, login() will attempt to log in using
     information from these sources (in order of preference):

    1. .synapseConfig file (supports multiple profiles)(in user home folder unless configured otherwise)
    2. User defined arguments during a CLI session
    3. User's Personal Access Token (aka: Synapse Auth Token)
        from the environment variable: SYNAPSE_AUTH_TOKEN
    4. Retrieves user's authentication token from AWS SSM Parameter store (if configured)

    Arguments:
        email (str): Synapse user name (or an email address associated with a Synapse account)
        authToken (str): A bearer authorization token, e.g. a
            [personal access token](https://python-docs.synapse.org/tutorials/authentication/).
        silent (bool): Defaults to False.  Suppresses the "Welcome ...!" message.
        profile (str): Profile to use from .synapseConfig (default: "default").

    Example: Logging in
    - Logging in using a specific profile:
            import synapseclient
            syn = synapseclient.login(profile="user1)
            > Welcome, username! You are using the user1 profile

    - Logging in with an authentication token:
        import synapseclient
        syn = synapseclient.login(authToken = "your_auth_token"))
        > Welcome, username!
    """
    # Note: the order of the logic below reflects the ordering in the docstring above.

    # Check version before logging in
    if not self.skip_checks:
        version_check(logger=self.logger)

    # Make sure to invalidate the existing session
    self.logout()

    user_login_args = UserLoginArgs(
        profile=profile, username=email, auth_token=authToken
    )
    credential_provider_chain = get_default_credential_chain()
    self.credentials = credential_provider_chain.get_credentials(
        syn=self, user_login_args=user_login_args
    )

    # Final check on login success
    if not self.credentials:
        raise SynapseNoCredentialsError(
            f"No valid authentication credentials provided.\n"
            f"Tried profile: '{profile}', email: '{email or 'N/A'}'.\n"
            "Check your `.synapseConfig` or ensure the provided auth token is valid."
        )

    if not silent:
        display_name = self.credentials.displayname or self.credentials.username
        if (
            not self.credentials.profile_name
            or self.credentials.profile_name.lower()
            == config_file_constants.AUTHENTICATION_SECTION_NAME
        ):
            self.logger.info(f"Welcome, {display_name}!\n")
        else:
            self.logger.info(
                f"Welcome, {display_name}! You are using the '{self.credentials.profile_name}' profile."
            )

logout

logout() -> None

Removes authentication information from the Synapse client.

RETURNS DESCRIPTION
None

None

Source code in synapseclient/client.py
1144
1145
1146
1147
1148
1149
1150
1151
def logout(self) -> None:
    """
    Removes authentication information from the Synapse client.

    Returns:
        None
    """
    self.credentials = None

get

get(entity, **kwargs)

Gets a Synapse entity from the repository service.

PARAMETER DESCRIPTION
entity

A Synapse ID (e.g. syn123 or syn123.1, with .1 denoting version), a Synapse Entity object, a plain dictionary in which 'id' maps to a Synapse ID or a local file that is stored in Synapse (found by the file MD5)

version

The specific version to get. Defaults to the most recent version. If not denoted in the entity input.

downloadFile

Whether associated files(s) should be downloaded. Defaults to True.

downloadLocation

Directory where to download the Synapse File Entity. Defaults to the local cache.

followLink

Whether the link returns the target Entity. Defaults to False.

ifcollision

Determines how to handle file collisions. May be "overwrite.local", "keep.local", or "keep.both". Defaults to "keep.both".

limitSearch

A Synanpse ID used to limit the search in Synapse if entity is specified as a local file. That is, if the file is stored in multiple locations in Synapse only the ones in the specified folder/project will be returned.

md5

The MD5 checksum for the file, if known. Otherwise if the file is a local file, it will be calculated automatically.

RETURNS DESCRIPTION

A new Synapse Entity object of the appropriate type.

Using this function

Download file into cache

entity = syn.get('syn1906479')
print(entity.name)
print(entity.path)

Download file into current working directory

entity = syn.get('syn1906479', downloadLocation='.')
print(entity.name)
print(entity.path)

Determine the provenance of a locally stored file as indicated in Synapse

entity = syn.get('/path/to/file.txt', limitSearch='syn12312')
print(syn.getProvenance(entity))
Source code in synapseclient/client.py
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
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import get` instead.",
)
def get(self, entity, **kwargs):
    """
    Gets a Synapse entity from the repository service.

    Arguments:
        entity:           A Synapse ID (e.g. syn123 or syn123.1, with .1 denoting version), a Synapse Entity object,
                          a plain dictionary in which 'id' maps to a Synapse ID or a local file that is stored in
                          Synapse (found by the file MD5)
        version:          The specific version to get.
                            Defaults to the most recent version. If not denoted in the entity input.
        downloadFile:     Whether associated files(s) should be downloaded.
                            Defaults to True.
        downloadLocation: Directory where to download the Synapse File Entity.
                            Defaults to the local cache.
        followLink:       Whether the link returns the target Entity.
                            Defaults to False.
        ifcollision:      Determines how to handle file collisions.
                            May be "overwrite.local", "keep.local", or "keep.both".
                            Defaults to "keep.both".
        limitSearch:      A Synanpse ID used to limit the search in Synapse if entity is specified as a local
                            file.  That is, if the file is stored in multiple locations in Synapse only the ones
                            in the specified folder/project will be returned.
        md5: The MD5 checksum for the file, if known. Otherwise if the file is a
            local file, it will be calculated automatically.

    Returns:
        A new Synapse Entity object of the appropriate type.

    Example: Using this function
        Download file into cache

            entity = syn.get('syn1906479')
            print(entity.name)
            print(entity.path)

        Download file into current working directory

            entity = syn.get('syn1906479', downloadLocation='.')
            print(entity.name)
            print(entity.path)

        Determine the provenance of a locally stored file as indicated in Synapse

            entity = syn.get('/path/to/file.txt', limitSearch='syn12312')
            print(syn.getProvenance(entity))
    """
    return wrap_async_to_sync(self.get_async(entity, **kwargs))

store

store(obj, *, createOrUpdate=True, forceVersion=True, versionLabel=None, isRestricted=False, activity=None, used=None, executed=None, activityName=None, activityDescription=None, set_annotations=True)

Creates a new Entity or updates an existing Entity, uploading any files in the process.

PARAMETER DESCRIPTION
obj

A Synapse Entity, Evaluation, or Wiki

used

The Entity, Synapse ID, or URL used to create the object (can also be a list of these)

DEFAULT: None

executed

The Entity, Synapse ID, or URL representing code executed to create the object (can also be a list of these)

DEFAULT: None

activity

Activity object specifying the user's provenance.

DEFAULT: None

activityName

Activity name to be used in conjunction with used and executed.

DEFAULT: None

activityDescription

Activity description to be used in conjunction with used and executed.

DEFAULT: None

createOrUpdate

Indicates whether the method should automatically perform an update if the 'obj' conflicts with an existing Synapse object.

DEFAULT: True

forceVersion

Indicates whether the method should increment the version of the object even if nothing has changed.

DEFAULT: True

versionLabel

Arbitrary string used to label the version.

DEFAULT: None

isRestricted

If set to true, an email will be sent to the Synapse access control team to start the process of adding terms-of-use or review board approval for this entity. You will be contacted with regards to the specific data being restricted and the requirements of access.

DEFAULT: False

set_annotations

If True, set the annotations on the entity. If False, do not set the annotations.

DEFAULT: True

RETURNS DESCRIPTION

A Synapse Entity, Evaluation, or Wiki

Using this function

Creating a new Project:

from synapseclient import Project

project = Project('My uniquely named project')
project = syn.store(project)

Adding files with provenance (aka: Activity):

from synapseclient import File, Activity

A synapse entity syn1906480 contains data and an entity syn1917825 contains code

activity = Activity(
    'Fancy Processing',
    description='No seriously, really fancy processing',
    used=['syn1906480', 'http://data_r_us.com/fancy/data.txt'],
    executed='syn1917825')

test_entity = File('/path/to/data/file.xyz', description='Fancy new data', parent=project)
test_entity = syn.store(test_entity, activity=activity)
Source code in synapseclient/client.py
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
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import store` instead.",
)
def store(
    self,
    obj,
    *,
    createOrUpdate=True,
    forceVersion=True,
    versionLabel=None,
    isRestricted=False,
    activity=None,
    used=None,
    executed=None,
    activityName=None,
    activityDescription=None,
    set_annotations=True,
):
    """
    Creates a new Entity or updates an existing Entity, uploading any files in the process.

    Arguments:
        obj: A Synapse Entity, Evaluation, or Wiki
        used: The Entity, Synapse ID, or URL used to create the object (can also be a list of these)
        executed: The Entity, Synapse ID, or URL representing code executed to create the object
                    (can also be a list of these)
        activity: Activity object specifying the user's provenance.
        activityName: Activity name to be used in conjunction with *used* and *executed*.
        activityDescription: Activity description to be used in conjunction with *used* and *executed*.
        createOrUpdate: Indicates whether the method should automatically perform an update if the 'obj'
                        conflicts with an existing Synapse object.
        forceVersion: Indicates whether the method should increment the version of the object even if nothing
                        has changed.
        versionLabel: Arbitrary string used to label the version.
        isRestricted: If set to true, an email will be sent to the Synapse access control team to start the
                        process of adding terms-of-use or review board approval for this entity.
                        You will be contacted with regards to the specific data being restricted and the
                        requirements of access.
        set_annotations: If True, set the annotations on the entity. If False, do not set the annotations.

    Returns:
        A Synapse Entity, Evaluation, or Wiki

    Example: Using this function
        Creating a new Project:

            from synapseclient import Project

            project = Project('My uniquely named project')
            project = syn.store(project)

        Adding files with [provenance (aka: Activity)][synapseclient.Activity]:

            from synapseclient import File, Activity

        A synapse entity *syn1906480* contains data and an entity *syn1917825* contains code

            activity = Activity(
                'Fancy Processing',
                description='No seriously, really fancy processing',
                used=['syn1906480', 'http://data_r_us.com/fancy/data.txt'],
                executed='syn1917825')

            test_entity = File('/path/to/data/file.xyz', description='Fancy new data', parent=project)
            test_entity = syn.store(test_entity, activity=activity)

    """
    return wrap_async_to_sync(
        coroutine=self.store_async(
            obj,
            createOrUpdate=createOrUpdate,
            forceVersion=forceVersion,
            versionLabel=versionLabel,
            isRestricted=isRestricted,
            activity=activity,
            used=used,
            executed=executed,
            activityName=activityName,
            activityDescription=activityDescription,
            set_annotations=set_annotations,
        )
    )

move

move(entity, new_parent)

Deprecated with replacement. This method will be removed in 5.0.0. Use the new dataclass models (File, Folder, Table, etc.) with their parent_id attribute and .store() method instead.

Move a Synapse entity to a new container.

PARAMETER DESCRIPTION
entity

A Synapse ID, a Synapse Entity object, or a local file that is stored in Synapse

new_parent

The new parent container (Folder or Project) to which the entity should be moved.

RETURNS DESCRIPTION

The Synapse Entity object that has been moved.

Using this function (DEPRECATED)

Move a Synapse Entity object to a new parent container

entity = syn.move('syn456', 'syn123')
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import (
    File, Folder, Table, Dataset, DatasetCollection,
    EntityView, SubmissionView, MaterializedView, VirtualTable
)

# Login to Synapse
syn = Synapse()
syn.login()

# Moving a File
file = File(id="syn456", download_file=False).get()
file.parent_id = "syn123"
file = file.store()
print(f"Moved file to: {file.parent_id}")

# Moving a Folder
folder = Folder(id="syn789").get()
folder.parent_id = "syn123"
folder = folder.store()
print(f"Moved folder to: {folder.parent_id}")

# Moving a Table
table = Table(id="syn101112").get()
table.parent_id = "syn123"
table = table.store()
print(f"Moved table to: {table.parent_id}")

# Moving a Dataset
dataset = Dataset(id="syn131415").get()
dataset.parent_id = "syn123"
dataset = dataset.store()
print(f"Moved dataset to: {dataset.parent_id}")

# Moving a DatasetCollection
dataset_collection = DatasetCollection(id="syn161718").get()
dataset_collection.parent_id = "syn123"
dataset_collection = dataset_collection.store()
print(f"Moved dataset collection to: {dataset_collection.parent_id}")

# Moving an EntityView
entity_view = EntityView(id="syn192021").get()
entity_view.parent_id = "syn123"
entity_view = entity_view.store()
print(f"Moved entity view to: {entity_view.parent_id}")

# Moving a SubmissionView
submission_view = SubmissionView(id="syn222324").get()
submission_view.parent_id = "syn123"
submission_view = submission_view.store()
print(f"Moved submission view to: {submission_view.parent_id}")

# Moving a MaterializedView
materialized_view = MaterializedView(id="syn252627").get()
materialized_view.parent_id = "syn123"
materialized_view = materialized_view.store()
print(f"Moved materialized view to: {materialized_view.parent_id}")

# Moving a VirtualTable
virtual_table = VirtualTable(id="syn282930").get()
virtual_table.parent_id = "syn123"
virtual_table = virtual_table.store()
print(f"Moved virtual table to: {virtual_table.parent_id}")
Source code in synapseclient/client.py
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
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "This method uses legacy Entity objects. "
    "Use the new dataclass models (File, Folder, Table, etc.) with their `parent_id` attribute and `.store()` method instead. ",
)
def move(self, entity, new_parent):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the new dataclass models (File, Folder, Table, etc.) with their `parent_id`
    attribute and `.store()` method instead.

    Move a Synapse entity to a new container.

    Arguments:
        entity:     A Synapse ID, a Synapse Entity object, or a local file that is stored in Synapse
        new_parent: The new parent container (Folder or Project) to which the entity should be moved.

    Returns:
        The Synapse Entity object that has been moved.

    Example: Using this function (DEPRECATED)
        Move a Synapse Entity object to a new parent container

            entity = syn.move('syn456', 'syn123')

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            File, Folder, Table, Dataset, DatasetCollection,
            EntityView, SubmissionView, MaterializedView, VirtualTable
        )

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Moving a File
        file = File(id="syn456", download_file=False).get()
        file.parent_id = "syn123"
        file = file.store()
        print(f"Moved file to: {file.parent_id}")

        # Moving a Folder
        folder = Folder(id="syn789").get()
        folder.parent_id = "syn123"
        folder = folder.store()
        print(f"Moved folder to: {folder.parent_id}")

        # Moving a Table
        table = Table(id="syn101112").get()
        table.parent_id = "syn123"
        table = table.store()
        print(f"Moved table to: {table.parent_id}")

        # Moving a Dataset
        dataset = Dataset(id="syn131415").get()
        dataset.parent_id = "syn123"
        dataset = dataset.store()
        print(f"Moved dataset to: {dataset.parent_id}")

        # Moving a DatasetCollection
        dataset_collection = DatasetCollection(id="syn161718").get()
        dataset_collection.parent_id = "syn123"
        dataset_collection = dataset_collection.store()
        print(f"Moved dataset collection to: {dataset_collection.parent_id}")

        # Moving an EntityView
        entity_view = EntityView(id="syn192021").get()
        entity_view.parent_id = "syn123"
        entity_view = entity_view.store()
        print(f"Moved entity view to: {entity_view.parent_id}")

        # Moving a SubmissionView
        submission_view = SubmissionView(id="syn222324").get()
        submission_view.parent_id = "syn123"
        submission_view = submission_view.store()
        print(f"Moved submission view to: {submission_view.parent_id}")

        # Moving a MaterializedView
        materialized_view = MaterializedView(id="syn252627").get()
        materialized_view.parent_id = "syn123"
        materialized_view = materialized_view.store()
        print(f"Moved materialized view to: {materialized_view.parent_id}")

        # Moving a VirtualTable
        virtual_table = VirtualTable(id="syn282930").get()
        virtual_table.parent_id = "syn123"
        virtual_table = virtual_table.store()
        print(f"Moved virtual table to: {virtual_table.parent_id}")
        ```
    """

    entity = self.get(entity, downloadFile=False)
    entity.parentId = id_of(new_parent)
    entity = self.store(entity, forceVersion=False)
    trace.get_current_span().set_attributes(
        {
            "synapse.id": entity.get("id", ""),
            "synapse.parent_id": entity.get("parentId", ""),
        }
    )

    return entity

delete

delete(obj, version=None)

Removes an object from Synapse.

PARAMETER DESCRIPTION
obj

An existing object stored on Synapse such as Evaluation, File, Project, or Wiki

version

For entities, specify a particular version to delete.

DEFAULT: None

Source code in synapseclient/client.py
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import delete` instead.",
)
def delete(
    self,
    obj,
    version=None,
):
    """
    Removes an object from Synapse.

    Arguments:
        obj: An existing object stored on Synapse such as Evaluation, File, Project, or Wiki
        version: For entities, specify a particular version to delete.
    """
    # Handle all strings as the Entity ID for backward compatibility
    if isinstance(obj, str):
        entity_id = id_of(obj)
        trace.get_current_span().set_attributes({"synapse.id": entity_id})
        if version:
            self.restDELETE(uri=f"/entity/{entity_id}/version/{version}")
        else:
            self.restDELETE(uri=f"/entity/{entity_id}")
    elif hasattr(obj, "_synapse_delete"):
        return obj._synapse_delete(self)
    else:
        try:
            if isinstance(obj, Versionable):
                self.restDELETE(obj.deleteURI(versionNumber=version))
            else:
                self.restDELETE(obj.deleteURI())
        except AttributeError:
            raise SynapseError(
                f"Can't delete a {type(obj)}. Please specify a Synapse object or id"
            )

get_annotations

get_annotations(entity: Union[str, Entity], version: Union[str, int] = None) -> Annotations

Retrieve annotations for an Entity from the Synapse Repository as a Python dict.

Note that collapsing annotations from the native Synapse format to a Python dict may involve some loss of information. See _getRawAnnotations to get annotations in the native format.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to lookup

TYPE: Union[str, Entity]

version

The version of the Entity to retrieve.

TYPE: Union[str, int] DEFAULT: None

RETURNS DESCRIPTION
Annotations

A synapseclient.annotations.Annotations object, a dict that also has id and etag attributes

Migrating from this method to dataclass models

Legacy approach (deprecated):

# Get the File entity first
file_entity = syn.get("syn123")

# Get annotations separately
annotations = syn.get_annotations(file_entity)
print(annotations)

New approach using dataclass models:

import synapseclient
from synapseclient.models import (
    File, Folder, Project, Table, EntityView, Dataset,
    DatasetCollection, MaterializedView, SubmissionView, VirtualTable
)

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# File - don't download the file content, just get metadata
file_instance = File(id="syn12345", download_file=False)
file_instance = file_instance.get()
print(f"File annotations: {file_instance.annotations}")

# Folder
folder_instance = Folder(id="syn11111")
folder_instance = folder_instance.get()
print(f"Folder annotations: {folder_instance.annotations}")

# Project
project_instance = Project(id="syn22222")
project_instance = project_instance.get()
print(f"Project annotations: {project_instance.annotations}")

# Table
table_instance = Table(id="syn33333")
table_instance = table_instance.get()
print(f"Table annotations: {table_instance.annotations}")

# EntityView
view_instance = EntityView(id="syn44444")
view_instance = view_instance.get()
print(f"EntityView annotations: {view_instance.annotations}")

# Dataset
dataset_instance = Dataset(id="syn55555")
dataset_instance = dataset_instance.get()
print(f"Dataset annotations: {dataset_instance.annotations}")

# DatasetCollection
collection_instance = DatasetCollection(id="syn66666")
collection_instance = collection_instance.get()
print(f"DatasetCollection annotations: {collection_instance.annotations}")

# MaterializedView
mat_view_instance = MaterializedView(id="syn77777")
mat_view_instance = mat_view_instance.get()
print(f"MaterializedView annotations: {mat_view_instance.annotations}")

# SubmissionView
sub_view_instance = SubmissionView(id="syn88888")
sub_view_instance = sub_view_instance.get()
print(f"SubmissionView annotations: {sub_view_instance.annotations}")

# VirtualTable
virtual_table_instance = VirtualTable(id="syn99999")
virtual_table_instance = virtual_table_instance.get()
print(f"VirtualTable annotations: {virtual_table_instance.annotations}")

# Access specific annotation values
# annotations is always a dict by default (empty {} if no annotations exist)
species = file_instance.annotations.get("species", [])
data_type = file_instance.annotations.get("dataType", [])
print(f"Species: {species}, Data type: {data_type}")

# Check if a specific annotation exists
if species:
    print(f"Species annotation exists: {species}")
else:
    print("Species annotation not found")

# Get all annotation keys
annotation_keys = list(file_instance.annotations.keys())
print(f"Available annotation keys: {annotation_keys}")

Source code in synapseclient/client.py
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. Use the dataclass model attributes instead. "
    "All dataclass models support annotations: File, Folder, Project, Table, EntityView, Dataset, "
    "DatasetCollection, MaterializedView, SubmissionView, VirtualTable. "
    "Access annotations directly via `instance.annotations` attribute.",
)
def get_annotations(
    self, entity: typing.Union[str, Entity], version: typing.Union[str, int] = None
) -> Annotations:
    """
    Retrieve annotations for an Entity from the Synapse Repository as a Python dict.

    Note that collapsing annotations from the native Synapse format to a Python dict may involve some loss of
    information. See `_getRawAnnotations` to get annotations in the native format.

    Arguments:
        entity: An Entity or Synapse ID to lookup
        version: The version of the Entity to retrieve.

    Returns:
        A [synapseclient.annotations.Annotations][] object, a dict that also has id and etag attributes

    Example: Migrating from this method to dataclass models
        **Legacy approach (deprecated):**
        ```python
        # Get the File entity first
        file_entity = syn.get("syn123")

        # Get annotations separately
        annotations = syn.get_annotations(file_entity)
        print(annotations)
        ```

        **New approach using dataclass models:**
        ```python
        import synapseclient
        from synapseclient.models import (
            File, Folder, Project, Table, EntityView, Dataset,
            DatasetCollection, MaterializedView, SubmissionView, VirtualTable
        )

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # File - don't download the file content, just get metadata
        file_instance = File(id="syn12345", download_file=False)
        file_instance = file_instance.get()
        print(f"File annotations: {file_instance.annotations}")

        # Folder
        folder_instance = Folder(id="syn11111")
        folder_instance = folder_instance.get()
        print(f"Folder annotations: {folder_instance.annotations}")

        # Project
        project_instance = Project(id="syn22222")
        project_instance = project_instance.get()
        print(f"Project annotations: {project_instance.annotations}")

        # Table
        table_instance = Table(id="syn33333")
        table_instance = table_instance.get()
        print(f"Table annotations: {table_instance.annotations}")

        # EntityView
        view_instance = EntityView(id="syn44444")
        view_instance = view_instance.get()
        print(f"EntityView annotations: {view_instance.annotations}")

        # Dataset
        dataset_instance = Dataset(id="syn55555")
        dataset_instance = dataset_instance.get()
        print(f"Dataset annotations: {dataset_instance.annotations}")

        # DatasetCollection
        collection_instance = DatasetCollection(id="syn66666")
        collection_instance = collection_instance.get()
        print(f"DatasetCollection annotations: {collection_instance.annotations}")

        # MaterializedView
        mat_view_instance = MaterializedView(id="syn77777")
        mat_view_instance = mat_view_instance.get()
        print(f"MaterializedView annotations: {mat_view_instance.annotations}")

        # SubmissionView
        sub_view_instance = SubmissionView(id="syn88888")
        sub_view_instance = sub_view_instance.get()
        print(f"SubmissionView annotations: {sub_view_instance.annotations}")

        # VirtualTable
        virtual_table_instance = VirtualTable(id="syn99999")
        virtual_table_instance = virtual_table_instance.get()
        print(f"VirtualTable annotations: {virtual_table_instance.annotations}")

        # Access specific annotation values
        # annotations is always a dict by default (empty {} if no annotations exist)
        species = file_instance.annotations.get("species", [])
        data_type = file_instance.annotations.get("dataType", [])
        print(f"Species: {species}, Data type: {data_type}")

        # Check if a specific annotation exists
        if species:
            print(f"Species annotation exists: {species}")
        else:
            print("Species annotation not found")

        # Get all annotation keys
        annotation_keys = list(file_instance.annotations.keys())
        print(f"Available annotation keys: {annotation_keys}")
        ```
    """
    return from_synapse_annotations(self._getRawAnnotations(entity, version))

set_annotations

set_annotations(annotations: Annotations)

Store annotations for an Entity in the Synapse Repository.

PARAMETER DESCRIPTION
annotations

A synapseclient.annotations.Annotations of annotation names and values, with the id and etag attribute set

TYPE: Annotations

RETURNS DESCRIPTION

The updated synapseclient.annotations.Annotations for the entity

Migrating from this method to dataclass models

Legacy approach (deprecated):

# Get annotations, modify, and set back
annos = syn.get_annotations('syn12345')
annos['foo'] = ['bar', 'baz']
annos['qwerty'] = 'asdf'
annos = syn.set_annotations(annos)
print(annos)

New approach using dataclass models:

In this example all of these updates are destructive, meaning they will overwrite any existing annotations. If you want to merge annotations instead, see the merging example below.

import synapseclient
from synapseclient.models import (
    File, Folder, Project, Table, EntityView, Dataset,
    DatasetCollection, MaterializedView, SubmissionView, VirtualTable
)

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# File - don't download the file content, just get metadata
file_instance = File(id="syn12345", download_file=False)
file_instance = file_instance.get()
file_instance.annotations = {
    "foo": ["bar", "baz"],
    "qwerty": ["asdf"],
    "species": ["Homo sapiens"]
}
file_instance = file_instance.store()
print(f"File annotations: {file_instance.annotations}")

# Folder
folder_instance = Folder(id="syn11111")
folder_instance = folder_instance.get()
folder_instance.annotations = {
    "category": ["research"],
    "department": ["biology"]
}
folder_instance = folder_instance.store()
print(f"Folder annotations: {folder_instance.annotations}")

# Project
project_instance = Project(id="syn22222")
project_instance = project_instance.get()
project_instance.annotations = {
    "funding": ["NIH"],
    "grant_number": ["R01-12345"]
}
project_instance = project_instance.store()
print(f"Project annotations: {project_instance.annotations}")

# Table
table_instance = Table(id="syn33333")
table_instance = table_instance.get()
table_instance.annotations = {
    "version": ["1.0"],
    "data_type": ["clinical"]
}
table_instance = table_instance.store()
print(f"Table annotations: {table_instance.annotations}")

# EntityView
view_instance = EntityView(id="syn44444")
view_instance = view_instance.get()
view_instance.annotations = {
    "scope": ["project_wide"],
    "view_type": ["file_view"]
}
view_instance = view_instance.store()
print(f"EntityView annotations: {view_instance.annotations}")

# Dataset
dataset_instance = Dataset(id="syn55555")
dataset_instance = dataset_instance.get()
dataset_instance.annotations = {
    "dataset_type": ["genomic"],
    "size": ["large"]
}
dataset_instance = dataset_instance.store()
print(f"Dataset annotations: {dataset_instance.annotations}")

# DatasetCollection
collection_instance = DatasetCollection(id="syn66666")
collection_instance = collection_instance.get()
collection_instance.annotations = {
    "collection_type": ["multi_omics"],
    "studies": ["3"]
}
collection_instance = collection_instance.store()
print(f"DatasetCollection annotations: {collection_instance.annotations}")

# MaterializedView
mat_view_instance = MaterializedView(id="syn77777")
mat_view_instance = mat_view_instance.get()
mat_view_instance.annotations = {
    "refresh_frequency": ["daily"],
    "data_source": ["clinical_db"]
}
mat_view_instance = mat_view_instance.store()
print(f"MaterializedView annotations: {mat_view_instance.annotations}")

# SubmissionView
sub_view_instance = SubmissionView(id="syn88888")
sub_view_instance = sub_view_instance.get()
sub_view_instance.annotations = {
    "evaluation_queue": ["challenge_2024"],
    "status": ["active"]
}
sub_view_instance = sub_view_instance.store()
print(f"SubmissionView annotations: {sub_view_instance.annotations}")

# VirtualTable
virtual_table_instance = VirtualTable(id="syn99999")
virtual_table_instance = virtual_table_instance.get()
virtual_table_instance.annotations = {
    "virtual_type": ["federated"],
    "source_count": ["5"]
}
virtual_table_instance = virtual_table_instance.store()
print(f"VirtualTable annotations: {virtual_table_instance.annotations}")

For merging with existing annotations:

import synapseclient
from synapseclient.models import File, Folder

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# Get existing annotations and merge for File
file_instance = File(id="syn12345", download_file=False)
file_instance = file_instance.get()

# Merge with existing annotations (annotations is always a dict by default)
file_instance.annotations.update({
    "foo": ["bar", "baz"],
    "qwerty": ["asdf"]
})

# Store the updated File
file_instance = file_instance.store()
print(f"Updated file annotations: {file_instance.annotations}")

# Same pattern works for all other dataclass models
folder_instance = Folder(id="syn11111")
folder_instance = folder_instance.get()
folder_instance.annotations.update({"new_key": ["new_value"]})
folder_instance = folder_instance.store()
print(f"Updated folder annotations: {folder_instance.annotations}")

For updating single annotation values:

import synapseclient
from synapseclient.models import File

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# Update a single annotation value while preserving existing annotations
file_instance = File(id="syn12345", download_file=False)
file_instance = file_instance.get()

# annotations is always a dict by default (empty {} if no annotations exist)
# You can directly access and modify annotation values
file_instance.annotations["species"] = ["Mus musculus"]
file_instance.annotations["data_type"] = ["RNA-seq"]

# Store the updated File
file_instance = file_instance.store()
print(f"Updated file annotations: {file_instance.annotations}")

IMPORTANT - Destructive vs Non-destructive updates:

import synapseclient
from synapseclient.models import File

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# When you call .get(), existing annotations are loaded into the instance
file_instance = File(id="syn12345", download_file=False)
file_instance = file_instance.get()
# Now file_instance.annotations contains existing annotations from Synapse

# DESTRUCTIVE UPDATE - This replaces ALL existing annotations
file_instance.annotations = {
    "new_key": ["new_value"]
}
# All previous annotations are lost!

# NON-DESTRUCTIVE UPDATE - This preserves existing annotations
# annotations is always a dict by default (empty {} if no annotations exist)
file_instance.annotations.update({
    "new_key": ["new_value"]
})
# OR modify individual keys:
file_instance.annotations["another_key"] = ["another_value"]
# Previous annotations are preserved

# To remove ALL annotations, set to None or empty dict
file_instance.annotations = None  # Clears all annotations
# OR
file_instance.annotations = {}    # Also clears all annotations

file_instance = file_instance.store()

Using this function (DEPRECATED)

Getting annotations, adding a new annotation, and updating the annotations:

annos = syn.get_annotations('syn123')

annos will contain the id and etag associated with the entity upon retrieval

print(annos.id)
> syn123
print(annos.etag)
> 7bdb83e9-a50a-46e4-987a-4962559f090f   (Usually some UUID in the form of a string)

Returned annos object from get_annotations() can be used as if it were a dict. Set key 'foo' to have value of 'bar' and 'baz'

annos['foo'] = ['bar', 'baz']

Single values will automatically be wrapped in a list once stored

annos['qwerty'] = 'asdf'

Store the annotations

annos = syn.set_annotations(annos)

print(annos)
> {'foo':['bar','baz], 'qwerty':['asdf']}
Source code in synapseclient/client.py
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. Use the dataclass model attributes instead. "
    "All dataclass models support annotations: File, Folder, Project, Table, EntityView, Dataset, "
    "DatasetCollection, MaterializedView, SubmissionView, VirtualTable. "
    "Set annotations via `instance.annotations = {...}` then call `instance.store()`.",
)
def set_annotations(self, annotations: Annotations):
    """
    Store annotations for an Entity in the Synapse Repository.

    Arguments:
        annotations: A [synapseclient.annotations.Annotations][] of annotation names and values,
                        with the id and etag attribute set

    Returns:
        The updated [synapseclient.annotations.Annotations][] for the entity

    Example: Migrating from this method to dataclass models
        **Legacy approach (deprecated):**
        ```python
        # Get annotations, modify, and set back
        annos = syn.get_annotations('syn12345')
        annos['foo'] = ['bar', 'baz']
        annos['qwerty'] = 'asdf'
        annos = syn.set_annotations(annos)
        print(annos)
        ```

        **New approach using dataclass models:**

        In this example all of these updates are destructive, meaning they will
        overwrite any existing annotations. If you want to merge annotations
        instead, see the merging example below.
        ```python
        import synapseclient
        from synapseclient.models import (
            File, Folder, Project, Table, EntityView, Dataset,
            DatasetCollection, MaterializedView, SubmissionView, VirtualTable
        )

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # File - don't download the file content, just get metadata
        file_instance = File(id="syn12345", download_file=False)
        file_instance = file_instance.get()
        file_instance.annotations = {
            "foo": ["bar", "baz"],
            "qwerty": ["asdf"],
            "species": ["Homo sapiens"]
        }
        file_instance = file_instance.store()
        print(f"File annotations: {file_instance.annotations}")

        # Folder
        folder_instance = Folder(id="syn11111")
        folder_instance = folder_instance.get()
        folder_instance.annotations = {
            "category": ["research"],
            "department": ["biology"]
        }
        folder_instance = folder_instance.store()
        print(f"Folder annotations: {folder_instance.annotations}")

        # Project
        project_instance = Project(id="syn22222")
        project_instance = project_instance.get()
        project_instance.annotations = {
            "funding": ["NIH"],
            "grant_number": ["R01-12345"]
        }
        project_instance = project_instance.store()
        print(f"Project annotations: {project_instance.annotations}")

        # Table
        table_instance = Table(id="syn33333")
        table_instance = table_instance.get()
        table_instance.annotations = {
            "version": ["1.0"],
            "data_type": ["clinical"]
        }
        table_instance = table_instance.store()
        print(f"Table annotations: {table_instance.annotations}")

        # EntityView
        view_instance = EntityView(id="syn44444")
        view_instance = view_instance.get()
        view_instance.annotations = {
            "scope": ["project_wide"],
            "view_type": ["file_view"]
        }
        view_instance = view_instance.store()
        print(f"EntityView annotations: {view_instance.annotations}")

        # Dataset
        dataset_instance = Dataset(id="syn55555")
        dataset_instance = dataset_instance.get()
        dataset_instance.annotations = {
            "dataset_type": ["genomic"],
            "size": ["large"]
        }
        dataset_instance = dataset_instance.store()
        print(f"Dataset annotations: {dataset_instance.annotations}")

        # DatasetCollection
        collection_instance = DatasetCollection(id="syn66666")
        collection_instance = collection_instance.get()
        collection_instance.annotations = {
            "collection_type": ["multi_omics"],
            "studies": ["3"]
        }
        collection_instance = collection_instance.store()
        print(f"DatasetCollection annotations: {collection_instance.annotations}")

        # MaterializedView
        mat_view_instance = MaterializedView(id="syn77777")
        mat_view_instance = mat_view_instance.get()
        mat_view_instance.annotations = {
            "refresh_frequency": ["daily"],
            "data_source": ["clinical_db"]
        }
        mat_view_instance = mat_view_instance.store()
        print(f"MaterializedView annotations: {mat_view_instance.annotations}")

        # SubmissionView
        sub_view_instance = SubmissionView(id="syn88888")
        sub_view_instance = sub_view_instance.get()
        sub_view_instance.annotations = {
            "evaluation_queue": ["challenge_2024"],
            "status": ["active"]
        }
        sub_view_instance = sub_view_instance.store()
        print(f"SubmissionView annotations: {sub_view_instance.annotations}")

        # VirtualTable
        virtual_table_instance = VirtualTable(id="syn99999")
        virtual_table_instance = virtual_table_instance.get()
        virtual_table_instance.annotations = {
            "virtual_type": ["federated"],
            "source_count": ["5"]
        }
        virtual_table_instance = virtual_table_instance.store()
        print(f"VirtualTable annotations: {virtual_table_instance.annotations}")
        ```

        **For merging with existing annotations:**
        ```python
        import synapseclient
        from synapseclient.models import File, Folder

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # Get existing annotations and merge for File
        file_instance = File(id="syn12345", download_file=False)
        file_instance = file_instance.get()

        # Merge with existing annotations (annotations is always a dict by default)
        file_instance.annotations.update({
            "foo": ["bar", "baz"],
            "qwerty": ["asdf"]
        })

        # Store the updated File
        file_instance = file_instance.store()
        print(f"Updated file annotations: {file_instance.annotations}")

        # Same pattern works for all other dataclass models
        folder_instance = Folder(id="syn11111")
        folder_instance = folder_instance.get()
        folder_instance.annotations.update({"new_key": ["new_value"]})
        folder_instance = folder_instance.store()
        print(f"Updated folder annotations: {folder_instance.annotations}")
        ```

        **For updating single annotation values:**
        ```python
        import synapseclient
        from synapseclient.models import File

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # Update a single annotation value while preserving existing annotations
        file_instance = File(id="syn12345", download_file=False)
        file_instance = file_instance.get()

        # annotations is always a dict by default (empty {} if no annotations exist)
        # You can directly access and modify annotation values
        file_instance.annotations["species"] = ["Mus musculus"]
        file_instance.annotations["data_type"] = ["RNA-seq"]

        # Store the updated File
        file_instance = file_instance.store()
        print(f"Updated file annotations: {file_instance.annotations}")
        ```

        **IMPORTANT - Destructive vs Non-destructive updates:**
        ```python
        import synapseclient
        from synapseclient.models import File

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # When you call .get(), existing annotations are loaded into the instance
        file_instance = File(id="syn12345", download_file=False)
        file_instance = file_instance.get()
        # Now file_instance.annotations contains existing annotations from Synapse

        # DESTRUCTIVE UPDATE - This replaces ALL existing annotations
        file_instance.annotations = {
            "new_key": ["new_value"]
        }
        # All previous annotations are lost!

        # NON-DESTRUCTIVE UPDATE - This preserves existing annotations
        # annotations is always a dict by default (empty {} if no annotations exist)
        file_instance.annotations.update({
            "new_key": ["new_value"]
        })
        # OR modify individual keys:
        file_instance.annotations["another_key"] = ["another_value"]
        # Previous annotations are preserved

        # To remove ALL annotations, set to None or empty dict
        file_instance.annotations = None  # Clears all annotations
        # OR
        file_instance.annotations = {}    # Also clears all annotations

        file_instance = file_instance.store()
        ```

    Example: Using this function (DEPRECATED)
        Getting annotations, adding a new annotation, and updating the annotations:

            annos = syn.get_annotations('syn123')

        `annos` will contain the id and etag associated with the entity upon retrieval

            print(annos.id)
            > syn123
            print(annos.etag)
            > 7bdb83e9-a50a-46e4-987a-4962559f090f   (Usually some UUID in the form of a string)

        Returned `annos` object from `get_annotations()` can be used as if it were a dict.
        Set key 'foo' to have value of 'bar' and 'baz'

            annos['foo'] = ['bar', 'baz']

        Single values will automatically be wrapped in a list once stored

            annos['qwerty'] = 'asdf'

        Store the annotations

            annos = syn.set_annotations(annos)

            print(annos)
            > {'foo':['bar','baz], 'qwerty':['asdf']}
    """

    if not isinstance(annotations, Annotations):
        raise TypeError("Expected a synapseclient.Annotations object")

    synapseAnnos = to_synapse_annotations(annotations)

    entity_id = id_of(annotations)
    trace.get_current_span().set_attributes({"synapse.id": entity_id})

    return from_synapse_annotations(
        self.restPUT(
            f"/entity/{entity_id}/annotations2",
            body=json.dumps(synapseAnnos),
        )
    )

tableQuery

tableQuery(query: str, resultsAs: str = 'csv', **kwargs)

Deprecated with replacement. This method will be removed in 5.0.0. Use the query or query_async functions from synapseclient.models.Table instead.

Query a Synapse Table.

You can receive query results either as a generator over rows or as a CSV file. For smallish tables, either method will work equally well. Use of a "rowset" generator allows rows to be processed one at a time and processing may be stopped before downloading the entire table.

Optional keyword arguments differ for the two return types of rowset or csv

PARAMETER DESCRIPTION
query

Query string in a SQL-like syntax, for example: "SELECT * from syn12345"

TYPE: str

resultsAs

select whether results are returned as a CSV file ("csv") or incrementally downloaded as sets of rows ("rowset")

TYPE: str DEFAULT: 'csv'

limit

(rowset only) Specify the maximum number of rows to be returned, defaults to None

offset

(rowset only) Don't return the first n rows, defaults to None

quoteCharacter

(csv only) default double quote

escapeCharacter

(csv only) default backslash

lineEnd

(csv only) defaults to os.linesep

separator

(csv only) defaults to comma

header

(csv only) True by default

includeRowIdAndRowVersion

(csv only) True by default

downloadLocation

(csv only) directory path to download the CSV file to

RETURNS DESCRIPTION
NOTE

When performing queries on frequently updated tables, the table can be inaccessible for a period leading to a timeout of the query. Since the results are guaranteed to eventually be returned you can change the max timeout by setting the table_query_timeout variable of the Synapse object:

  # Sets the max timeout to 5 minutes.
  syn.table_query_timeout = 300
Using this function (DEPRECATED)

Getting query results as a DataFrame:

results = syn.tableQuery("SELECT * FROM syn12345")
df = results.asDataFrame()

Getting query results as a CSV file:

results = syn.tableQuery("SELECT * FROM syn12345", resultsAs="csv", downloadLocation="./my_data/")
Migration to new method

 

import asyncio
from synapseclient import Synapse
from synapseclient.models import query, query_async

# Login to Synapse
syn = Synapse()
syn.login()

# Synchronous query (recommended for most use cases)
results = query(query="SELECT * FROM syn12345")
print(results)

# Query with specific options
results = query(
    query="SELECT * FROM syn12345",
    include_row_id_and_row_version=True,
    convert_to_datetime=True
)
print(results)

# Download query results to a CSV file
file_path = query(
    query="SELECT * FROM syn12345",
    download_location="./my_data/",
    separator=",",
    quote_character='"',
    header=True
)
print(f"Results downloaded to: {file_path}")

# Asynchronous query (for advanced use cases)
async def async_query_example():
    results = await query_async(query="SELECT * FROM syn12345")
    print(results)

    # Download query results to a CSV file asynchronously
    file_path = await query_async(
        query="SELECT * FROM syn12345",
        download_location="./my_data/",
        separator=",",
        quote_character='"',
        header=True
    )
    print(f"Results downloaded to: {file_path}")

# Run the async example
asyncio.run(async_query_example())
Source code in synapseclient/client.py
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the `query` functions from `synapseclient.models.Table` instead. "
    "Check the docstring for the replacement function example.",
)
def tableQuery(self, query: str, resultsAs: str = "csv", **kwargs):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `query` or `query_async` functions from [synapseclient.models.Table][] instead.

    Query a Synapse Table.

    You can receive query results either as a generator over rows or as a CSV file. For smallish tables, either
    method will work equally well. Use of a "rowset" generator allows rows to be processed one at a time and
    processing may be stopped before downloading the entire table.

    Optional keyword arguments differ for the two return types of `rowset` or `csv`

    Arguments:
        query: Query string in a [SQL-like syntax](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html), for example: `"SELECT * from syn12345"`
        resultsAs: select whether results are returned as a CSV file ("csv") or incrementally downloaded as sets of rows ("rowset")
        limit: (rowset only) Specify the maximum number of rows to be returned, defaults to None
        offset: (rowset only) Don't return the first n rows, defaults to None
        quoteCharacter: (csv only) default double quote
        escapeCharacter: (csv only) default backslash
        lineEnd: (csv only) defaults to os.linesep
        separator: (csv only) defaults to comma
        header: (csv only) True by default
        includeRowIdAndRowVersion: (csv only) True by default
        downloadLocation: (csv only) directory path to download the CSV file to

    Returns:
        A [TableQueryResult][synapseclient.table.TableQueryResult] or [CsvFileTable][synapseclient.table.CsvFileTable] object

    NOTE:
        When performing queries on frequently updated tables, the table can be inaccessible for a period leading
          to a timeout of the query.  Since the results are guaranteed to eventually be returned you can change the
          max timeout by setting the table_query_timeout variable of the Synapse object:

              # Sets the max timeout to 5 minutes.
              syn.table_query_timeout = 300

    Example: Using this function (DEPRECATED)
        Getting query results as a DataFrame:

            results = syn.tableQuery("SELECT * FROM syn12345")
            df = results.asDataFrame()

        Getting query results as a CSV file:

            results = syn.tableQuery("SELECT * FROM syn12345", resultsAs="csv", downloadLocation="./my_data/")

    Example: Migration to new method
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.models import query, query_async

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Synchronous query (recommended for most use cases)
        results = query(query="SELECT * FROM syn12345")
        print(results)

        # Query with specific options
        results = query(
            query="SELECT * FROM syn12345",
            include_row_id_and_row_version=True,
            convert_to_datetime=True
        )
        print(results)

        # Download query results to a CSV file
        file_path = query(
            query="SELECT * FROM syn12345",
            download_location="./my_data/",
            separator=",",
            quote_character='"',
            header=True
        )
        print(f"Results downloaded to: {file_path}")

        # Asynchronous query (for advanced use cases)
        async def async_query_example():
            results = await query_async(query="SELECT * FROM syn12345")
            print(results)

            # Download query results to a CSV file asynchronously
            file_path = await query_async(
                query="SELECT * FROM syn12345",
                download_location="./my_data/",
                separator=",",
                quote_character='"',
                header=True
            )
            print(f"Results downloaded to: {file_path}")

        # Run the async example
        asyncio.run(async_query_example())
        ```

    """
    if resultsAs.lower() == "rowset":
        return TableQueryResult(self, query, **kwargs)
    elif resultsAs.lower() == "csv":
        # TODO: remove isConsistent because it has now been deprecated
        # from the backend
        if kwargs.get("isConsistent") is not None:
            kwargs.pop("isConsistent")
        return CsvFileTable.from_table_query(self, query, **kwargs)
    else:
        raise ValueError(
            "Unknown return type requested from tableQuery: " + str(resultsAs)
        )

createColumns

createColumns(columns: List[Column]) -> List[Column]

Deprecated with replacement. This method will be removed in 5.0.0. Use the .columns attribute on table-like classes or the add_column method to store columns during the storage of these table-like classes.

Creates a batch of synapseclient.table.Column's within a single request.

PARAMETER DESCRIPTION
columns

TYPE: List[Column]

RETURNS DESCRIPTION
List[Column]

A list of synapseclient.table.Column's that have been created in Synapse

Using this function (DEPRECATED)

Creating multiple columns

columns = [
    Column(name="col1", columnType="STRING"),
    Column(name="col2", columnType="INTEGER")
]
created_columns = syn.createColumns(columns)
Migration to new methods

 

from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, Table
from synapseclient.api.table_services import post_columns
import asyncio

# Login to Synapse
syn = Synapse()
syn.login()

# Method 1: Create columns and add to table using ColumnMixin
columns = [
    Column(name="col1", column_type=ColumnType.STRING),
    Column(name="col2", column_type=ColumnType.INTEGER)
]

# Get an existing table and add the columns
table = Table(id="syn1234").get(include_columns=True)
table.add_column(columns)
table.store()

# Method 2: Create a new table with columns
table = Table(
    name="My Table",
    parent_id="syn5678",
    columns=[
        Column(name="col1", column_type=ColumnType.STRING),
        Column(name="col2", column_type=ColumnType.INTEGER),
    ]
)
table.store()

# Method 3: Use the async post_columns function directly
async def create_columns():
    columns = [
        Column(name="col1", column_type=ColumnType.STRING),
        Column(name="col2", column_type=ColumnType.INTEGER)
    ]
    created_columns = await post_columns(columns)
    return created_columns

# Run the async function
created_columns = asyncio.run(create_columns())
Source code in synapseclient/client.py
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the `.columns` attribute on table-like classes or the `add_column` method to store columns during the storage of these table-like classes. "
    "For batch column operations, use the synapseclient.api.table_services.post_columns function. "
    "Check the docstring for the replacement function example.",
)
def createColumns(self, columns: typing.List[Column]) -> typing.List[Column]:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `.columns` attribute on table-like classes or the `add_column` method to store columns during the storage of these table-like classes.

    Creates a batch of [synapseclient.table.Column][]'s within a single request.

    Arguments:
        columns: A list of [synapseclient.table.Column][]'s

    Returns:
        A list of [synapseclient.table.Column][]'s that have been created in Synapse

    Example: Using this function (DEPRECATED)
        Creating multiple columns

            columns = [
                Column(name="col1", columnType="STRING"),
                Column(name="col2", columnType="INTEGER")
            ]
            created_columns = syn.createColumns(columns)

    Example: Migration to new methods
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Column, ColumnType, Table
        from synapseclient.api.table_services import post_columns
        import asyncio

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Method 1: Create columns and add to table using ColumnMixin
        columns = [
            Column(name="col1", column_type=ColumnType.STRING),
            Column(name="col2", column_type=ColumnType.INTEGER)
        ]

        # Get an existing table and add the columns
        table = Table(id="syn1234").get(include_columns=True)
        table.add_column(columns)
        table.store()

        # Method 2: Create a new table with columns
        table = Table(
            name="My Table",
            parent_id="syn5678",
            columns=[
                Column(name="col1", column_type=ColumnType.STRING),
                Column(name="col2", column_type=ColumnType.INTEGER),
            ]
        )
        table.store()

        # Method 3: Use the async post_columns function directly
        async def create_columns():
            columns = [
                Column(name="col1", column_type=ColumnType.STRING),
                Column(name="col2", column_type=ColumnType.INTEGER)
            ]
            created_columns = await post_columns(columns)
            return created_columns

        # Run the async function
        created_columns = asyncio.run(create_columns())
        ```
    """
    request_body = {
        "concreteType": "org.sagebionetworks.repo.model.ListWrapper",
        "list": list(columns),
    }
    response = self.restPOST("/column/batch", json.dumps(request_body))
    return [Column(**col) for col in response["list"]]

getColumn

getColumn(id)

Deprecated with replacement. This method will be removed in 5.0.0. Use the Column.get() method instead.

Gets a Column object from Synapse by ID.

See: synapseclient.table.Column

PARAMETER DESCRIPTION
id

The ID of the column to retrieve

RETURNS DESCRIPTION

An object of type synapseclient.table.Column

Using this function (DEPRECATED)

Getting a column

column = syn.getColumn(123)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Column

# Login to Synapse
syn = Synapse()
syn.login()

# Get a column by ID
column = Column(id="123").get()
print(f"Column name: {column.name}")
print(f"Column type: {column.column_type}")
print(f"Column ID: {column.id}")
Source code in synapseclient/client.py
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the `Column.get()` method instead. "
    "Check the docstring for the replacement function example.",
)
def getColumn(self, id):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `Column.get()` method instead.

    Gets a Column object from Synapse by ID.

    See: [synapseclient.table.Column][]

    Arguments:
        id: The ID of the column to retrieve

    Returns:
        An object of type [synapseclient.table.Column][]

    Example: Using this function (DEPRECATED)
        Getting a column

            column = syn.getColumn(123)

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Column

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get a column by ID
        column = Column(id="123").get()
        print(f"Column name: {column.name}")
        print(f"Column type: {column.column_type}")
        print(f"Column ID: {column.id}")
        ```
    """
    return Column(**self.restGET(Column.getURI(id)))

getColumns

getColumns(x, limit=100, offset=0)

Deprecated with replacement. This method will be removed in 5.0.0. Use the .columns attribute on table classes or Column.list() method instead.

Get the columns defined in Synapse either (1) corresponding to a set of column headers, (2) those for a given schema, or (3) those whose names start with a given prefix.

PARAMETER DESCRIPTION
x

A list of column headers, a Table Entity object (Schema/EntityViewSchema), a Table's Synapse ID, or a string prefix

limit

Number of columns to retrieve per request to Synapse (pagination parameter). The function will continue retrieving results until all matching columns are returned.

DEFAULT: 100

offset

the index of the first column to return (pagination parameter)

DEFAULT: 0

YIELDS DESCRIPTION

A generator over synapseclient.table.Column objects

Using this function (DEPRECATED)

Getting columns for a table

for column in syn.getColumns("syn12345"):
    print(column.name)

Getting columns with a prefix

for column in syn.getColumns("my_prefix"):
    print(column.name)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Column, Table, EntityView, SubmissionView, Dataset, DatasetCollection

# Login to Synapse
syn = Synapse()
syn.login()

# For getting columns of a specific table/view/dataset
table = Table(id="syn12345")
table = table.get(include_columns=True)
for column_name, column in table.columns.items():
    print(f"Table column: {column_name}, Type: {column.column_type}")

# For EntityView
view = EntityView(id="syn67890")
view = view.get(include_columns=True)
for column_name, column in view.columns.items():
    print(f"EntityView column: {column_name}, Type: {column.column_type}")

# For SubmissionView
submission_view = SubmissionView(id="syn11111")
submission_view = submission_view.get(include_columns=True)
for column_name, column in submission_view.columns.items():
    print(f"SubmissionView column: {column_name}, Type: {column.column_type}")

# For Dataset
dataset = Dataset(id="syn22222")
dataset = dataset.get(include_columns=True)
for column_name, column in dataset.columns.items():
    print(f"Dataset column: {column_name}, Type: {column.column_type}")

# For DatasetCollection
dataset_collection = DatasetCollection(id="syn33333")
dataset_collection = dataset_collection.get(include_columns=True)
for column_name, column in dataset_collection.columns.items():
    print(f"DatasetCollection column: {column_name}, Type: {column.column_type}")

# For listing all columns with a prefix
for column in Column.list(prefix="my_prefix"):
    print(f"Prefixed column: {column.name}, Type: {column.column_type}")

# For listing all columns
for column in Column.list():
    print(f"All columns: {column.name}, Type: {column.column_type}")
Source code in synapseclient/client.py
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "For table columns, use the `.columns` attribute on Table, EntityView, SubmissionView, or Dataset classes after calling `.get(include_columns=True)`. "
    "For column listing and prefix filtering, use the `Column.list()` method. "
    "Check the docstring for the replacement function example.",
)
def getColumns(self, x, limit=100, offset=0):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `.columns` attribute on table classes or `Column.list()` method instead.

    Get the columns defined in Synapse either (1) corresponding to a set of column headers, (2) those for a given
    schema, or (3) those whose names start with a given prefix.

    Arguments:
        x: A list of column headers, a Table Entity object (Schema/EntityViewSchema), a Table's Synapse ID, or a
            string prefix
        limit: Number of columns to retrieve per request to Synapse (pagination parameter).
            The function will continue retrieving results until all matching columns are returned.
        offset: the index of the first column to return (pagination parameter)

    Yields:
        A generator over [synapseclient.table.Column][] objects

    Example: Using this function (DEPRECATED)
        Getting columns for a table

            for column in syn.getColumns("syn12345"):
                print(column.name)

        Getting columns with a prefix

            for column in syn.getColumns("my_prefix"):
                print(column.name)

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Column, Table, EntityView, SubmissionView, Dataset, DatasetCollection

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # For getting columns of a specific table/view/dataset
        table = Table(id="syn12345")
        table = table.get(include_columns=True)
        for column_name, column in table.columns.items():
            print(f"Table column: {column_name}, Type: {column.column_type}")

        # For EntityView
        view = EntityView(id="syn67890")
        view = view.get(include_columns=True)
        for column_name, column in view.columns.items():
            print(f"EntityView column: {column_name}, Type: {column.column_type}")

        # For SubmissionView
        submission_view = SubmissionView(id="syn11111")
        submission_view = submission_view.get(include_columns=True)
        for column_name, column in submission_view.columns.items():
            print(f"SubmissionView column: {column_name}, Type: {column.column_type}")

        # For Dataset
        dataset = Dataset(id="syn22222")
        dataset = dataset.get(include_columns=True)
        for column_name, column in dataset.columns.items():
            print(f"Dataset column: {column_name}, Type: {column.column_type}")

        # For DatasetCollection
        dataset_collection = DatasetCollection(id="syn33333")
        dataset_collection = dataset_collection.get(include_columns=True)
        for column_name, column in dataset_collection.columns.items():
            print(f"DatasetCollection column: {column_name}, Type: {column.column_type}")

        # For listing all columns with a prefix
        for column in Column.list(prefix="my_prefix"):
            print(f"Prefixed column: {column.name}, Type: {column.column_type}")

        # For listing all columns
        for column in Column.list():
            print(f"All columns: {column.name}, Type: {column.column_type}")

        ```
    """
    if x is None:
        uri = "/column"
        for result in self._GET_paginated(uri, limit=limit, offset=offset):
            yield Column(**result)
    elif isinstance(x, (list, tuple)):
        for header in x:
            try:
                # if header is an integer, it's a columnID, otherwise it's an aggregate column, like "AVG(Foo)"
                int(header)
                yield self.getColumn(header)
            except ValueError:
                # ignore aggregate column
                pass
    elif isinstance(x, SchemaBase) or utils.is_synapse_id_str(x):
        for col in self.getTableColumns(x):
            yield col
    elif isinstance(x, str):
        uri = "/column?prefix=" + x
        for result in self._GET_paginated(uri, limit=limit, offset=offset):
            yield Column(**result)
    else:
        ValueError("Can't get columns for a %s" % type(x))

getTableColumns

getTableColumns(table)

Deprecated with replacement. This method will be removed in 5.0.0. Use the columns attribute on synapseclient.models.Table instead.

Retrieve the column models used in the given table schema.

PARAMETER DESCRIPTION
table

The schema of the Table whose columns are to be retrieved

YIELDS DESCRIPTION

A Generator over the Table's columns

Using this function (DEPRECATED)

Getting columns from a table schema:

columns = list(syn.getTableColumns("syn123"))
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Table, Dataset, DatasetCollection, EntityView, SubmissionView

# Login to Synapse
syn = Synapse()
syn.login()

# For Tables
table = Table(id="syn123").get()
columns = list(table.columns.values())
print("Columns in table:", columns)
# Access individual columns by name
my_table_column = table.columns["my_column_name"]

# For Datasets
dataset = Dataset(id="syn456").get()
columns = list(dataset.columns.values())
print("Columns in dataset:", columns)
# Access individual columns by name
my_dataset_column = dataset.columns["my_column_name"]

# For Dataset Collections
dataset_collection = DatasetCollection(id="syn789").get()
columns = list(dataset_collection.columns.values())
print("Columns in dataset collection:", columns)
# Access individual columns by name
my_collection_column = dataset_collection.columns["my_column_name"]

# For Entity Views
entity_view = EntityView(id="syn012").get()
columns = list(entity_view.columns.values())
print("Columns in entity view:", columns)
# Access individual columns by name
my_view_column = entity_view.columns["my_column_name"]

# For Submission Views
submission_view = SubmissionView(id="syn345").get()
columns = list(submission_view.columns.values())
print("Columns in submission view:", columns)
# Access individual columns by name
my_submission_column = submission_view.columns["my_column_name"]
Source code in synapseclient/client.py
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `columns` attribute on the `from synapseclient.models import Table` class. "
    "Check the docstring for the replacement function example.",
)
def getTableColumns(self, table):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `columns` attribute on [synapseclient.models.Table][] instead.

    Retrieve the column models used in the given table schema.

    Arguments:
        table: The schema of the Table whose columns are to be retrieved

    Yields:
        A Generator over the Table's [columns][synapseclient.table.Column]

    Example: Using this function (DEPRECATED)
        Getting columns from a table schema:

            columns = list(syn.getTableColumns("syn123"))

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Table, Dataset, DatasetCollection, EntityView, SubmissionView

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # For Tables
        table = Table(id="syn123").get()
        columns = list(table.columns.values())
        print("Columns in table:", columns)
        # Access individual columns by name
        my_table_column = table.columns["my_column_name"]

        # For Datasets
        dataset = Dataset(id="syn456").get()
        columns = list(dataset.columns.values())
        print("Columns in dataset:", columns)
        # Access individual columns by name
        my_dataset_column = dataset.columns["my_column_name"]

        # For Dataset Collections
        dataset_collection = DatasetCollection(id="syn789").get()
        columns = list(dataset_collection.columns.values())
        print("Columns in dataset collection:", columns)
        # Access individual columns by name
        my_collection_column = dataset_collection.columns["my_column_name"]

        # For Entity Views
        entity_view = EntityView(id="syn012").get()
        columns = list(entity_view.columns.values())
        print("Columns in entity view:", columns)
        # Access individual columns by name
        my_view_column = entity_view.columns["my_column_name"]

        # For Submission Views
        submission_view = SubmissionView(id="syn345").get()
        columns = list(submission_view.columns.values())
        print("Columns in submission view:", columns)
        # Access individual columns by name
        my_submission_column = submission_view.columns["my_column_name"]
        ```
    """
    uri = "/entity/{id}/column".format(id=id_of(table))
    # The returned object type for this service, PaginatedColumnModels, is a misnomer.
    # This service always returns the full list of results so the pagination does not not actually matter.
    for result in self.restGET(uri)["results"]:
        yield Column(**result)

downloadTableColumns

downloadTableColumns(table, columns, downloadLocation=None, **kwargs)

Bulk download of table-associated files.

PARAMETER DESCRIPTION
table

Table query result

columns

A list of column names as strings

downloadLocation

Directory into which to download the files

DEFAULT: None

RETURNS DESCRIPTION

A dictionary from file handle ID to path in the local file system.

For example, consider a Synapse table whose ID is "syn12345" with two columns of type FILEHANDLEID named 'foo' and 'bar'. The associated files are JSON encoded, so we might retrieve the files from Synapse and load for the second 100 of those rows as shown here:

import json

results = syn.tableQuery('SELECT * FROM syn12345 LIMIT 100 OFFSET 100')
file_map = syn.downloadTableColumns(results, ['foo', 'bar'])

for file_handle_id, path in file_map.items():
    with open(path) as f:
        data[file_handle_id] = f.read()
Source code in synapseclient/client.py
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. This function has no replacement.",
)
def downloadTableColumns(self, table, columns, downloadLocation=None, **kwargs):
    """
    Bulk download of table-associated files.

    Arguments:
        table: Table query result
        columns: A list of column names as strings
        downloadLocation: Directory into which to download the files

    Returns:
        A dictionary from file handle ID to path in the local file system.

    For example, consider a Synapse table whose ID is "syn12345" with two columns of type FILEHANDLEID named 'foo'
    and 'bar'. The associated files are JSON encoded, so we might retrieve the files from Synapse and load for the
    second 100 of those rows as shown here:

        import json

        results = syn.tableQuery('SELECT * FROM syn12345 LIMIT 100 OFFSET 100')
        file_map = syn.downloadTableColumns(results, ['foo', 'bar'])

        for file_handle_id, path in file_map.items():
            with open(path) as f:
                data[file_handle_id] = f.read()

    """
    return wrap_async_to_sync(
        self.downloadTableColumns_async(table, columns, downloadLocation, **kwargs)
    )

get_acl

get_acl(entity: Union[Entity, Evaluation, str, Mapping], principal_id: str = None, check_benefactor: bool = True) -> List[str]

Deprecated with replacement. This method will be removed in 5.0.0. Use the get_acl method on the dataclass models that inherit from AccessControllable mixin instead.

Get the ACL that a user or group has on an Entity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to lookup

TYPE: Union[Entity, Evaluation, str, Mapping]

principal_id

Identifier of a user or group (defaults to PUBLIC users)

TYPE: str DEFAULT: None

check_benefactor

If True (default), check the benefactor for the entity to get the ACL. If False, only check the entity itself. This is useful for checking the ACL of an entity that has local sharing settings, but you want to check the ACL of the entity itself and not the benefactor it may inherit from.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
List[str]

An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array

Using this function (DEPRECATED)

Getting ACL permissions for a user on an entity

permissions = syn.get_acl("syn123", principal_id="12345")

Getting ACL permissions for the public on an entity

permissions = syn.get_acl("syn123")
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import (
    File, Folder, Project, Table, EntityView, Dataset,
    DatasetCollection, MaterializedView, SubmissionView, VirtualTable
)

# Create client and login
syn = Synapse()
syn.login()

# Get ACL permissions for a specific user on a File
file_instance = File(id="syn123")
permissions = file_instance.get_acl(principal_id=12345)
print(f"User 12345 permissions on File syn123: {permissions}")

# Get ACL permissions for the public on a File
file_instance = File(id="syn123")
permissions = file_instance.get_acl()  # defaults to PUBLIC users
print(f"Public permissions on File syn123: {permissions}")

# Get ACL permissions with benefactor check disabled
file_instance = File(id="syn123")
permissions = file_instance.get_acl(
    principal_id=12345,
    check_benefactor=False
)
print(f"Entity-specific permissions for user 12345 on File syn123: {permissions}")

# Works with all AccessControllable models:

# Project
project = Project(id="syn123")
permissions = project.get_acl(principal_id=12345)
print(f"User 12345 permissions on Project syn123: {permissions}")

# Folder
folder = Folder(id="syn123")
permissions = folder.get_acl(principal_id=12345)
print(f"User 12345 permissions on Folder syn123: {permissions}")

# Table
table = Table(id="syn123")
permissions = table.get_acl(principal_id=12345)
print(f"User 12345 permissions on Table syn123: {permissions}")

# EntityView
entity_view = EntityView(id="syn123")
permissions = entity_view.get_acl(principal_id=12345)
print(f"User 12345 permissions on EntityView syn123: {permissions}")

# Dataset
dataset = Dataset(id="syn123")
permissions = dataset.get_acl(principal_id=12345)
print(f"User 12345 permissions on Dataset syn123: {permissions}")

# DatasetCollection
dataset_collection = DatasetCollection(id="syn123")
permissions = dataset_collection.get_acl(principal_id=12345)
print(f"User 12345 permissions on DatasetCollection syn123: {permissions}")

# MaterializedView
materialized_view = MaterializedView(id="syn123")
permissions = materialized_view.get_acl(principal_id=12345)
print(f"User 12345 permissions on MaterializedView syn123: {permissions}")

# SubmissionView
submission_view = SubmissionView(id="syn123")
permissions = submission_view.get_acl(principal_id=12345)
print(f"User 12345 permissions on SubmissionView syn123: {permissions}")

# VirtualTable
virtual_table = VirtualTable(id="syn123")
permissions = virtual_table.get_acl(principal_id=12345)
print(f"User 12345 permissions on VirtualTable syn123: {permissions}")

# Additional functionality available on AccessControllable models:

# List all ACL entries for an entity
file_instance = File(id="syn123")
acl_list = file_instance.list_acl()
print(f"All ACL entries for File syn123: {acl_list}")

# Delete the entire ACL for an entity (makes it inherit from benefactor)
file_instance = File(id="syn123")
file_instance.delete_permissions()
print("Successfully deleted entire ACL for File syn123 - now inherits permissions")

# To remove permissions for a specific user/group, use set_permissions with empty access_type
file_instance = File(id="syn123")
file_instance.set_permissions(principal_id=12345, access_type=[])
print("Successfully removed all permissions for user 12345 on File syn123")

# Use dry_run to preview what would be deleted without actually deleting
file_instance = File(id="syn123")
file_instance.delete_permissions(dry_run=True)
print("Dry run completed - showed what would be deleted")
Source code in synapseclient/client.py
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `get_acl` method on the dataclass models that inherit from `AccessControllable` mixin. "
    "Example: `from synapseclient.models import File; File(id='syn123').get_acl()`",
)
def get_acl(
    self,
    entity: Union[Entity, Evaluation, str, collections.abc.Mapping],
    principal_id: str = None,
    check_benefactor: bool = True,
) -> typing.List[str]:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `get_acl` method on the dataclass models that inherit from `AccessControllable` mixin instead.

    Get the [ACL](https://rest-docs.synapse.org/rest/org/
    sagebionetworks/repo/model/ACCESS_TYPE.html)
    that a user or group has on an Entity.

    Arguments:
        entity:      An Entity or Synapse ID to lookup
        principal_id: Identifier of a user or group (defaults to PUBLIC users)
        check_benefactor: If True (default), check the benefactor for the entity
            to get the ACL. If False, only check the entity itself.
            This is useful for checking the ACL of an entity that has local sharing
            settings, but you want to check the ACL of the entity itself and not
            the benefactor it may inherit from.

    Returns:
        An array containing some combination of
            ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
            'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
            or an empty array

    Example: Using this function (DEPRECATED)
        Getting ACL permissions for a user on an entity

            permissions = syn.get_acl("syn123", principal_id="12345")

        Getting ACL permissions for the public on an entity

            permissions = syn.get_acl("syn123")

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            File, Folder, Project, Table, EntityView, Dataset,
            DatasetCollection, MaterializedView, SubmissionView, VirtualTable
        )

        # Create client and login
        syn = Synapse()
        syn.login()

        # Get ACL permissions for a specific user on a File
        file_instance = File(id="syn123")
        permissions = file_instance.get_acl(principal_id=12345)
        print(f"User 12345 permissions on File syn123: {permissions}")

        # Get ACL permissions for the public on a File
        file_instance = File(id="syn123")
        permissions = file_instance.get_acl()  # defaults to PUBLIC users
        print(f"Public permissions on File syn123: {permissions}")

        # Get ACL permissions with benefactor check disabled
        file_instance = File(id="syn123")
        permissions = file_instance.get_acl(
            principal_id=12345,
            check_benefactor=False
        )
        print(f"Entity-specific permissions for user 12345 on File syn123: {permissions}")

        # Works with all AccessControllable models:

        # Project
        project = Project(id="syn123")
        permissions = project.get_acl(principal_id=12345)
        print(f"User 12345 permissions on Project syn123: {permissions}")

        # Folder
        folder = Folder(id="syn123")
        permissions = folder.get_acl(principal_id=12345)
        print(f"User 12345 permissions on Folder syn123: {permissions}")

        # Table
        table = Table(id="syn123")
        permissions = table.get_acl(principal_id=12345)
        print(f"User 12345 permissions on Table syn123: {permissions}")

        # EntityView
        entity_view = EntityView(id="syn123")
        permissions = entity_view.get_acl(principal_id=12345)
        print(f"User 12345 permissions on EntityView syn123: {permissions}")

        # Dataset
        dataset = Dataset(id="syn123")
        permissions = dataset.get_acl(principal_id=12345)
        print(f"User 12345 permissions on Dataset syn123: {permissions}")

        # DatasetCollection
        dataset_collection = DatasetCollection(id="syn123")
        permissions = dataset_collection.get_acl(principal_id=12345)
        print(f"User 12345 permissions on DatasetCollection syn123: {permissions}")

        # MaterializedView
        materialized_view = MaterializedView(id="syn123")
        permissions = materialized_view.get_acl(principal_id=12345)
        print(f"User 12345 permissions on MaterializedView syn123: {permissions}")

        # SubmissionView
        submission_view = SubmissionView(id="syn123")
        permissions = submission_view.get_acl(principal_id=12345)
        print(f"User 12345 permissions on SubmissionView syn123: {permissions}")

        # VirtualTable
        virtual_table = VirtualTable(id="syn123")
        permissions = virtual_table.get_acl(principal_id=12345)
        print(f"User 12345 permissions on VirtualTable syn123: {permissions}")

        # Additional functionality available on AccessControllable models:

        # List all ACL entries for an entity
        file_instance = File(id="syn123")
        acl_list = file_instance.list_acl()
        print(f"All ACL entries for File syn123: {acl_list}")

        # Delete the entire ACL for an entity (makes it inherit from benefactor)
        file_instance = File(id="syn123")
        file_instance.delete_permissions()
        print("Successfully deleted entire ACL for File syn123 - now inherits permissions")

        # To remove permissions for a specific user/group, use set_permissions with empty access_type
        file_instance = File(id="syn123")
        file_instance.set_permissions(principal_id=12345, access_type=[])
        print("Successfully removed all permissions for user 12345 on File syn123")

        # Use dry_run to preview what would be deleted without actually deleting
        file_instance = File(id="syn123")
        file_instance.delete_permissions(dry_run=True)
        print("Dry run completed - showed what would be deleted")
        ```
    """

    principal_id = self._getUserbyPrincipalIdOrName(principal_id)

    trace.get_current_span().set_attributes(
        {"synapse.id": id_of(entity), "synapse.principal_id": principal_id}
    )

    acl = self._getACL(entity=entity, check_benefactor=check_benefactor)

    team_list = self._find_teams_for_principal(principal_id)
    team_ids = [int(team.id) for team in team_list]
    effective_permission_set = set()

    # This user_profile_bundle is being used to verify that the principal_id
    #  is a registered user of the system
    user_profile_bundle = self._get_user_bundle(principal_id, 1)

    # Loop over all permissions in the returned ACL and add it to the effective_permission_set
    # if the principalId in the ACL matches
    # 1) the one we are looking for,
    # 2) a team the entity is a member of,
    # 3) PUBLIC
    # 4) A user_profile_bundle exists for the principal_id
    for permissions in acl["resourceAccess"]:
        if "principalId" in permissions and (
            permissions["principalId"] == principal_id
            or permissions["principalId"] in team_ids
            or permissions["principalId"] == PUBLIC
            or (
                permissions["principalId"] == AUTHENTICATED_USERS
                and user_profile_bundle is not None
            )
        ):
            effective_permission_set = effective_permission_set.union(
                permissions["accessType"]
            )
    return list(effective_permission_set)

get_permissions

get_permissions(entity: Union[Entity, Evaluation, str, Mapping]) -> Permissions

Deprecated with replacement. This method will be removed in 5.0.0. Use the get_permissions method on the dataclass models that inherit from AccessControllable mixin instead.

Get the permissions that the caller has on an Entity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to lookup

TYPE: Union[Entity, Evaluation, str, Mapping]

RETURNS DESCRIPTION
Permissions

An Permissions object

Using this function (DEPRECATED)

Getting permissions for a Synapse Entity

permissions = syn.get_permissions(Entity)

Getting permissions for a Synapse ID

permissions = syn.get_permissions("syn12345")

Getting access types list from the Permissions object

permissions.access_types
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import (
    File, Folder, Project, Table, EntityView, Dataset,
    DatasetCollection, MaterializedView, SubmissionView, VirtualTable
)

# Create client and login
syn = Synapse()
syn.login()

# Get permissions for the current user on a File
file_instance = File(id="syn12345")
permissions = file_instance.get_permissions()
print(f"Current user permissions on File syn12345: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# Get permissions for the current user on other entity types:

# Project
project = Project(id="syn12345")
permissions = project.get_permissions()
print(f"Current user permissions on Project {project.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# Folder
folder = Folder(id="syn12345")
permissions = folder.get_permissions()
print(f"Current user permissions on Folder {folder.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# Table
table = Table(id="syn12345")
permissions = table.get_permissions()
print(f"Current user permissions on Table {table.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# EntityView
entity_view = EntityView(id="syn12345")
permissions = entity_view.get_permissions()
print(f"Current user permissions on EntityView {entity_view.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# Dataset
dataset = Dataset(id="syn12345")
permissions = dataset.get_permissions()
print(f"Current user permissions on Dataset {dataset.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# DatasetCollection
dataset_collection = DatasetCollection(id="syn12345")
permissions = dataset_collection.get_permissions()
print(f"Current user permissions on DatasetCollection {dataset_collection.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# MaterializedView
materialized_view = MaterializedView(id="syn12345")
permissions = materialized_view.get_permissions()
print(f"Current user permissions on MaterializedView {materialized_view.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# SubmissionView
submission_view = SubmissionView(id="syn12345")
permissions = submission_view.get_permissions()
print(f"Current user permissions on SubmissionView {submission_view.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# VirtualTable
virtual_table = VirtualTable(id="syn12345")
permissions = virtual_table.get_permissions()
print(f"Current user permissions on VirtualTable {virtual_table.id}: {permissions}")
print(f"Current user access types: {permissions.access_types}")

# To get permissions for a specific user/group, use get_acl instead:
file_instance = File(id="syn12345")

# Get ACL permissions for a specific user
user_permissions = file_instance.get_acl(principal_id=12345)
print(f"User 12345 permissions on File {file_instance.id}: {user_permissions}")

# Get ACL permissions for the public
public_permissions = file_instance.get_acl()  # defaults to PUBLIC users
print(f"Public permissions on File {file_instance.id}: {public_permissions}")

# List all ACL entries for an entity
acl_list = file_instance.list_acl()
print(f"All ACL entries for File {file_instance.id}: {acl_list}")
Source code in synapseclient/client.py
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `get_permissions` method on the dataclass models that inherit from `AccessControllable` mixin. "
    "Note: The new `get_permissions` method only returns permissions for the current user. "
    "To get permissions for a specific principal, use the `get_acl` method instead. "
    "Example: `from synapseclient.models import File; File(id='syn123').get_permissions(); File(id='syn123').get_acl(principal_id=12345)`",
)
def get_permissions(
    self, entity: Union[Entity, Evaluation, str, collections.abc.Mapping]
) -> Permissions:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `get_permissions` method on the dataclass models that inherit from `AccessControllable` mixin instead.

    Get the [permissions](https://rest-docs.synapse.org/rest/org/
    sagebionetworks/repo/model/auth/UserEntityPermissions.html)
    that the caller has on an Entity.

    Arguments:
        entity: An Entity or Synapse ID to lookup

    Returns:
        An Permissions object

    Example: Using this function (DEPRECATED)
        Getting permissions for a Synapse Entity

            permissions = syn.get_permissions(Entity)

        Getting permissions for a Synapse ID

            permissions = syn.get_permissions("syn12345")

        Getting access types list from the Permissions object

            permissions.access_types

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            File, Folder, Project, Table, EntityView, Dataset,
            DatasetCollection, MaterializedView, SubmissionView, VirtualTable
        )

        # Create client and login
        syn = Synapse()
        syn.login()

        # Get permissions for the current user on a File
        file_instance = File(id="syn12345")
        permissions = file_instance.get_permissions()
        print(f"Current user permissions on File syn12345: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # Get permissions for the current user on other entity types:

        # Project
        project = Project(id="syn12345")
        permissions = project.get_permissions()
        print(f"Current user permissions on Project {project.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # Folder
        folder = Folder(id="syn12345")
        permissions = folder.get_permissions()
        print(f"Current user permissions on Folder {folder.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # Table
        table = Table(id="syn12345")
        permissions = table.get_permissions()
        print(f"Current user permissions on Table {table.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # EntityView
        entity_view = EntityView(id="syn12345")
        permissions = entity_view.get_permissions()
        print(f"Current user permissions on EntityView {entity_view.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # Dataset
        dataset = Dataset(id="syn12345")
        permissions = dataset.get_permissions()
        print(f"Current user permissions on Dataset {dataset.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # DatasetCollection
        dataset_collection = DatasetCollection(id="syn12345")
        permissions = dataset_collection.get_permissions()
        print(f"Current user permissions on DatasetCollection {dataset_collection.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # MaterializedView
        materialized_view = MaterializedView(id="syn12345")
        permissions = materialized_view.get_permissions()
        print(f"Current user permissions on MaterializedView {materialized_view.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # SubmissionView
        submission_view = SubmissionView(id="syn12345")
        permissions = submission_view.get_permissions()
        print(f"Current user permissions on SubmissionView {submission_view.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # VirtualTable
        virtual_table = VirtualTable(id="syn12345")
        permissions = virtual_table.get_permissions()
        print(f"Current user permissions on VirtualTable {virtual_table.id}: {permissions}")
        print(f"Current user access types: {permissions.access_types}")

        # To get permissions for a specific user/group, use get_acl instead:
        file_instance = File(id="syn12345")

        # Get ACL permissions for a specific user
        user_permissions = file_instance.get_acl(principal_id=12345)
        print(f"User 12345 permissions on File {file_instance.id}: {user_permissions}")

        # Get ACL permissions for the public
        public_permissions = file_instance.get_acl()  # defaults to PUBLIC users
        print(f"Public permissions on File {file_instance.id}: {public_permissions}")

        # List all ACL entries for an entity
        acl_list = file_instance.list_acl()
        print(f"All ACL entries for File {file_instance.id}: {acl_list}")
        ```
    """

    entity_id = id_of(entity)

    trace.get_current_span().set_attributes({"synapse.id": entity_id})

    url = f"/entity/{entity_id}/permissions"
    data = self.restGET(url)
    return Permissions.from_dict(data)

getPermissions

getPermissions(entity: Union[Entity, Evaluation, str, Mapping], principal_id: str = None) -> List[str]

Deprecated and replaced with get_acl.

Get the permissions that a user or group has on an Entity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to lookup

TYPE: Union[Entity, Evaluation, str, Mapping]

principal_id

Identifier of a user or group (defaults to PUBLIC users)

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
List[str]

An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array

Source code in synapseclient/client.py
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
@deprecated(
    version="4.0.0",
    reason="deprecated and replaced with synapseclient.Synapse.get_acl",
)
def getPermissions(
    self,
    entity: Union[Entity, Evaluation, str, collections.abc.Mapping],
    principal_id: str = None,
) -> typing.List[str]:
    """
    **Deprecated** and replaced with [get_acl][synapseclient.Synapse.get_acl].


    Get the permissions that a user or group has on an Entity.

    Arguments:
        entity:      An Entity or Synapse ID to lookup
        principal_id: Identifier of a user or group (defaults to PUBLIC users)

    Returns:
        An array containing some combination of
            ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE',
            'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS']
            or an empty array
    """

    return self.get_acl(entity=entity, principal_id=principal_id)

setPermissions

setPermissions(entity, principalId=None, accessType=['READ', 'DOWNLOAD'], modify_benefactor=False, warn_if_inherits=True, overwrite=True)

Deprecated with replacement. This method will be removed in 5.0.0. Use the set_permissions method on the dataclass models that inherit from AccessControllable mixin instead.

Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to modify

principalId

Identifier of a user or group. '273948' is for all registered Synapse users and '273949' is for public access. None implies public access.

DEFAULT: None

accessType

Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS

DEFAULT: ['READ', 'DOWNLOAD']

modify_benefactor

Set as True when modifying a benefactor's ACL. The term 'benefactor' is used to indicate which Entity an Entity inherits its ACL from. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project. If the entity already has local sharing settings the benefactor would be itself. It may also be the immediate parent, somewhere in the parent tree, or the project itself.

DEFAULT: False

warn_if_inherits

When modify_benefactor is True, this does not have any effect. When modify_benefactor is False, and warn_if_inherits is True, a warning log message is produced if the benefactor for the entity you passed into the function is not itself, i.e., it's the parent folder, or another entity in the parent tree.

DEFAULT: True

overwrite

By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.

DEFAULT: True

RETURNS DESCRIPTION

An Access Control List object

Using this function (DEPRECATED)

Grant all registered users download access

syn.setPermissions('syn1234','273948',['READ','DOWNLOAD'])

Grant the public view access

syn.setPermissions('syn1234','273949',['READ'])
Migration to new method

 

from synapseclient import Synapse, AUTHENTICATED_USERS, PUBLIC
from synapseclient.models import (
    File, Folder, Project, Table, EntityView, Dataset,
    DatasetCollection, MaterializedView, SubmissionView, VirtualTable
)

# Create client and login
syn = Synapse()
syn.login()

# Set permissions for a File
file_instance = File(id="syn1234")

# Grant all registered users download access
file_instance.set_permissions(
    principal_id=AUTHENTICATED_USERS,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully granted READ and DOWNLOAD access to all registered users on File {file_instance.id}")

# Grant the public view access
file_instance.set_permissions(
    principal_id=PUBLIC,
    access_type=["READ"]
)
print(f"Successfully granted READ access to public users on File {file_instance.id}")

# Set permissions with additional options
file_instance.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD", "UPDATE"],
    modify_benefactor=True,
    warn_if_inherits=False,
    overwrite=False  # Add to existing permissions instead of overwriting
)
print(f"Successfully added READ, DOWNLOAD, and UPDATE access for user 12345 on File {file_instance.id}")

# Remove permissions for a specific user/group by setting access_type to empty list
file_instance.set_permissions(
    principal_id=12345,
    access_type=[]  # Empty list removes all permissions for this principal
)
print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

# Alternative: Remove permissions by setting access_type to None
file_instance.set_permissions(
    principal_id=12345,
    access_type=None  # None also removes all permissions for this principal
)
print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

# Set permissions for other entity types:

# Project
project = Project(id="syn1234")
project.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Project {project.id}")

# Folder
folder = Folder(id="syn1234")
folder.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Folder {folder.id}")

# Table
table = Table(id="syn1234")
table.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Table {table.id}")

# EntityView
entity_view = EntityView(id="syn1234")
entity_view.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on EntityView {entity_view.id}")

# Dataset
dataset = Dataset(id="syn1234")
dataset.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Dataset {dataset.id}")

# DatasetCollection
dataset_collection = DatasetCollection(id="syn1234")
dataset_collection.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on DatasetCollection {dataset_collection.id}")

# MaterializedView
materialized_view = MaterializedView(id="syn1234")
materialized_view.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on MaterializedView {materialized_view.id}")

# SubmissionView
submission_view = SubmissionView(id="syn1234")
submission_view.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on SubmissionView {submission_view.id}")

# VirtualTable
virtual_table = VirtualTable(id="syn1234")
virtual_table.set_permissions(
    principal_id=12345,
    access_type=["READ", "DOWNLOAD"]
)
print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on VirtualTable {virtual_table.id}")

# Additional functionality available on AccessControllable models:

# List all ACL entries for an entity
file_instance = File(id="syn1234")
acl_list = file_instance.list_acl()
print(f"All ACL entries for File syn1234: {acl_list}")

# Delete the entire ACL for an entity (makes it inherit from benefactor)
file_instance = File(id="syn1234")
file_instance.delete_permissions()
print(f"Successfully deleted entire ACL for File {file_instance.id} - now inherits permissions")

# To remove permissions for a specific user/group, use set_permissions with empty access_type
file_instance = File(id="syn1234")
file_instance.set_permissions(principal_id=12345, access_type=[])
print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

# Use dry_run to preview what would be deleted without actually deleting
file_instance = File(id="syn1234")
file_instance.delete_permissions(dry_run=True)
print("Dry run completed - showed what would be deleted")
Source code in synapseclient/client.py
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `set_permissions` method on the dataclass models that inherit from `AccessControllable` mixin. "
    "Example: `from synapseclient.models import File; File(id='syn123').set_permissions(principal_id=12345, access_type=['READ'])`. "
    "To remove permissions for a specific user, use `access_type=[]` or `access_type=None`.",
)
def setPermissions(
    self,
    entity,
    principalId=None,
    accessType=["READ", "DOWNLOAD"],
    modify_benefactor=False,
    warn_if_inherits=True,
    overwrite=True,
):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `set_permissions` method on the dataclass models that inherit from `AccessControllable` mixin instead.

    Sets permission that a user or group has on an Entity.
    An Entity may have its own ACL or inherit its ACL from a benefactor.

    Arguments:
        entity: An Entity or Synapse ID to modify
        principalId: Identifier of a user or group. '273948' is for all registered Synapse users
                        and '273949' is for public access. None implies public access.
        accessType: Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE,
                        DELETE, CHANGE_PERMISSIONS
        modify_benefactor: Set as True when modifying a benefactor's ACL. The term
            'benefactor' is used to indicate which Entity an Entity inherits its
            ACL from. For example, a newly created Project will be its own
            benefactor, while a new FileEntity's benefactor will start off as its
            containing Project. If the entity already has local sharing settings
            the benefactor would be itself. It may also be the immediate parent,
            somewhere in the parent tree, or the project itself.
        warn_if_inherits: When `modify_benefactor` is True, this does not have any
            effect. When `modify_benefactor` is False, and `warn_if_inherits` is
            True, a warning log message is produced if the benefactor for the
            entity you passed into the function is not itself, i.e., it's the
            parent folder, or another entity in the parent tree.
        overwrite: By default this function overwrites existing permissions for the specified user.
                    Set this flag to False to add new permissions non-destructively.

    Returns:
        An Access Control List object

    Example: Using this function (DEPRECATED)
        Grant all registered users download access

            syn.setPermissions('syn1234','273948',['READ','DOWNLOAD'])

        Grant the public view access

            syn.setPermissions('syn1234','273949',['READ'])

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse, AUTHENTICATED_USERS, PUBLIC
        from synapseclient.models import (
            File, Folder, Project, Table, EntityView, Dataset,
            DatasetCollection, MaterializedView, SubmissionView, VirtualTable
        )

        # Create client and login
        syn = Synapse()
        syn.login()

        # Set permissions for a File
        file_instance = File(id="syn1234")

        # Grant all registered users download access
        file_instance.set_permissions(
            principal_id=AUTHENTICATED_USERS,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully granted READ and DOWNLOAD access to all registered users on File {file_instance.id}")

        # Grant the public view access
        file_instance.set_permissions(
            principal_id=PUBLIC,
            access_type=["READ"]
        )
        print(f"Successfully granted READ access to public users on File {file_instance.id}")

        # Set permissions with additional options
        file_instance.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD", "UPDATE"],
            modify_benefactor=True,
            warn_if_inherits=False,
            overwrite=False  # Add to existing permissions instead of overwriting
        )
        print(f"Successfully added READ, DOWNLOAD, and UPDATE access for user 12345 on File {file_instance.id}")

        # Remove permissions for a specific user/group by setting access_type to empty list
        file_instance.set_permissions(
            principal_id=12345,
            access_type=[]  # Empty list removes all permissions for this principal
        )
        print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

        # Alternative: Remove permissions by setting access_type to None
        file_instance.set_permissions(
            principal_id=12345,
            access_type=None  # None also removes all permissions for this principal
        )
        print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

        # Set permissions for other entity types:

        # Project
        project = Project(id="syn1234")
        project.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Project {project.id}")

        # Folder
        folder = Folder(id="syn1234")
        folder.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Folder {folder.id}")

        # Table
        table = Table(id="syn1234")
        table.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Table {table.id}")

        # EntityView
        entity_view = EntityView(id="syn1234")
        entity_view.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on EntityView {entity_view.id}")

        # Dataset
        dataset = Dataset(id="syn1234")
        dataset.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on Dataset {dataset.id}")

        # DatasetCollection
        dataset_collection = DatasetCollection(id="syn1234")
        dataset_collection.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on DatasetCollection {dataset_collection.id}")

        # MaterializedView
        materialized_view = MaterializedView(id="syn1234")
        materialized_view.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on MaterializedView {materialized_view.id}")

        # SubmissionView
        submission_view = SubmissionView(id="syn1234")
        submission_view.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on SubmissionView {submission_view.id}")

        # VirtualTable
        virtual_table = VirtualTable(id="syn1234")
        virtual_table.set_permissions(
            principal_id=12345,
            access_type=["READ", "DOWNLOAD"]
        )
        print(f"Successfully set READ and DOWNLOAD permissions for user 12345 on VirtualTable {virtual_table.id}")

        # Additional functionality available on AccessControllable models:

        # List all ACL entries for an entity
        file_instance = File(id="syn1234")
        acl_list = file_instance.list_acl()
        print(f"All ACL entries for File syn1234: {acl_list}")

        # Delete the entire ACL for an entity (makes it inherit from benefactor)
        file_instance = File(id="syn1234")
        file_instance.delete_permissions()
        print(f"Successfully deleted entire ACL for File {file_instance.id} - now inherits permissions")

        # To remove permissions for a specific user/group, use set_permissions with empty access_type
        file_instance = File(id="syn1234")
        file_instance.set_permissions(principal_id=12345, access_type=[])
        print(f"Successfully removed all permissions for user 12345 on File {file_instance.id}")

        # Use dry_run to preview what would be deleted without actually deleting
        file_instance = File(id="syn1234")
        file_instance.delete_permissions(dry_run=True)
        print("Dry run completed - showed what would be deleted")
        ```
    """
    entity_id = id_of(entity)
    trace.get_current_span().set_attributes({"synapse.id": entity_id})

    benefactor = self._getBenefactor(entity)
    if benefactor["id"] != entity_id:
        if modify_benefactor:
            entity = benefactor
        elif warn_if_inherits:
            self.logger.warning(
                "Creating an ACL for entity %s, which formerly inherited access control from a"
                ' benefactor entity, "%s" (%s).\n'
                % (entity_id, benefactor["name"], benefactor["id"])
            )

    acl = self._getACL(entity)

    principalId = self._getUserbyPrincipalIdOrName(principalId)

    # Find existing permissions
    permissions_to_update = None
    for permissions in acl["resourceAccess"]:
        if (
            "principalId" in permissions
            and permissions["principalId"] == principalId
        ):
            permissions_to_update = permissions
            break

    if accessType is None or accessType == []:
        # remove permissions
        if permissions_to_update and overwrite:
            acl["resourceAccess"].remove(permissions_to_update)
    else:
        # add a 'resourceAccess' entry, if necessary
        if not permissions_to_update:
            permissions_to_update = {"accessType": [], "principalId": principalId}
            acl["resourceAccess"].append(permissions_to_update)
        if overwrite:
            permissions_to_update["accessType"] = accessType
        else:
            permissions_to_update["accessType"] = list(
                set(permissions_to_update["accessType"]) | set(accessType)
            )
    return self._storeACL(entity, acl)

getProvenance

getProvenance(entity: Union[str, Mapping, Number], version: int = None) -> Activity

Deprecated with replacement. This method will be removed in 5.0.0. Use [synapseclient.models.Activity.get][] instead.

Retrieve provenance information for a Synapse Entity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to lookup

TYPE: Union[str, Mapping, Number]

version

The version of the Entity to retrieve. Gets the most recent version if omitted

TYPE: int DEFAULT: None

RETURNS DESCRIPTION
Activity

An Activity object or raises exception if no provenance record exists

RAISES DESCRIPTION
SynapseHTTPError

if no provenance record exists

Using this function (DEPRECATED)

Getting provenance for an entity

activity = syn.getProvenance("syn123")
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Activity

# Login to Synapse
syn = Synapse()
syn.login()

# Get the activity associated with the entity
activity = Activity.get(parent_id="syn123")
if activity:
    print(f"Activity: {activity.name}")
else:
    print("No activity found")

# Get the activity for a specific version
activity = Activity.get(parent_id="syn123", parent_version_number=2)
if activity:
    print(f"Activity: {activity.name}")
else:
    print("No activity found")
Source code in synapseclient/client.py
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `get` method on the `from synapseclient.models import Activity` class. "
    "Check the docstring for the replacement function example.",
)
def getProvenance(
    self,
    entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
    version: int = None,
) -> Activity:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Activity.get][] instead.

    Retrieve provenance information for a Synapse Entity.

    Arguments:
        entity:  An Entity or Synapse ID to lookup
        version: The version of the Entity to retrieve. Gets the most recent version if omitted

    Returns:
        An Activity object or raises exception if no provenance record exists

    Raises:
        SynapseHTTPError: if no provenance record exists

    Example: Using this function (DEPRECATED)
        Getting provenance for an entity

            activity = syn.getProvenance("syn123")

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Activity

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get the activity associated with the entity
        activity = Activity.get(parent_id="syn123")
        if activity:
            print(f"Activity: {activity.name}")
        else:
            print("No activity found")

        # Get the activity for a specific version
        activity = Activity.get(parent_id="syn123", parent_version_number=2)
        if activity:
            print(f"Activity: {activity.name}")
        else:
            print("No activity found")
        ```
    """
    # Get versionNumber from Entity
    if version is None and "versionNumber" in entity:
        version = entity["versionNumber"]
    entity_id = id_of(entity)
    if version:
        uri = "/entity/%s/version/%d/generatedBy" % (entity_id, version)
    else:
        uri = "/entity/%s/generatedBy" % entity_id

    trace.get_current_span().set_attributes({"synapse.id": entity_id})
    return Activity(data=self.restGET(uri))

setProvenance

setProvenance(entity: Union[str, Mapping, Number], activity: Activity) -> Activity

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Activity.store instead.

Stores a record of the code and data used to derive a Synapse entity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to modify

TYPE: Union[str, Mapping, Number]

activity

TYPE: Activity

RETURNS DESCRIPTION
Activity
Using this function (DEPRECATED)

Setting provenance for an entity

activity = Activity(name="Analysis", description="Data processing")
updated_activity = syn.setProvenance("syn123", activity)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Activity

# Login to Synapse
syn = Synapse()
syn.login()

# Create an activity
activity = Activity(
    name="Analysis",
    description="Data processing"
)

# Store the activity and associate it with the entity
stored_activity = activity.store(parent="syn123")
print(f"Stored activity: {stored_activity.name}")
Source code in synapseclient/client.py
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `store` method on the `from synapseclient.models import Activity` class. "
    "Check the docstring for the replacement function example.",
)
def setProvenance(
    self,
    entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
    activity: Activity,
) -> Activity:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Activity.store][] instead.

    Stores a record of the code and data used to derive a Synapse entity.

    Arguments:
        entity:   An Entity or Synapse ID to modify
        activity: A [synapseclient.activity.Activity][]

    Returns:
        An updated [synapseclient.activity.Activity][] object

    Example: Using this function (DEPRECATED)
        Setting provenance for an entity

            activity = Activity(name="Analysis", description="Data processing")
            updated_activity = syn.setProvenance("syn123", activity)

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Activity

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Create an activity
        activity = Activity(
            name="Analysis",
            description="Data processing"
        )

        # Store the activity and associate it with the entity
        stored_activity = activity.store(parent="syn123")
        print(f"Stored activity: {stored_activity.name}")
        ```
    """
    # Assert that the entity was generated by a given Activity.
    activity = self._saveActivity(activity)

    entity_id = id_of(entity)
    # assert that an entity is generated by an activity
    uri = "/entity/%s/generatedBy?generatedBy=%s" % (entity_id, activity["id"])
    activity = Activity(data=self.restPUT(uri))

    trace.get_current_span().set_attributes({"synapse.id": entity_id})
    return activity

deleteProvenance

deleteProvenance(entity: Union[str, Mapping, Number]) -> None

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Activity.delete instead.

Removes provenance information from an Entity and deletes the associated Activity.

PARAMETER DESCRIPTION
entity

An Entity or Synapse ID to modify

TYPE: Union[str, Mapping, Number]

Using this function (DEPRECATED)

Deleting provenance for an entity

syn.deleteProvenance("syn123")
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Activity

# Login to Synapse
syn = Synapse()
syn.login()

# Delete the activity associated with the entity
Activity.delete(parent="syn123")
print("Activity deleted")
Source code in synapseclient/client.py
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `delete` method on the `from synapseclient.models import Activity` class. "
    "Check the docstring for the replacement function example.",
)
def deleteProvenance(
    self,
    entity: typing.Union[str, collections.abc.Mapping, numbers.Number],
) -> None:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Activity.delete][] instead.

    Removes provenance information from an Entity and deletes the associated Activity.

    Arguments:
        entity: An Entity or Synapse ID to modify

    Example: Using this function (DEPRECATED)
        Deleting provenance for an entity

            syn.deleteProvenance("syn123")

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Activity

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Delete the activity associated with the entity
        Activity.delete(parent="syn123")
        print("Activity deleted")
        ```
    """
    activity = self.getProvenance(entity)
    if not activity:
        return
    entity_id = id_of(entity)
    trace.get_current_span().set_attributes({"synapse.id": entity_id})

    uri = "/entity/%s/generatedBy" % entity_id
    self.restDELETE(uri)

    # If the activity is shared by more than one entity you recieve an HTTP 400 error:
    # "If you wish to delete this activity, please first delete all Entities generated by this Activity.""
    uri = "/activity/%s" % activity["id"]
    self.restDELETE(uri)

updateActivity

updateActivity(activity) -> Activity

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Activity.store instead.

Modifies an existing Activity.

PARAMETER DESCRIPTION
activity

The Activity to be updated.

RETURNS DESCRIPTION
Activity

An updated Activity object

Using this function (DEPRECATED)

Updating an existing activity

activity = syn.getProvenance("syn123")
activity['name'] = "Updated Analysis"
updated_activity = syn.updateActivity(activity)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Activity

# Login to Synapse
syn = Synapse()
syn.login()

# Get the existing activity by parent entity
activity = Activity.get(parent_id="syn123")

if activity:
    # Update the activity
    activity.name = "Updated Analysis"
    activity.description = "Updated data processing"

    # Store the updated activity
    updated_activity = activity.store()
    print(f"Updated activity: {updated_activity.name}")
Source code in synapseclient/client.py
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `store` method on the `from synapseclient.models import Activity` class. "
    "Check the docstring for the replacement function example.",
)
def updateActivity(self, activity) -> Activity:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Activity.store][] instead.

    Modifies an existing Activity.

    Arguments:
        activity: The Activity to be updated.

    Returns:
        An updated Activity object

    Example: Using this function (DEPRECATED)
        Updating an existing activity

            activity = syn.getProvenance("syn123")
            activity['name'] = "Updated Analysis"
            updated_activity = syn.updateActivity(activity)

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Activity

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get the existing activity by parent entity
        activity = Activity.get(parent_id="syn123")

        if activity:
            # Update the activity
            activity.name = "Updated Analysis"
            activity.description = "Updated data processing"

            # Store the updated activity
            updated_activity = activity.store()
            print(f"Updated activity: {updated_activity.name}")
        ```
    """
    if "id" not in activity:
        raise ValueError("The activity you want to update must exist on Synapse")
    trace.get_current_span().set_attributes({"synapse.id": activity["id"]})
    return self._saveActivity(activity)

findEntityId

findEntityId(name, parent=None)

Find an Entity given its name and parent.

PARAMETER DESCRIPTION
name

Name of the entity to find

parent

An Entity object or the Id of an entity as a string. Omit if searching for a Project by name

DEFAULT: None

RETURNS DESCRIPTION

The Entity ID or None if not found

Source code in synapseclient/client.py
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import find_entity_id` instead.",
)
def findEntityId(self, name, parent=None):
    """
    Find an Entity given its name and parent.

    Arguments:
        name: Name of the entity to find
        parent: An Entity object or the Id of an entity as a string. Omit if searching for a Project by name

    Returns:
        The Entity ID or None if not found
    """
    # when we want to search for a project by name. set parentId as None instead of ROOT_ENTITY
    entity_lookup_request = {
        "parentId": id_of(parent) if parent else None,
        "entityName": name,
    }
    try:
        return self.restPOST(
            "/entity/child", body=json.dumps(entity_lookup_request)
        ).get("id")
    except SynapseHTTPError as e:
        if (
            e.response.status_code == 404
        ):  # a 404 error is raised if the entity does not exist
            return None
        raise

getChildren

getChildren(parent, includeTypes=['folder', 'file', 'table', 'link', 'entityview', 'dockerrepo', 'submissionview', 'dataset', 'materializedview'], sortBy='NAME', sortDirection='ASC')

Retrieves all of the entities stored within a parent such as folder or project.

PARAMETER DESCRIPTION
parent

An id or an object of a Synapse container or None to retrieve all projects

includeTypes

Must be a list of entity types (ie. ["folder","file"]) which can be found here

DEFAULT: ['folder', 'file', 'table', 'link', 'entityview', 'dockerrepo', 'submissionview', 'dataset', 'materializedview']

sortBy

How results should be sorted. Can be NAME, or CREATED_ON

DEFAULT: 'NAME'

sortDirection

The direction of the result sort. Can be ASC, or DESC

DEFAULT: 'ASC'

YIELDS DESCRIPTION

An iterator that shows all the children of the container.

Also see:

Migrating from this method to new approaches

 

Legacy approach (deprecated):

# Using the deprecated getChildren method
for child in syn.getChildren("syn12345", includeTypes=["file", "folder"]):
    print(f"Child: {child['name']} (ID: {child['id']})")

New approach using dataclass models with sync_from_synapse:

import synapseclient
from synapseclient.models import Project, Folder

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# For projects - get all children automatically (recursive by default)
project = Project(id="syn12345")
project = project.sync_from_synapse(download_file=False)

# Access different types of children
print(f"Files: {len(project.files)}")
for file in project.files:
    print(f"  File: {file.name} (ID: {file.id})")

print(f"Folders: {len(project.folders)}")
for folder in project.folders:
    print(f"  Folder: {folder.name} (ID: {folder.id})")

print(f"Tables: {len(project.tables)}")
for table in project.tables:
    print(f"  Table: {table.name} (ID: {table.id})")

# For folders - get all children automatically (recursive by default)
folder = Folder(id="syn67890")
folder = folder.sync_from_synapse(download_file=False)

# Access children in the same way
for file in folder.files:
    print(f"  File: {file.name} (ID: {file.id})")

# For non-recursive behavior (equivalent to single getChildren call)
folder = Folder(id="syn67890")
folder = folder.sync_from_synapse(download_file=False, recursive=False)

# This will only get immediate children, not subfolders' contents
for file in folder.files:
    print(f"  File: {file.name} (ID: {file.id})")
for subfolder in folder.folders:
    print(f"  Subfolder: {subfolder.name} (ID: {subfolder.id})")
    # Note: subfolder.files and subfolder.folders will be empty
    # because recursive=False

New approach using the API directly (for advanced sorting/filtering):

import asyncio
import synapseclient
from synapseclient.api import get_children

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# Using the new async API function directly
async def get_sorted_children():
    async for child in get_children(
        parent="syn12345",
        include_types=["file", "folder"],
        sort_by="NAME",
        sort_direction="ASC"
    ):
        print(f"Child: {child['name']} (ID: {child['id']}, Type: {child['type']})")

# Run the async function
asyncio.run(get_sorted_children())

Source code in synapseclient/client.py
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the new dataclass models `from synapseclient.models import Project, Folder` "
    "with their `sync_from_synapse` method for most use cases, "
    "or the `synapseclient.api.get_children` function for direct API access with sorting and filtering.",
)
def getChildren(
    self,
    parent,
    includeTypes=[
        "folder",
        "file",
        "table",
        "link",
        "entityview",
        "dockerrepo",
        "submissionview",
        "dataset",
        "materializedview",
    ],
    sortBy="NAME",
    sortDirection="ASC",
):
    """
    Retrieves all of the entities stored within a parent such as folder or project.

    Arguments:
        parent: An id or an object of a Synapse container or None to retrieve all projects
        includeTypes: Must be a list of entity types (ie. ["folder","file"]) which can be found [here](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/EntityType.html)
        sortBy: How results should be sorted. Can be NAME, or CREATED_ON
        sortDirection: The direction of the result sort. Can be ASC, or DESC

    Yields:
        An iterator that shows all the children of the container.

    Also see:

    - [synapseutils.walk][]

    Example: Migrating from this method to new approaches
        &nbsp;

        **Legacy approach (deprecated):**
        ```python
        # Using the deprecated getChildren method
        for child in syn.getChildren("syn12345", includeTypes=["file", "folder"]):
            print(f"Child: {child['name']} (ID: {child['id']})")
        ```

        **New approach using dataclass models with sync_from_synapse:**
        ```python
        import synapseclient
        from synapseclient.models import Project, Folder

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # For projects - get all children automatically (recursive by default)
        project = Project(id="syn12345")
        project = project.sync_from_synapse(download_file=False)

        # Access different types of children
        print(f"Files: {len(project.files)}")
        for file in project.files:
            print(f"  File: {file.name} (ID: {file.id})")

        print(f"Folders: {len(project.folders)}")
        for folder in project.folders:
            print(f"  Folder: {folder.name} (ID: {folder.id})")

        print(f"Tables: {len(project.tables)}")
        for table in project.tables:
            print(f"  Table: {table.name} (ID: {table.id})")

        # For folders - get all children automatically (recursive by default)
        folder = Folder(id="syn67890")
        folder = folder.sync_from_synapse(download_file=False)

        # Access children in the same way
        for file in folder.files:
            print(f"  File: {file.name} (ID: {file.id})")

        # For non-recursive behavior (equivalent to single getChildren call)
        folder = Folder(id="syn67890")
        folder = folder.sync_from_synapse(download_file=False, recursive=False)

        # This will only get immediate children, not subfolders' contents
        for file in folder.files:
            print(f"  File: {file.name} (ID: {file.id})")
        for subfolder in folder.folders:
            print(f"  Subfolder: {subfolder.name} (ID: {subfolder.id})")
            # Note: subfolder.files and subfolder.folders will be empty
            # because recursive=False
        ```

        **New approach using the API directly (for advanced sorting/filtering):**
        ```python
        import asyncio
        import synapseclient
        from synapseclient.api import get_children

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # Using the new async API function directly
        async def get_sorted_children():
            async for child in get_children(
                parent="syn12345",
                include_types=["file", "folder"],
                sort_by="NAME",
                sort_direction="ASC"
            ):
                print(f"Child: {child['name']} (ID: {child['id']}, Type: {child['type']})")

        # Run the async function
        asyncio.run(get_sorted_children())
        ```
    """
    parentId = id_of(parent) if parent is not None else None

    trace.get_current_span().set_attributes({"synapse.parent_id": parentId})
    entityChildrenRequest = {
        "parentId": parentId,
        "includeTypes": includeTypes,
        "sortBy": sortBy,
        "sortDirection": sortDirection,
        "nextPageToken": None,
    }
    entityChildrenResponse = {"nextPageToken": "first"}
    while entityChildrenResponse.get("nextPageToken") is not None:
        entityChildrenResponse = self.restPOST(
            "/entity/children", body=json.dumps(entityChildrenRequest)
        )
        for child in entityChildrenResponse["page"]:
            yield child
        if entityChildrenResponse.get("nextPageToken") is not None:
            entityChildrenRequest["nextPageToken"] = entityChildrenResponse[
                "nextPageToken"
            ]

getTeam

getTeam(id: Union[int, str]) -> Team

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.from_id or synapseclient.models.Team.from_name instead.

Finds a team with a given ID or name.

PARAMETER DESCRIPTION
id

The ID or name of the team or a Team object to retrieve.

TYPE: Union[int, str]

RETURNS DESCRIPTION
Team

An object of type synapseclient.team.Team

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Get a team by ID
team_by_id = Team.from_id(id=12345)
print(f"Team by ID: {team_by_id.name}")

# Get a team by name
team_by_name = Team.from_name(name="My Team")
print(f"Team by name: {team_by_name.name}")
Source code in synapseclient/client.py
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `get`, `from_id`, and `from_name` methods on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def getTeam(self, id: Union[int, str]) -> Team:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.from_id][] or [synapseclient.models.Team.from_name][] instead.

    Finds a team with a given ID or name.

    Arguments:
        id: The ID or name of the team or a Team object to retrieve.

    Returns:
        An object of type [synapseclient.team.Team][]

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get a team by ID
        team_by_id = Team.from_id(id=12345)
        print(f"Team by ID: {team_by_id.name}")

        # Get a team by name
        team_by_name = Team.from_name(name="My Team")
        print(f"Team by name: {team_by_name.name}")
        ```
    """
    # Retrieves team id
    teamid = id_of(id)
    try:
        int(teamid)
    except (TypeError, ValueError):
        if isinstance(id, str):
            for team in self._findTeam(id):
                if team.name == id:
                    teamid = team.id
                    break
            else:
                raise ValueError('Can\'t find team "{}"'.format(teamid))
        else:
            raise ValueError('Can\'t find team "{}"'.format(teamid))
    return Team(**self.restGET("/team/%s" % teamid))

getTeamMembers

getTeamMembers(team: Union[Team, int, str]) -> Generator[TeamMember, None, None]

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.members instead.

Lists the members of the given team.

PARAMETER DESCRIPTION
team

A synapseclient.team.Team object or a team's ID.

TYPE: Union[Team, int, str]

YIELDS DESCRIPTION
TeamMember

A generator over synapseclient.team.TeamMember objects.

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Get team members
team = Team.from_id(id=12345)
members = team.members()
for member in members:
    print(f"Member: {member.member.user_name}")
Source code in synapseclient/client.py
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `members` method on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def getTeamMembers(
    self, team: Union[Team, int, str]
) -> typing.Generator[TeamMember, None, None]:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.members][] instead.

    Lists the members of the given team.

    Arguments:
        team: A [synapseclient.team.Team][] object or a team's ID.

    Yields:
        A generator over [synapseclient.team.TeamMember][] objects.

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get team members
        team = Team.from_id(id=12345)
        members = team.members()
        for member in members:
            print(f"Member: {member.member.user_name}")
        ```

    """
    for result in self._GET_paginated("/teamMembers/{id}".format(id=id_of(team))):
        yield TeamMember(**result)

invite_to_team

invite_to_team(team: Union[Team, int, str], user: str = None, inviteeEmail: str = None, message: str = None, force: bool = False)

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.invite instead.

Invite user to a Synapse team via Synapse username or email (choose one or the other)

PARAMETER DESCRIPTION
syn

Synapse object

team

A synapseclient.team.Team object or a team's ID.

TYPE: Union[Team, int, str]

user

Synapse username or profile id of user

TYPE: str DEFAULT: None

inviteeEmail

Email of user

TYPE: str DEFAULT: None

message

Additional message for the user getting invited to the team.

TYPE: str DEFAULT: None

force

If an open invitation exists for the invitee, the old invite will be cancelled.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

MembershipInvitation or None if user is already a member

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Invite a user to a team
team = Team.from_id(id=12345)
invitation = team.invite(
    user="username",
    message="Welcome to the team!",
    force=True
)
print(f"Invitation sent: {invitation}")
Source code in synapseclient/client.py
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `invite` method on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def invite_to_team(
    self,
    team: Union[Team, int, str],
    user: str = None,
    inviteeEmail: str = None,
    message: str = None,
    force: bool = False,
):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.invite][] instead.

    Invite user to a Synapse team via Synapse username or email
    (choose one or the other)

    Arguments:
        syn: Synapse object
        team: A [synapseclient.team.Team][] object or a team's ID.
        user: Synapse username or profile id of user
        inviteeEmail: Email of user
        message: Additional message for the user getting invited to the team.
        force: If an open invitation exists for the invitee, the old invite will be cancelled.

    Returns:
        MembershipInvitation or None if user is already a member

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Invite a user to a team
        team = Team.from_id(id=12345)
        invitation = team.invite(
            user="username",
            message="Welcome to the team!",
            force=True
        )
        print(f"Invitation sent: {invitation}")
        ```
    """
    # Throw error if both user and email is specified and if both not
    # specified
    id_email_specified = inviteeEmail is not None and user is not None
    id_email_notspecified = inviteeEmail is None and user is None
    if id_email_specified or id_email_notspecified:
        raise ValueError("Must specify either 'user' or 'inviteeEmail'")

    teamid = id_of(team)
    is_member = False
    open_invitations = self.get_team_open_invitations(teamid)

    if user is not None:
        inviteeId = self.getUserProfile(user)["ownerId"]
        membership_status = self.get_membership_status(inviteeId, teamid)
        is_member = membership_status["isMember"]
        open_invites_to_user = [
            invitation
            for invitation in open_invitations
            if invitation.get("inviteeId") == inviteeId
        ]
    else:
        inviteeId = None
        open_invites_to_user = [
            invitation
            for invitation in open_invitations
            if invitation.get("inviteeEmail") == inviteeEmail
        ]
    # Only invite if the invitee is not a member and
    # if invitee doesn't have an open invitation unless force=True
    if not is_member and (not open_invites_to_user or force):
        # Delete all old invitations
        for invite in open_invites_to_user:
            self._delete_membership_invitation(invite["id"])
        return self.send_membership_invitation(
            teamid,
            inviteeId=inviteeId,
            inviteeEmail=inviteeEmail,
            message=message,
        )
    if is_member:
        not_sent_reason = "invitee is already a member"
    else:
        not_sent_reason = (
            "invitee already has an open invitation "
            "Set force=True to send new invite."
        )

    self.logger.warning("No invitation sent: {}".format(not_sent_reason))
    # Return None if no invite is sent.
    return None

get_membership_status

get_membership_status(userid, team)

Retrieve a user's Team Membership Status bundle. https://rest-docs.synapse.org/rest/GET/team/id/member/principalId/membershipStatus.html

PARAMETER DESCRIPTION
user

Synapse user ID

team

A synapseclient.team.Team object or a team's ID.

RETURNS DESCRIPTION

dict of TeamMembershipStatus

Using this function (DEPRECATED)

  Getting a user's membership status for a team

from synapseclient import Synapse

# Login to Synapse
syn = Synapse()
syn.login()

status = syn.get_membership_status(userid="12345", team="67890")
print(status)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Use synchronous version (recommended for most use cases)
team = Team.from_id(id="67890")
status = team.get_user_membership_status(
    user_id="12345",
)
print(status)
Source code in synapseclient/client.py
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the `get_user_membership_status` method on the `Team` class from `synapseclient.models` instead. "
    "Check the docstring for the replacement function example.",
)
def get_membership_status(self, userid, team):
    """Retrieve a user's Team Membership Status bundle.
    <https://rest-docs.synapse.org/rest/GET/team/id/member/principalId/membershipStatus.html>

    Arguments:
        user: Synapse user ID
        team: A [synapseclient.team.Team][] object or a team's ID.

    Returns:
        dict of TeamMembershipStatus

    Example: Using this function (DEPRECATED)
        &nbsp;
        Getting a user's membership status for a team

        ```python
        from synapseclient import Synapse

        # Login to Synapse
        syn = Synapse()
        syn.login()

        status = syn.get_membership_status(userid="12345", team="67890")
        print(status)
        ```


    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Use synchronous version (recommended for most use cases)
        team = Team.from_id(id="67890")
        status = team.get_user_membership_status(
            user_id="12345",
        )
        print(status)
        ```
    """
    teamid = id_of(team)
    request = "/team/{team}/member/{user}/membershipStatus".format(
        team=teamid, user=userid
    )
    membership_status = self.restGET(request)
    return membership_status

get_team_open_invitations

get_team_open_invitations(team: Union[Team, int, str]) -> Generator[dict, None, None]

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.open_invitations instead.

Retrieve the open requests submitted to a Team https://rest-docs.synapse.org/rest/GET/team/id/openInvitation.html

PARAMETER DESCRIPTION
team

A synapseclient.team.Team object or a team's ID.

TYPE: Union[Team, int, str]

YIELDS DESCRIPTION
dict

Generator of MembershipRequest dictionaries

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Get open invitations for a team
team = Team.from_id(id=12345)
invitations = team.open_invitations()
for invitation in invitations:
    print(f"Invitation: {invitation}")
Source code in synapseclient/client.py
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `open_invitations` method on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def get_team_open_invitations(
    self, team: Union[Team, int, str]
) -> typing.Generator[dict, None, None]:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.open_invitations][] instead.

    Retrieve the open requests submitted to a Team
    <https://rest-docs.synapse.org/rest/GET/team/id/openInvitation.html>

    Arguments:
        team: A [synapseclient.team.Team][] object or a team's ID.

    Yields:
        Generator of MembershipRequest dictionaries

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get open invitations for a team
        team = Team.from_id(id=12345)
        invitations = team.open_invitations()
        for invitation in invitations:
            print(f"Invitation: {invitation}")
        ```
    """
    teamid = id_of(team)
    request = "/team/{team}/openInvitation".format(team=teamid)
    open_requests = self._GET_paginated(request)
    return open_requests

send_membership_invitation

send_membership_invitation(teamId, inviteeId=None, inviteeEmail=None, message=None)

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.api.team_services.send_membership_invitation instead.

Create a membership invitation and send an email notification to the invitee.

PARAMETER DESCRIPTION
teamId

Synapse teamId

inviteeId

Synapse username or profile id of user

DEFAULT: None

inviteeEmail

Email of user

DEFAULT: None

message

Additional message for the user getting invited to the team.

DEFAULT: None

RETURNS DESCRIPTION

MembershipInvitation

Migration to new method

 

import asyncio
from synapseclient import Synapse
from synapseclient.api.team_services import send_membership_invitation

# Login to Synapse
syn = Synapse()
syn.login()

# Send invitation by user ID
invitation = asyncio.run(send_membership_invitation(
    team_id=12345,
    invitee_id="username_or_user_id",
    message="Welcome to our team!"
))
print(f"Invitation sent: {invitation}")

# Send invitation by email
invitation = asyncio.run(send_membership_invitation(
    team_id=12345,
    invitee_email="user@example.com",
    message="Join our team!"
))
print(f"Invitation sent: {invitation}")
Source code in synapseclient/client.py
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to synapseclient.api.team_services.send_membership_invitation. "
    "Check the docstring for the replacement function example.",
)
def send_membership_invitation(
    self, teamId, inviteeId=None, inviteeEmail=None, message=None
):
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.api.team_services.send_membership_invitation][] instead.

    Create a membership invitation and send an email notification
    to the invitee.

    Arguments:
        teamId: Synapse teamId
        inviteeId: Synapse username or profile id of user
        inviteeEmail: Email of user
        message: Additional message for the user getting invited to the
                 team.

    Returns:
        MembershipInvitation

    Example: Migration to new method
        &nbsp;

        ```python
        import asyncio
        from synapseclient import Synapse
        from synapseclient.api.team_services import send_membership_invitation

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Send invitation by user ID
        invitation = asyncio.run(send_membership_invitation(
            team_id=12345,
            invitee_id="username_or_user_id",
            message="Welcome to our team!"
        ))
        print(f"Invitation sent: {invitation}")

        # Send invitation by email
        invitation = asyncio.run(send_membership_invitation(
            team_id=12345,
            invitee_email="user@example.com",
            message="Join our team!"
        ))
        print(f"Invitation sent: {invitation}")
        ```
    """

    invite_request = {"teamId": str(teamId), "message": message}
    if inviteeEmail is not None:
        invite_request["inviteeEmail"] = str(inviteeEmail)
    if inviteeId is not None:
        invite_request["inviteeId"] = str(inviteeId)

    response = self.restPOST(
        "/membershipInvitation", body=json.dumps(invite_request)
    )
    return response

submit

submit(evaluation, entity, name=None, team=None, silent=False, submitterAlias=None, teamName=None, dockerTag='latest')

Submit an Entity for evaluation.

PARAMETER DESCRIPTION
evalation

Evaluation queue to submit to

entity

The Entity containing the Submissions

name

A name for this submission. In the absent of this parameter, the entity name will be used. (Optional) A synapseclient.team.Team object, ID or name of a Team that is registered for the challenge

DEFAULT: None

team

(optional) A synapseclient.team.Team object, ID or name of a Team that is registered for the challenge

DEFAULT: None

silent

Set to True to suppress output.

DEFAULT: False

submitterAlias

(optional) A nickname, possibly for display in leaderboards in place of the submitter's name

DEFAULT: None

teamName

(deprecated) A synonym for submitterAlias

DEFAULT: None

dockerTag

(optional) The Docker tag must be specified if the entity is a DockerRepository.

DEFAULT: 'latest'

RETURNS DESCRIPTION

In the case of challenges, a team can optionally be provided to give credit to members of the team that contributed to the submission. The team must be registered for the challenge with which the given evaluation is associated. The caller must be a member of the submitting team.

Using this function

Getting and submitting an evaluation

evaluation = syn.getEvaluation(123)
entity = syn.get('syn456')
submission = syn.submit(evaluation, entity, name='Our Final Answer', team='Blue Team')
Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# submission = syn.submit(9614543, "syn456", name="Our Final Answer")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Submission

syn = Synapse()
syn.login()

submission = Submission(
    evaluation_id="9614543",
    entity_id="syn456",
    name="Our Final Answer",
).store()
Source code in synapseclient/client.py
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.Submission` model instead, e.g. "
    "`Submission(...).store()`.",
)
def submit(
    self,
    evaluation,
    entity,
    name=None,
    team=None,
    silent=False,
    submitterAlias=None,
    teamName=None,
    dockerTag="latest",
):
    """
    Submit an Entity for [evaluation][synapseclient.evaluation.Evaluation].

    Arguments:
        evalation: Evaluation queue to submit to
        entity: The Entity containing the Submissions
        name: A name for this submission. In the absent of this parameter, the entity name will be used.
                (Optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
        team: (optional) A [synapseclient.team.Team][] object, ID or name of a Team that is registered for the challenge
        silent: Set to True to suppress output.
        submitterAlias: (optional) A nickname, possibly for display in leaderboards in place of the submitter's name
        teamName: (deprecated) A synonym for submitterAlias
        dockerTag: (optional) The Docker tag must be specified if the entity is a DockerRepository.

    Returns:
        A [synapseclient.evaluation.Submission][] object


    In the case of challenges, a team can optionally be provided to give credit to members of the team that
    contributed to the submission. The team must be registered for the challenge with which the given evaluation is
    associated. The caller must be a member of the submitting team.

    Example: Using this function
        Getting and submitting an evaluation

            evaluation = syn.getEvaluation(123)
            entity = syn.get('syn456')
            submission = syn.submit(evaluation, entity, name='Our Final Answer', team='Blue Team')

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # submission = syn.submit(9614543, "syn456", name="Our Final Answer")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Submission

        syn = Synapse()
        syn.login()

        submission = Submission(
            evaluation_id="9614543",
            entity_id="syn456",
            name="Our Final Answer",
        ).store()
        ```
    """
    return wrap_async_to_sync(
        self.submit_async(
            evaluation,
            entity,
            name=name,
            team=team,
            silent=silent,
            submitterAlias=submitterAlias,
            teamName=teamName,
            dockerTag=dockerTag,
        )
    )

getConfigFile cached

getConfigFile(configPath: str) -> RawConfigParser

Retrieves the client configuration information.

PARAMETER DESCRIPTION
configPath

Path to configuration file on local file system

TYPE: str

RETURNS DESCRIPTION
RawConfigParser

A RawConfigParser populated with properties from the user's configuration file.

Source code in synapseclient/client.py
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
@deprecated(
    version="4.4.0",
    reason="To be removed in 5.0.0. "
    "Moved to synapseclient/api/configuration_services.py::get_config_file",
)
@functools.lru_cache()
def getConfigFile(self, configPath: str) -> configparser.RawConfigParser:
    """
    Retrieves the client configuration information.

    Arguments:
        configPath:  Path to configuration file on local file system

    Returns:
        A RawConfigParser populated with properties from the user's configuration file.
    """

    try:
        config = configparser.RawConfigParser()
        config.read(configPath)  # Does not fail if the file does not exist
        return config
    except configparser.Error as ex:
        raise ValueError(
            "Error parsing Synapse config file: {}".format(configPath)
        ) from ex

setEndpoints

setEndpoints(repoEndpoint: str = None, authEndpoint: str = None, fileHandleEndpoint: str = None, portalEndpoint: str = None, skip_checks: bool = False) -> None

Sets the locations for each of the Synapse services (mostly useful for testing).

PARAMETER DESCRIPTION
repoEndpoint

Location of synapse repository

TYPE: str DEFAULT: None

authEndpoint

Location of authentication service

TYPE: str DEFAULT: None

fileHandleEndpoint

Location of file service

TYPE: str DEFAULT: None

portalEndpoint

Location of the website

TYPE: str DEFAULT: None

skip_checks

Skip version and endpoint checks

TYPE: bool DEFAULT: False

Switching endpoints

To switch between staging and production endpoints

syn.setEndpoints(**synapseclient.client.STAGING_ENDPOINTS)
syn.setEndpoints(**synapseclient.client.PRODUCTION_ENDPOINTS)
Source code in synapseclient/client.py
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
def setEndpoints(
    self,
    repoEndpoint: str = None,
    authEndpoint: str = None,
    fileHandleEndpoint: str = None,
    portalEndpoint: str = None,
    skip_checks: bool = False,
) -> None:
    """
    Sets the locations for each of the Synapse services (mostly useful for testing).

    Arguments:
        repoEndpoint:          Location of synapse repository
        authEndpoint:          Location of authentication service
        fileHandleEndpoint:    Location of file service
        portalEndpoint:        Location of the website
        skip_checks:           Skip version and endpoint checks

    Example: Switching endpoints
        To switch between staging and production endpoints

            syn.setEndpoints(**synapseclient.client.STAGING_ENDPOINTS)
            syn.setEndpoints(**synapseclient.client.PRODUCTION_ENDPOINTS)

    """

    endpoints = {
        "repoEndpoint": repoEndpoint,
        "authEndpoint": authEndpoint,
        "fileHandleEndpoint": fileHandleEndpoint,
        "portalEndpoint": portalEndpoint,
    }

    # For unspecified endpoints, first look in the config file
    config = get_config_file(self.configPath)
    for point in endpoints.keys():
        if endpoints[point] is None and config.has_option("endpoints", point):
            endpoints[point] = config.get("endpoints", point)

    # Endpoints default to production
    for point in endpoints.keys():
        if endpoints[point] is None:
            endpoints[point] = PRODUCTION_ENDPOINTS[point]

        # Update endpoints if we get redirected
        if not skip_checks:
            response = with_retry(
                lambda point=point: self._requests_session.get(
                    endpoints[point],
                    allow_redirects=False,
                    headers=synapseclient.USER_AGENT,
                    timeout=self._http_timeout_seconds,
                ),
                verbose=self.debug,
                **{**STANDARD_RETRY_PARAMS, "retries": 2},
            )
            if response.status_code == 301:
                endpoints[point] = response.headers["location"]

    self.repoEndpoint = endpoints["repoEndpoint"]
    self.authEndpoint = endpoints["authEndpoint"]
    self.fileHandleEndpoint = endpoints["fileHandleEndpoint"]
    self.portalEndpoint = endpoints["portalEndpoint"]

invalidateAPIKey

invalidateAPIKey()

Deprecated with no replacement. The client does not support API keys for authentication. Please use a personal access token instead. This method will be removed in a future release.

Invalidates authentication across all clients.

RETURNS DESCRIPTION

None

Source code in synapseclient/client.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
@deprecated(
    version="4.0.0",
    reason="deprecated with no replacement. The client does not support API keys for "
    "authentication. Please use a personal access token instead. This method will "
    "be removed in a future release.",
)
def invalidateAPIKey(self):
    """
    **Deprecated with no replacement.** The client does not support API keys for
    authentication. Please use a
    [personal access token](https://python-docs.synapse.org/tutorials/authentication/)
    instead. This method will be removed in a future release.


    Invalidates authentication across all clients.

    Returns:
        None
    """

    # Logout globally
    if self._is_logged_in():
        self.restDELETE("/secretKey", endpoint=self.authEndpoint)

get_user_profile_by_username cached

get_user_profile_by_username(username: str = None, sessionToken: str = None) -> UserProfile

Deprecated with replacement. This method will be removed in 5.0.0. Use the from_username method on the from synapseclient.models import UserProfile class.

Get the details about a Synapse user. Retrieves information on the current user if 'id' is omitted or is empty string.

PARAMETER DESCRIPTION
username

The userName of a user

TYPE: str DEFAULT: None

sessionToken

The session token to use to find the user profile

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
UserProfile

The user profile for the user of interest.

Using this function (DEPRECATED)

Getting your own profile

my_profile = syn.get_user_profile_by_username()

Getting another user's profile

users_profile = syn.get_user_profile_by_username('synapse-service-dpe-team')
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import UserProfile

# Login to Synapse
syn = Synapse()
syn.login()

# Get your own profile
my_profile = UserProfile().get()
print(f"My profile: {my_profile.username}")

# Get another user's profile by username
profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
print(f"Profile by username: {profile_by_username.username}")
Source code in synapseclient/client.py
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
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `from_username` method on the `from synapseclient.models import UserProfile` class. "
    "Check the docstring for the replacement function example.",
)
@functools.lru_cache()
def get_user_profile_by_username(
    self,
    username: str = None,
    sessionToken: str = None,
) -> UserProfile:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the [from_username][synapseclient.models.UserProfile.from_username] method on the `from synapseclient.models import UserProfile` class.

    Get the details about a Synapse user.
    Retrieves information on the current user if 'id' is omitted or is empty string.

    Arguments:
        username:     The userName of a user
        sessionToken: The session token to use to find the user profile

    Returns:
        The user profile for the user of interest.

    Example: Using this function (DEPRECATED)
        Getting your own profile

            my_profile = syn.get_user_profile_by_username()

        Getting another user's profile

            users_profile = syn.get_user_profile_by_username('synapse-service-dpe-team')

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import UserProfile

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get your own profile
        my_profile = UserProfile().get()
        print(f"My profile: {my_profile.username}")

        # Get another user's profile by username
        profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
        print(f"Profile by username: {profile_by_username.username}")
        ```
    """
    is_none = username is None
    is_str = isinstance(username, str)
    if not is_str and not is_none:
        raise TypeError("username must be string or None")
    if is_str:
        principals = self._findPrincipals(username)
        for principal in principals:
            if principal.get("userName", None).lower() == username.lower():
                id = principal["ownerId"]
                break
        else:
            raise ValueError(f"Can't find user '{username}'")
    else:
        id = ""
    uri = f"/userProfile/{id}"
    return UserProfile(
        **self.restGET(
            uri, headers={"sessionToken": sessionToken} if sessionToken else None
        )
    )

get_user_profile_by_id cached

get_user_profile_by_id(id: int = None, sessionToken: str = None) -> UserProfile

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.UserProfile.from_id instead.

Get the details about a Synapse user. Retrieves information on the current user if 'id' is omitted.

PARAMETER DESCRIPTION
id

The ownerId of a user

TYPE: int DEFAULT: None

sessionToken

The session token to use to find the user profile

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
UserProfile

The user profile for the user of interest.

Using this function (DEPRECATED)

Getting your own profile

my_profile = syn.get_user_profile_by_id()

Getting another user's profile

users_profile = syn.get_user_profile_by_id(3485485)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import UserProfile

# Login to Synapse
syn = Synapse()
syn.login()

# Get your own profile
my_profile = UserProfile().get()
print(f"My profile: {my_profile.username}")

# Get another user's profile by ID
profile_by_id = UserProfile.from_id(user_id=3485485)
print(f"Profile by id: {profile_by_id.username}")
Source code in synapseclient/client.py
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
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `from_id` method on the `from synapseclient.models import UserProfile` class. "
    "Check the docstring for the replacement function example.",
)
@functools.lru_cache()
def get_user_profile_by_id(
    self,
    id: int = None,
    sessionToken: str = None,
) -> UserProfile:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.UserProfile.from_id][] instead.

    Get the details about a Synapse user.
    Retrieves information on the current user if 'id' is omitted.

    Arguments:
        id:           The ownerId of a user
        sessionToken: The session token to use to find the user profile

    Returns:
        The user profile for the user of interest.

    Example: Using this function (DEPRECATED)
        Getting your own profile

            my_profile = syn.get_user_profile_by_id()

        Getting another user's profile

            users_profile = syn.get_user_profile_by_id(3485485)

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import UserProfile

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get your own profile
        my_profile = UserProfile().get()
        print(f"My profile: {my_profile.username}")

        # Get another user's profile by ID
        profile_by_id = UserProfile.from_id(user_id=3485485)
        print(f"Profile by id: {profile_by_id.username}")
        ```
    """
    if id:
        if not isinstance(id, int):
            raise TypeError("id must be an 'ownerId' integer")
    else:
        id = ""
    uri = f"/userProfile/{id}"
    return UserProfile(
        **self.restGET(
            uri, headers={"sessionToken": sessionToken} if sessionToken else None
        )
    )

getUserProfile cached

getUserProfile(id: Union[str, int, UserProfile, TeamMember] = None, sessionToken: str = None) -> UserProfile

Deprecated with replacement. This method will be removed in 5.0.0. Use [synapseclient.models.protocols.user_protocol.from_id][] instead.

Get the details about a Synapse user. Retrieves information on the current user if 'id' is omitted.

PARAMETER DESCRIPTION
id

The 'userId' (aka 'ownerId') of a user or the userName

TYPE: Union[str, int, UserProfile, TeamMember] DEFAULT: None

sessionToken

The session token to use to find the user profile

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
UserProfile

The user profile for the user of interest.

Using this function (DEPRECATED)

Getting your own profile

my_profile = syn.getUserProfile()

Getting another user's profile

users_profile = syn.getUserProfile('synapse-service-dpe-team')
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import UserProfile

# Login to Synapse
syn = Synapse()
syn.login()

# Get your own profile
my_profile = UserProfile().get()
print(f"My profile: {my_profile.username}")

# Get another user's profile by username
profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
print(f"Profile by username: {profile_by_username.username}")

# Get another user's profile by ID
profile_by_id = UserProfile.from_id(user_id=3485485)
print(f"Profile by id: {profile_by_id.username}")
Source code in synapseclient/client.py
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
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `from_id` and `from_username` methods on the `from synapseclient.models import UserProfile` class. "
    "Check the docstring for the replacement function example.",
)
@functools.lru_cache()
def getUserProfile(
    self,
    id: Union[str, int, UserProfile, TeamMember] = None,
    sessionToken: str = None,
) -> UserProfile:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.protocols.user_protocol.from_id][] instead.

    Get the details about a Synapse user.
    Retrieves information on the current user if 'id' is omitted.

    Arguments:
        id:           The 'userId' (aka 'ownerId') of a user or the userName
        sessionToken: The session token to use to find the user profile

    Returns:
        The user profile for the user of interest.

    Example: Using this function (DEPRECATED)
        Getting your own profile

            my_profile = syn.getUserProfile()

        Getting another user's profile

            users_profile = syn.getUserProfile('synapse-service-dpe-team')

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import UserProfile

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Get your own profile
        my_profile = UserProfile().get()
        print(f"My profile: {my_profile.username}")

        # Get another user's profile by username
        profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
        print(f"Profile by username: {profile_by_username.username}")

        # Get another user's profile by ID
        profile_by_id = UserProfile.from_id(user_id=3485485)
        print(f"Profile by id: {profile_by_id.username}")
        ```
    """
    try:
        # if id is unset or a userID, this will succeed
        id = "" if id is None else int(id)
    except (TypeError, ValueError):
        if isinstance(id, collections.abc.Mapping) and "ownerId" in id:
            id = id.ownerId
        elif isinstance(id, TeamMember):
            id = id.member.ownerId
        else:
            principals = self._findPrincipals(id)
            if len(principals) == 1:
                id = principals[0]["ownerId"]
            else:
                for principal in principals:
                    if principal.get("userName", None).lower() == id.lower():
                        id = principal["ownerId"]
                        break
                else:  # no break
                    raise ValueError('Can\'t find user "%s": ' % id)
    uri = "/userProfile/%s" % id
    return UserProfile(
        **self.restGET(
            uri, headers={"sessionToken": sessionToken} if sessionToken else None
        )
    )

is_certified

is_certified(user: Union[str, int]) -> bool

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.UserProfile.is_certified instead.

Determines whether a Synapse user is a certified user.

PARAMETER DESCRIPTION
user

Synapse username or Id

TYPE: Union[str, int]

RETURNS DESCRIPTION
bool

True if the Synapse user is certified

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import UserProfile

# Login to Synapse
syn = Synapse()
syn.login()

# Check if user is certified by username
profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
user_certified = profile_by_username.is_certified()
print(f"User {profile_by_username.username} is certified: {user_certified}")

# Check if user is certified by ID
profile_by_id = UserProfile.from_id(user_id=3485485)
user_certified = profile_by_id.is_certified()
print(f"User {profile_by_id.username} is certified: {user_certified}")
Source code in synapseclient/client.py
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
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `is_certified` method on the `from synapseclient.models import UserProfile` class. "
    "Check the docstring for the replacement function example.",
)
def is_certified(self, user: typing.Union[str, int]) -> bool:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.UserProfile.is_certified][] instead.

    Determines whether a Synapse user is a certified user.

    Arguments:
        user: Synapse username or Id

    Returns:
        True if the Synapse user is certified

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import UserProfile

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Check if user is certified by username
        profile_by_username = UserProfile.from_username(username='synapse-service-dpe-team')
        user_certified = profile_by_username.is_certified()
        print(f"User {profile_by_username.username} is certified: {user_certified}")

        # Check if user is certified by ID
        profile_by_id = UserProfile.from_id(user_id=3485485)
        user_certified = profile_by_id.is_certified()
        print(f"User {profile_by_id.username} is certified: {user_certified}")
        ```
    """
    # Check if userid or username exists
    syn_user = self.getUserProfile(user)
    # Get passing record

    try:
        certification_status = self._get_certified_passing_record(
            syn_user["ownerId"]
        )
        return certification_status["passed"]
    except SynapseHTTPError as ex:
        if ex.response.status_code == 404:
            # user hasn't taken the quiz
            return False
        raise

is_synapse_id

is_synapse_id(syn_id: str) -> bool

Checks if given synID is valid (attached to actual entity?)

PARAMETER DESCRIPTION
syn_id

A Synapse ID

TYPE: str

RETURNS DESCRIPTION
bool

True if the Synapse ID is valid

Source code in synapseclient/client.py
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
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import is_synapse_id` instead.",
)
def is_synapse_id(self, syn_id: str) -> bool:
    """Checks if given synID is valid (attached to actual entity?)

    Arguments:
        syn_id: A Synapse ID

    Returns:
        True if the Synapse ID is valid
    """
    if isinstance(syn_id, str):
        try:
            self.get(syn_id, downloadFile=False)
        except SynapseFileNotFoundError:
            return False
        except (
            SynapseHTTPError,
            SynapseAuthenticationError,
        ) as err:
            status = (
                err.__context__.response.status_code or err.response.status_code
            )
            if status in (400, 404):
                return False
            # Valid ID but user lacks permission or is not logged in
            elif status == 403:
                return True
        return True
    self.logger.warning("synID must be a string")
    return False

onweb

onweb(entity, subpageId=None)

Opens up a browser window to the entity page or wiki-subpage.

PARAMETER DESCRIPTION
entity

Either an Entity or a Synapse ID

subpageId

(Optional) ID of one of the wiki's sub-pages

DEFAULT: None

RETURNS DESCRIPTION

None

Source code in synapseclient/client.py
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import onweb` instead.",
)
def onweb(self, entity, subpageId=None):
    """Opens up a browser window to the entity page or wiki-subpage.

    Arguments:
        entity:    Either an Entity or a Synapse ID
        subpageId: (Optional) ID of one of the wiki's sub-pages

    Returns:
        None
    """
    if isinstance(entity, str) and os.path.isfile(entity):
        entity = self.get(entity, downloadFile=False)
    synId = id_of(entity)
    if subpageId is None:
        webbrowser.open("%s/Synapse:%s" % (self.portalEndpoint, synId))
    else:
        webbrowser.open(
            "%s/Wiki:%s/ENTITY/%s" % (self.portalEndpoint, synId, subpageId)
        )

printEntity

printEntity(entity, ensure_ascii=True) -> None

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.operations.print_entity instead.

Pretty prints an Entity.

PARAMETER DESCRIPTION
entity

The entity to be printed.

ensure_ascii

If True, escapes all non-ASCII characters

DEFAULT: True

Migration to new function

 

from synapseclient import Synapse
from synapseclient.operations import print_entity

# Login to Synapse
syn = Synapse()
syn.login()

# Print an entity by Synapse ID
print_entity("syn123456")

# Print an entity object
from synapseclient.operations import get
entity = get(synapse_id="syn123456")
print_entity(entity)

# Print with unicode characters preserved
print_entity("syn123456", ensure_ascii=False)
RETURNS DESCRIPTION
None

None

Source code in synapseclient/client.py
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
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import print_entity` instead.",
)
def printEntity(self, entity, ensure_ascii=True) -> None:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.operations.print_entity][] instead.

    Pretty prints an Entity.

    Arguments:
        entity: The entity to be printed.
        ensure_ascii: If True, escapes all non-ASCII characters

    Example: Migration to new function
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.operations import print_entity

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Print an entity by Synapse ID
        print_entity("syn123456")

        # Print an entity object
        from synapseclient.operations import get
        entity = get(synapse_id="syn123456")
        print_entity(entity)

        # Print with unicode characters preserved
        print_entity("syn123456", ensure_ascii=False)
        ```

    Returns:
        None
    """

    if utils.is_synapse_id_str(entity):
        synid, version = utils.get_synid_and_version(entity)
        entity = self._getEntity(synid, version)
    try:
        self.logger.info(
            json.dumps(entity, sort_keys=True, indent=2, ensure_ascii=ensure_ascii)
        )
    except TypeError:
        self.logger.info(str(entity))

get_available_services

get_available_services() -> List[str]

Get available Synapse services This is a beta feature and is subject to change

RETURNS DESCRIPTION
List[str]

List of available services

Source code in synapseclient/client.py
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. This is a beta feature with no replacement.",
)
def get_available_services(self) -> typing.List[str]:
    """Get available Synapse services
    This is a beta feature and is subject to change

    Returns:
        List of available services
    """
    services = self._services.keys()
    return list(services)

service

service(service_name: str)

Get available Synapse services This is a beta feature and is subject to change

PARAMETER DESCRIPTION
service_name

name of the service

TYPE: str

Source code in synapseclient/client.py
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
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. This is a beta feature with no replacement.",
)
def service(self, service_name: str):
    """Get available Synapse services
    This is a beta feature and is subject to change

    Arguments:
        service_name: name of the service
    """
    # This is to avoid circular imports
    # TODO: revisit the import order and method https://stackoverflow.com/a/37126790
    # To move this to the top
    import synapseclient.services

    assert isinstance(service_name, str)
    service_name = service_name.lower().replace(" ", "_")
    assert service_name in self._services, (
        f"Unrecognized service ({service_name}). Run the 'get_available_"
        "services()' method to get a list of available services."
    )
    service_attr = self._services[service_name]
    service_cls = getattr(synapseclient.services, service_attr)
    service = service_cls(self)
    return service

clear_download_list

clear_download_list()

Clear all files from download list

Migration to new method

 

# Old approach (DEPRECATED)
# syn.clear_download_list()

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.operations import download_list_clear

syn = Synapse()
syn.login()

# Clear all files from the download list
download_list_clear()
Source code in synapseclient/client.py
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
@deprecated(
    version="4.13.0",
    reason=(
        "Use `synapseclient.operations.download_list_clear()` instead. "
        "See synapseclient.operations.download_list_operations for the new interface."
    ),
)
def clear_download_list(self):
    """Clear all files from download list

    Example: Migration to new method
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # syn.clear_download_list()

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.operations import download_list_clear

        syn = Synapse()
        syn.login()

        # Clear all files from the download list
        download_list_clear()
        ```
    """
    self.restDELETE("/download/list")

create_external_s3_file_handle

create_external_s3_file_handle(bucket_name, s3_file_key, file_path, *, parent=None, storage_location_id=None, mimetype=None, md5: str = None)

Create an external S3 file handle for e.g. a file that has been uploaded directly to an external S3 storage location.

PARAMETER DESCRIPTION
bucket_name

Name of the S3 bucket

s3_file_key

S3 key of the uploaded object

file_path

Local path of the uploaded file

parent

Parent entity to create the file handle in, the file handle will be created in the default storage location of the parent. Mutually exclusive with storage_location_id

DEFAULT: None

storage_location_id

Explicit storage location id to create the file handle in, mutually exclusive with parent

DEFAULT: None

mimetype

Mimetype of the file, if known

DEFAULT: None

md5

MD5 of the file, if known

TYPE: str DEFAULT: None

RAISES DESCRIPTION
ValueError

If neither parent nor storage_location_id is specified, or if both are specified.

Source code in synapseclient/client.py
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.api.post_external_s3_file_handle()` instead.",
)
def create_external_s3_file_handle(
    self,
    bucket_name,
    s3_file_key,
    file_path,
    *,
    parent=None,
    storage_location_id=None,
    mimetype=None,
    md5: str = None,
):
    """
    Create an external S3 file handle for e.g. a file that has been uploaded directly to
    an external S3 storage location.

    Arguments:
        bucket_name: Name of the S3 bucket
        s3_file_key: S3 key of the uploaded object
        file_path: Local path of the uploaded file
        parent: Parent entity to create the file handle in, the file handle will be created
                in the default storage location of the parent. Mutually exclusive with
                storage_location_id
        storage_location_id: Explicit storage location id to create the file handle in, mutually exclusive
                with parent
        mimetype: Mimetype of the file, if known
        md5: MD5 of the file, if known

    Raises:
        ValueError: If neither parent nor storage_location_id is specified, or if both are specified.
    """

    if storage_location_id:
        if parent:
            raise ValueError("Pass parent or storage_location_id, not both")
    elif not parent:
        raise ValueError("One of parent or storage_location_id is required")
    else:
        upload_destination = self._getDefaultUploadDestination(parent)
        storage_location_id = upload_destination["storageLocationId"]

    if mimetype is None:
        mimetype, _ = mimetypes.guess_type(file_path, strict=False)

    file_handle = {
        "concreteType": concrete_types.S3_FILE_HANDLE,
        "key": s3_file_key,
        "bucketName": bucket_name,
        "fileName": os.path.basename(file_path),
        "contentMd5": md5 or utils.md5_for_file(file_path).hexdigest(),
        "contentSize": os.stat(file_path).st_size,
        "storageLocationId": storage_location_id,
        "contentType": mimetype,
    }

    return self.restPOST(
        "/externalFileHandle/s3",
        json.dumps(file_handle),
        endpoint=self.fileHandleEndpoint,
    )

getMyStorageLocationSetting

getMyStorageLocationSetting(storage_location_id)

Get a StorageLocationSetting by its id.

PARAMETER DESCRIPTION
storage_location_id

id of the StorageLocationSetting to retrieve. The corresponding StorageLocationSetting must have been created by this user.

RETURNS DESCRIPTION

A dict describing the StorageLocationSetting retrieved by its id

Source code in synapseclient/client.py
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `StorageLocation(storage_location_id=id).get()` from "
    "synapseclient.models instead.",
)
def getMyStorageLocationSetting(self, storage_location_id):
    """
    Get a StorageLocationSetting by its id.

    Arguments:
        storage_location_id: id of the StorageLocationSetting to retrieve.
                                The corresponding StorageLocationSetting must have been created by this user.

    Returns:
        A dict describing the StorageLocationSetting retrieved by its id
    """
    return self.restGET("/storageLocation/%s" % storage_location_id)

createStorageLocationSetting

createStorageLocationSetting(storage_type, **kwargs)

Creates an IMMUTABLE storage location based on the specified type.

For each storage_type, the following kwargs should be specified:

ExternalObjectStorage: (S3-like (e.g. AWS S3 or Openstack) bucket not accessed by Synapse)

  • endpointUrl: endpoint URL of the S3 service (for example: 'https://s3.amazonaws.com')
  • bucket: the name of the bucket to use

ExternalS3Storage: (Amazon S3 bucket accessed by Synapse)

  • bucket: the name of the bucket to use

ExternalStorage: (SFTP or FTP storage location not accessed by Synapse)

  • url: the base URL for uploading to the external destination
  • supportsSubfolders(optional): does the destination support creating subfolders under the base url (default: false)

ProxyStorage: (a proxy server that controls access to a storage)

  • secretKey: The encryption key used to sign all pre-signed URLs used to communicate with the proxy.
  • proxyUrl: The HTTPS URL of the proxy used for upload and download.
PARAMETER DESCRIPTION
storage_type

The type of the StorageLocationSetting to create

banner

(Optional) The optional banner to show every time a file is uploaded

description

(Optional) The description to show the user when the user has to choose which upload destination to use

kwargs

fields necessary for creation of the specified storage_type

DEFAULT: {}

RETURNS DESCRIPTION

A dict of the created StorageLocationSetting

Source code in synapseclient/client.py
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `StorageLocation(...).store()` from synapseclient.models instead.",
)
def createStorageLocationSetting(self, storage_type, **kwargs):
    """
    Creates an IMMUTABLE storage location based on the specified type.

    For each storage_type, the following kwargs should be specified:

    **ExternalObjectStorage**: (S3-like (e.g. AWS S3 or Openstack) bucket not accessed by Synapse)

    - `endpointUrl`: endpoint URL of the S3 service (for example: 'https://s3.amazonaws.com')
    - `bucket`: the name of the bucket to use

    **ExternalS3Storage**: (Amazon S3 bucket accessed by Synapse)

    - `bucket`: the name of the bucket to use

    **ExternalStorage**: (SFTP or FTP storage location not accessed by Synapse)

    - `url`: the base URL for uploading to the external destination
    - `supportsSubfolders(optional)`: does the destination support creating subfolders under the base url
        (default: false)

    **ProxyStorage**: (a proxy server that controls access to a storage)

    - `secretKey`: The encryption key used to sign all pre-signed URLs used to communicate with the proxy.
    - `proxyUrl`: The HTTPS URL of the proxy used for upload and download.

    Arguments:
        storage_type: The type of the StorageLocationSetting to create
        banner: (Optional) The optional banner to show every time a file is uploaded
        description: (Optional) The description to show the user when the user has to choose which upload destination to use
        kwargs: fields necessary for creation of the specified storage_type

    Returns:
        A dict of the created StorageLocationSetting
    """
    upload_type_dict = {
        "ExternalObjectStorage": "S3",
        "ExternalS3Storage": "S3",
        "ExternalStorage": "SFTP",
        "ProxyStorage": "PROXYLOCAL",
    }

    if storage_type not in upload_type_dict:
        raise ValueError("Unknown storage_type: %s", storage_type)

    # ProxyStorageLocationSettings has an extra 's' at the end >:(
    kwargs["concreteType"] = (
        "org.sagebionetworks.repo.model.project."
        + storage_type
        + "LocationSetting"
        + ("s" if storage_type == "ProxyStorage" else "")
    )
    kwargs["uploadType"] = upload_type_dict[storage_type]

    return self.restPOST("/storageLocation", body=json.dumps(kwargs))

create_s3_storage_location

create_s3_storage_location(*, parent=None, folder_name=None, folder=None, bucket_name=None, base_key=None, sts_enabled=False) -> Tuple[Folder, Dict[str, str], Dict[str, str]]

Create a storage location in the given parent, either in the given folder or by creating a new folder in that parent with the given name. This will both create a StorageLocationSetting, and a ProjectSetting together, optionally creating a new folder in which to locate it, and optionally enabling this storage location for access via STS. If enabling an existing folder for STS, it must be empty.

Deprecated: To be removed in 5.0.0. Use the synapseclient.models.StorageLocation model and its store() method to create the storage location, and set_storage_location() on a Project or Folder to apply it as a project setting.

PARAMETER DESCRIPTION
parent

The parent in which to locate the storage location (mutually exclusive with folder)

DEFAULT: None

folder_name

The name of a new folder to create (mutually exclusive with folder)

DEFAULT: None

folder

The existing folder in which to create the storage location (mutually exclusive with folder_name)

DEFAULT: None

bucket_name

The name of an S3 bucket, if this is an external storage location, if None will use Synapse S3 storage

DEFAULT: None

base_key

The base key of within the bucket, None to use the bucket root, only applicable if bucket_name is passed

DEFAULT: None

sts_enabled

Whether this storage location should be STS enabled

DEFAULT: False

RETURNS DESCRIPTION
Tuple[Folder, Dict[str, str], Dict[str, str]]

A 3-tuple of the synapse Folder, a the storage location setting, and the project setting dictionaries.

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# folder, storage_setting, project_setting = syn.create_s3_storage_location(
#     parent="syn123",
#     folder_name="my-external-storage",
#     bucket_name="my-bucket",
# )

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Folder, StorageLocation, StorageLocationType

syn = Synapse()
syn.login()

# Create the storage location backed by your own S3 bucket
storage = StorageLocation(
    storage_type=StorageLocationType.EXTERNAL_S3,
    bucket="my-bucket",
).store()

# Create a folder to hold the externally stored files
folder = Folder(name="my-external-storage", parent_id="syn123").store()

# Apply the storage location as the folder's upload destination
folder.set_storage_location(storage_location_id=storage.storage_location_id)
Source code in synapseclient/client.py
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.StorageLocation` model and its `store()` "
    "method instead. To also create a folder and apply the storage location "
    "as a project setting, use `Folder` together with "
    "`set_storage_location()` on the project/folder.",
)
def create_s3_storage_location(
    self,
    *,
    parent=None,
    folder_name=None,
    folder=None,
    bucket_name=None,
    base_key=None,
    sts_enabled=False,
) -> Tuple[Folder, Dict[str, str], Dict[str, str]]:
    """
    Create a storage location in the given parent, either in the given folder or by creating a new
    folder in that parent with the given name. This will both create a StorageLocationSetting,
    and a ProjectSetting together, optionally creating a new folder in which to locate it,
    and optionally enabling this storage location for access via STS. If enabling an existing folder for STS,
    it must be empty.

    Deprecated: To be removed in 5.0.0. Use the synapseclient.models.StorageLocation
    model and its store() method to create the storage location, and
    set_storage_location() on a Project or Folder to apply it as a project setting.

    Arguments:
        parent: The parent in which to locate the storage location (mutually exclusive with folder)
        folder_name: The name of a new folder to create (mutually exclusive with folder)
        folder: The existing folder in which to create the storage location (mutually exclusive with folder_name)
        bucket_name: The name of an S3 bucket, if this is an external storage location,
                        if None will use Synapse S3 storage
        base_key: The base key of within the bucket, None to use the bucket root,
                        only applicable if bucket_name is passed
        sts_enabled: Whether this storage location should be STS enabled

    Returns:
        A 3-tuple of the synapse Folder, a the storage location setting, and the project setting dictionaries.

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # folder, storage_setting, project_setting = syn.create_s3_storage_location(
        #     parent="syn123",
        #     folder_name="my-external-storage",
        #     bucket_name="my-bucket",
        # )

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Folder, StorageLocation, StorageLocationType

        syn = Synapse()
        syn.login()

        # Create the storage location backed by your own S3 bucket
        storage = StorageLocation(
            storage_type=StorageLocationType.EXTERNAL_S3,
            bucket="my-bucket",
        ).store()

        # Create a folder to hold the externally stored files
        folder = Folder(name="my-external-storage", parent_id="syn123").store()

        # Apply the storage location as the folder's upload destination
        folder.set_storage_location(storage_location_id=storage.storage_location_id)
        ```
    """
    return wrap_async_to_sync(
        self.create_s3_storage_location_async(
            parent=parent,
            folder_name=folder_name,
            folder=folder,
            bucket_name=bucket_name,
            base_key=base_key,
            sts_enabled=sts_enabled,
        )
    )

setStorageLocation

setStorageLocation(entity, storage_location_id)

Sets the storage location for a Project or Folder

PARAMETER DESCRIPTION
entity

A Project or Folder to which the StorageLocationSetting is set

storage_location_id

A StorageLocation id or a list of StorageLocation ids. Pass in None for the default Synapse storage.

RETURNS DESCRIPTION

The created or updated settings as a dict.

Source code in synapseclient/client.py
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `Folder(id=...).set_storage_location(...)` or "
    "`Project(id=...).set_storage_location(...)` from synapseclient.models instead.",
)
def setStorageLocation(self, entity, storage_location_id):
    """
    Sets the storage location for a Project or Folder

    Arguments:
        entity: A Project or Folder to which the StorageLocationSetting is set
        storage_location_id: A StorageLocation id or a list of StorageLocation ids. Pass in None for the default
                                Synapse storage.

    Returns:
        The created or updated settings as a dict.
    """
    if storage_location_id is None:
        storage_location_id = DEFAULT_STORAGE_LOCATION_ID
    locations = (
        storage_location_id
        if isinstance(storage_location_id, list)
        else [storage_location_id]
    )

    existing_setting = self.getProjectSetting(entity, "upload")
    if existing_setting is not None:
        existing_setting["locations"] = locations
        self.restPUT("/projectSettings", body=json.dumps(existing_setting))
        return self.getProjectSetting(entity, "upload")
    else:
        project_destination = {
            "concreteType": "org.sagebionetworks.repo.model.project.UploadDestinationListSetting",
            "settingsType": "upload",
            "locations": locations,
            "projectId": id_of(entity),
        }

        return self.restPOST(
            "/projectSettings", body=json.dumps(project_destination)
        )

get_sts_storage_token

get_sts_storage_token(entity, permission, *, output_format='json', min_remaining_life=None)

Get STS credentials for the given entity_id and permission, outputting it in the given format

PARAMETER DESCRIPTION
entity

The entity or entity id whose credentials are being returned

permission

One of:

  • read_only
  • read_write

output_format

One of:

  • json: the dictionary returned from the Synapse STS API including expiration
  • boto: a dictionary compatible with a boto session (aws_access_key_id, etc)
  • shell: output commands for exporting credentials appropriate for the detected shell
  • bash: output commands for exporting credentials into a bash shell
  • cmd: output commands for exporting credentials into a windows cmd shell
  • powershell: output commands for exporting credentials into a windows powershell

DEFAULT: 'json'

min_remaining_life

The minimum allowable remaining life on a cached token to return. If a cached token has left than this amount of time left a fresh token will be fetched

DEFAULT: None

Source code in synapseclient/client.py
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `Folder(id=...).get_sts_storage_token(...)` or "
    "`Project(id=...).get_sts_storage_token(...)` from synapseclient.models instead.",
)
def get_sts_storage_token(
    self, entity, permission, *, output_format="json", min_remaining_life=None
):
    """Get STS credentials for the given entity_id and permission, outputting it in the given format

    Arguments:
        entity: The entity or entity id whose credentials are being returned
        permission: One of:

            - `read_only`
            - `read_write`

        output_format: One of:

            - `json`: the dictionary returned from the Synapse STS API including expiration
            - `boto`: a dictionary compatible with a boto session (aws_access_key_id, etc)
            - `shell`: output commands for exporting credentials appropriate for the detected shell
            - `bash`: output commands for exporting credentials into a bash shell
            - `cmd`: output commands for exporting credentials into a windows cmd shell
            - `powershell`: output commands for exporting credentials into a windows powershell

        min_remaining_life: The minimum allowable remaining life on a cached token to return. If a cached token
                            has left than this amount of time left a fresh token will be fetched
    """
    return sts_transfer.get_sts_credentials(
        self,
        id_of(entity),
        permission,
        output_format=output_format,
        min_remaining_life=min_remaining_life,
    )

create_snapshot_version

create_snapshot_version(table: Union[EntityViewSchema, Schema, str, SubmissionViewSchema, Dataset], comment: str = None, label: str = None, activity: Union[Activity, str] = None, wait: bool = True) -> int

Deprecated with replacement. This method will be removed in 5.0.0. Use the .snapshot() method on the Table, EntityView, SubmissionView, or Dataset classes instead.

Create a new Table Version, new View version, or new Dataset version.

PARAMETER DESCRIPTION
table

The schema of the Table/View, or its ID.

TYPE: Union[EntityViewSchema, Schema, str, SubmissionViewSchema, Dataset]

comment

Optional snapshot comment.

TYPE: str DEFAULT: None

label

Optional snapshot label.

TYPE: str DEFAULT: None

activity

Optional activity ID applied to snapshot version.

TYPE: Union[Activity, str] DEFAULT: None

wait

True if this method should return the snapshot version after waiting for any necessary asynchronous table updates to complete. If False this method will return as soon as any updates are initiated.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
int

The snapshot version number if wait=True, None if wait=False

Using this function (DEPRECATED)

Creating a snapshot of a table

table_id = "syn1234"
snapshot_version = syn.create_snapshot_version(
    table_id,
    comment="This is a snapshot",
    label="v1.0",
    activity=my_activity
)
Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Table, EntityView, SubmissionView, Dataset

# Login to Synapse
syn = Synapse()
syn.login()

# For Tables
table = Table(id="syn1234")
snapshot_response = table.snapshot(
    comment="This is a snapshot",
    label="v1.0",
    include_activity=True,
    associate_activity_to_new_version=True
)
print(f"Snapshot version: {snapshot_response['snapshotVersionNumber']}")

# For Entity Views
view = EntityView(id="syn5678")
snapshot_transaction = view.snapshot(
    comment="This is a snapshot",
    label="v1.0",
    include_activity=True,
    associate_activity_to_new_version=True
)
print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

# For Submission Views
submission_view = SubmissionView(id="syn9012")
snapshot_transaction = submission_view.snapshot(
    comment="This is a snapshot",
    label="v1.0",
    include_activity=True,
    associate_activity_to_new_version=True
)
print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

# For Datasets
dataset = Dataset(id="syn3456")
snapshot_transaction = dataset.snapshot(
    comment="This is a snapshot",
    label="v1.0",
    include_activity=True,
    associate_activity_to_new_version=True
)
print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")
Source code in synapseclient/client.py
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Use the `.snapshot()` method on the `Table`, `EntityView`, `SubmissionView`, or `Dataset` classes instead. "
    "Check the docstring for the replacement function example.",
)
def create_snapshot_version(
    self,
    table: typing.Union[
        EntityViewSchema, Schema, str, SubmissionViewSchema, Dataset
    ],
    comment: str = None,
    label: str = None,
    activity: typing.Union[Activity, str] = None,
    wait: bool = True,
) -> int:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use the `.snapshot()` method on the `Table`, `EntityView`, `SubmissionView`, or `Dataset` classes instead.

    Create a new Table Version, new View version, or new Dataset version.

    Arguments:
        table: The schema of the Table/View, or its ID.
        comment: Optional snapshot comment.
        label: Optional snapshot label.
        activity: Optional activity ID applied to snapshot version.
        wait: True if this method should return the snapshot version after waiting for any necessary
                asynchronous table updates to complete. If False this method will return
                as soon as any updates are initiated.

    Returns:
        The snapshot version number if wait=True, None if wait=False

    Example: Using this function (DEPRECATED)
        Creating a snapshot of a table

            table_id = "syn1234"
            snapshot_version = syn.create_snapshot_version(
                table_id,
                comment="This is a snapshot",
                label="v1.0",
                activity=my_activity
            )

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Table, EntityView, SubmissionView, Dataset

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # For Tables
        table = Table(id="syn1234")
        snapshot_response = table.snapshot(
            comment="This is a snapshot",
            label="v1.0",
            include_activity=True,
            associate_activity_to_new_version=True
        )
        print(f"Snapshot version: {snapshot_response['snapshotVersionNumber']}")

        # For Entity Views
        view = EntityView(id="syn5678")
        snapshot_transaction = view.snapshot(
            comment="This is a snapshot",
            label="v1.0",
            include_activity=True,
            associate_activity_to_new_version=True
        )
        print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

        # For Submission Views
        submission_view = SubmissionView(id="syn9012")
        snapshot_transaction = submission_view.snapshot(
            comment="This is a snapshot",
            label="v1.0",
            include_activity=True,
            associate_activity_to_new_version=True
        )
        print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")

        # For Datasets
        dataset = Dataset(id="syn3456")
        snapshot_transaction = dataset.snapshot(
            comment="This is a snapshot",
            label="v1.0",
            include_activity=True,
            associate_activity_to_new_version=True
        )
        print(f"Snapshot version: {snapshot_transaction.snapshot_version_number}")
        ```
    """
    ent = self.get(id_of(table), downloadFile=False)
    if isinstance(ent, (EntityViewSchema, SubmissionViewSchema, Dataset)):
        result = self._async_table_update(
            table,
            create_snapshot=True,
            comment=comment,
            label=label,
            activity=activity,
            wait=wait,
        )
    elif isinstance(ent, Schema):
        result = self._create_table_snapshot(
            table,
            comment=comment,
            label=label,
            activity=activity,
        )
    else:
        raise ValueError(
            "This function only accepts Synapse ids of Tables or Views"
        )

    # for consistency we return nothing if wait=False since we can't
    # supply the snapshot version on an async table update without waiting
    return result["snapshotVersionNumber"] if wait else None

getConfigFile cached

getConfigFile(configPath: str) -> RawConfigParser

Retrieves the client configuration information.

PARAMETER DESCRIPTION
configPath

Path to configuration file on local file system

TYPE: str

RETURNS DESCRIPTION
RawConfigParser

A RawConfigParser populated with properties from the user's configuration file.

Source code in synapseclient/client.py
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
@deprecated(
    version="4.4.0",
    reason="To be removed in 5.0.0. "
    "Moved to synapseclient/api/configuration_services.py::get_config_file",
)
@functools.lru_cache()
def getConfigFile(self, configPath: str) -> configparser.RawConfigParser:
    """
    Retrieves the client configuration information.

    Arguments:
        configPath:  Path to configuration file on local file system

    Returns:
        A RawConfigParser populated with properties from the user's configuration file.
    """

    try:
        config = configparser.RawConfigParser()
        config.read(configPath)  # Does not fail if the file does not exist
        return config
    except configparser.Error as ex:
        raise ValueError(
            "Error parsing Synapse config file: {}".format(configPath)
        ) from ex

getEvaluation

getEvaluation(id)

Gets an Evaluation object from Synapse.

PARAMETER DESCRIPTION
id

The ID of the synapseclient.evaluation.Evaluation to return.

RETURNS DESCRIPTION
Using this function

Creating an Evaluation instance

evaluation = syn.getEvaluation(2005090)
Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# evaluation = syn.getEvaluation(2005090)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Evaluation

syn = Synapse()
syn.login()

evaluation = Evaluation(id="2005090").get()
Source code in synapseclient/client.py
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.Evaluation` model instead, e.g. "
    "`Evaluation(id=...).get()`.",
)
def getEvaluation(self, id):
    """
    Gets an Evaluation object from Synapse.

    Arguments:
        id: The ID of the [synapseclient.evaluation.Evaluation][] to return.

    Returns:
        An [synapseclient.evaluation.Evaluation][] object

    Example: Using this function
        Creating an Evaluation instance

            evaluation = syn.getEvaluation(2005090)

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # evaluation = syn.getEvaluation(2005090)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Evaluation

        syn = Synapse()
        syn.login()

        evaluation = Evaluation(id="2005090").get()
        ```
    """

    evaluation_id = id_of(id)
    uri = Evaluation.getURI(evaluation_id)
    return Evaluation(**self.restGET(uri))

getEvaluationByContentSource

getEvaluationByContentSource(entity)

Returns a generator over evaluations that derive their content from the given entity

PARAMETER DESCRIPTION
entity

The synapseclient.entity.Project whose Evaluations are to be fetched.

YIELDS DESCRIPTION

A generator over synapseclient.evaluation.Evaluation objects for the given synapseclient.entity.Project.

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# evaluations = syn.getEvaluationByContentSource("syn123")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Evaluation

syn = Synapse()
syn.login()

evaluations = Evaluation.get_evaluations_by_project(project_id="syn123")
Source code in synapseclient/client.py
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.models.Evaluation.get_evaluations_by_project()` instead.",
)
def getEvaluationByContentSource(self, entity):
    """
    Returns a generator over evaluations that derive their content from the given entity

    Arguments:
        entity: The [synapseclient.entity.Project][] whose Evaluations are to be fetched.

    Yields:
        A generator over [synapseclient.evaluation.Evaluation][] objects for the given [synapseclient.entity.Project][].

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # evaluations = syn.getEvaluationByContentSource("syn123")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Evaluation

        syn = Synapse()
        syn.login()

        evaluations = Evaluation.get_evaluations_by_project(project_id="syn123")
        ```
    """

    entityId = id_of(entity)
    url = "/entity/%s/evaluation" % entityId

    for result in self._GET_paginated(url):
        yield Evaluation(**result)

getEvaluationByName

getEvaluationByName(name)

Gets an Evaluation object from Synapse.

PARAMETER DESCRIPTION
Name

The name of the synapseclient.evaluation.Evaluation to return.

RETURNS DESCRIPTION
Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# evaluation = syn.getEvaluationByName("My Evaluation")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Evaluation

syn = Synapse()
syn.login()

evaluation = Evaluation(name="My Evaluation").get()
Source code in synapseclient/client.py
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.Evaluation` model instead, e.g. "
    "`Evaluation(name=...).get()`.",
)
def getEvaluationByName(self, name):
    """
    Gets an Evaluation object from Synapse.

    Arguments:
        Name: The name of the [synapseclient.evaluation.Evaluation][] to return.

    Returns:
        An [synapseclient.evaluation.Evaluation][] object

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # evaluation = syn.getEvaluationByName("My Evaluation")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Evaluation

        syn = Synapse()
        syn.login()

        evaluation = Evaluation(name="My Evaluation").get()
        ```
    """
    uri = Evaluation.getByNameURI(name)
    return Evaluation(**self.restGET(uri))

create_team

create_team(name: str, description: str = None, icon: str = None, can_public_join: bool = False, can_request_membership: bool = True) -> Team

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.create instead.

Creates a new team.

PARAMETER DESCRIPTION
name

The name of the team to create.

TYPE: str

description

A description of the team.

TYPE: str DEFAULT: None

icon

The FileHandleID of the icon to be used for the team.

TYPE: str DEFAULT: None

canPublicJoin

Whether the team can be joined by anyone. Defaults to False.

canRequestMembership

Whether the team can request membership. Defaults to True.

RETURNS DESCRIPTION
Team

An object of type synapseclient.team.Team

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Create a new team
new_team = Team(
    name="My Team",
    description="A sample team",
    can_public_join=False,
    can_request_membership=True
)
created_team = new_team.create()
print(f"Created team: {created_team.name}")
Source code in synapseclient/client.py
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `create` method on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def create_team(
    self,
    name: str,
    description: str = None,
    icon: str = None,
    can_public_join: bool = False,
    can_request_membership: bool = True,
) -> Team:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.create][] instead.

    Creates a new team.

    Arguments:
        name: The name of the team to create.
        description: A description of the team.
        icon: The FileHandleID of the icon to be used for the team.
        canPublicJoin: Whether the team can be joined by anyone. Defaults to False.
        canRequestMembership: Whether the team can request membership. Defaults to True.

    Returns:
        An object of type [synapseclient.team.Team][]

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Create a new team
        new_team = Team(
            name="My Team",
            description="A sample team",
            can_public_join=False,
            can_request_membership=True
        )
        created_team = new_team.create()
        print(f"Created team: {created_team.name}")
        ```
    """
    request_body = {
        "name": name,
        "description": description,
        "icon": icon,
        "canPublicJoin": can_public_join,
        "canRequestMembership": can_request_membership,
    }
    return Team(
        **self.restPOST(
            "/team",
            json.dumps(request_body),
        )
    )

delete_team

delete_team(id: int) -> None

Deprecated with replacement. This method will be removed in 5.0.0. Use synapseclient.models.Team.delete instead.

Deletes a team.

PARAMETER DESCRIPTION
id

The ID of the team to delete.

TYPE: int

Migration to new method

 

from synapseclient import Synapse
from synapseclient.models import Team

# Login to Synapse
syn = Synapse()
syn.login()

# Delete a team
team = Team(id=12345)
team.delete()
Source code in synapseclient/client.py
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to the `delete` method on the `from synapseclient.models import Team` class. "
    "Check the docstring for the replacement function example.",
)
def delete_team(self, id: int) -> None:
    """
    **Deprecated with replacement.** This method will be removed in 5.0.0.
    Use [synapseclient.models.Team.delete][] instead.

    Deletes a team.

    Arguments:
        id: The ID of the team to delete.

    Example: Migration to new method
        &nbsp;

        ```python
        from synapseclient import Synapse
        from synapseclient.models import Team

        # Login to Synapse
        syn = Synapse()
        syn.login()

        # Delete a team
        team = Team(id=12345)
        team.delete()
        ```

    """
    return self.restDELETE(f"/team/{id}")

getProjectSetting

getProjectSetting(project, setting_type)

Gets the ProjectSetting for a project.

PARAMETER DESCRIPTION
project

Project entity or its id as a string

setting_type

Type of setting. Choose from:

  • upload
  • external_sync
  • requester_pays

RETURNS DESCRIPTION

The ProjectSetting as a dict or None if no settings of the specified type exist.

Source code in synapseclient/client.py
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
@deprecated(
    version="4.12.0",
    reason="To be removed in 5.0.0. "
    "Use `Folder(id=...).get_project_setting(...)` or "
    "`Project(id=...).get_project_setting(...)` from synapseclient.models instead.",
)
def getProjectSetting(self, project, setting_type):
    """
    Gets the ProjectSetting for a project.

    Arguments:
        project: Project entity or its id as a string
        setting_type: Type of setting. Choose from:

            - `upload`
            - `external_sync`
            - `requester_pays`

    Returns:
        The ProjectSetting as a dict or None if no settings of the specified type exist.
    """
    if setting_type not in {"upload", "external_sync", "requester_pays"}:
        raise ValueError("Invalid project_type: %s" % setting_type)

    response = self.restGET(
        "/projectSettings/{projectId}/type/{type}".format(
            projectId=id_of(project), type=setting_type
        )
    )
    return (
        response if response else None
    )  # if no project setting, a empty string is returned as the response

getSubmission

getSubmission(id: Union[str, int, Mapping], **kwargs) -> Submission

Gets a synapseclient.evaluation.Submission object based on a given ID or previous synapseclient.evaluation.Submission object.

PARAMETER DESCRIPTION
id

The ID of the submission to retrieve or a synapseclient.evaluation.Submission object

TYPE: Union[str, int, Mapping]

RETURNS DESCRIPTION
Submission

See:

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# submission = syn.getSubmission(9700123)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Submission

syn = Synapse()
syn.login()

submission = Submission(id="9700123").get()
Source code in synapseclient/client.py
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.Submission` model instead, e.g. "
    "`Submission(id=...).get()`.",
)
def getSubmission(
    self, id: typing.Union[str, int, collections.abc.Mapping], **kwargs
) -> Submission:
    """
    Gets a [synapseclient.evaluation.Submission][] object based on a given ID
    or previous [synapseclient.evaluation.Submission][] object.

    Arguments:
        id: The ID of the submission to retrieve or a [synapseclient.evaluation.Submission][] object

    Returns:
        A [synapseclient.evaluation.Submission][] object

    See:

    - [synapseclient.Synapse.get][] for information
         on the *downloadFile*, *downloadLocation*, and *ifcollision* parameters

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # submission = syn.getSubmission(9700123)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Submission

        syn = Synapse()
        syn.login()

        submission = Submission(id="9700123").get()
        ```
    """
    return wrap_async_to_sync(self.getSubmission_async(id=id, **kwargs))

getSubmissions

getSubmissions(evaluation, status=None, myOwn=False, limit=20, offset=0)
PARAMETER DESCRIPTION
evaluation

Evaluation to get submissions from.

status

Optionally filter submissions for a specific status. One of:

  • OPEN
  • CLOSED
  • SCORED
  • INVALID
  • VALIDATED
  • EVALUATION_IN_PROGRESS
  • RECEIVED
  • REJECTED
  • ACCEPTED

DEFAULT: None

myOwn

Determines if only your Submissions should be fetched. Defaults to False (all Submissions)

DEFAULT: False

limit

Limits the number of submissions in a single response. Because this method returns a generator and repeatedly fetches submissions, this argument is limiting the size of a single request and NOT the number of sub- missions returned in total.

DEFAULT: 20

offset

Start iterating at a submission offset from the first submission.

DEFAULT: 0

YIELDS DESCRIPTION

A generator over synapseclient.evaluation.Submission objects for an Evaluation

Using this function

Print submissions

for submission in syn.getSubmissions(1234567):
    print(submission['entityId'])

See:

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# for submission in syn.getSubmissions(1234567):
#     print(submission)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import Submission

syn = Synapse()
syn.login()

# All submissions for an evaluation
for submission in Submission.get_evaluation_submissions(evaluation_id="1234567"):
    print(submission)

# Only your own submissions (equivalent to myOwn=True)
for submission in Submission.get_user_submissions(evaluation_id="1234567"):
    print(submission)
Source code in synapseclient/client.py
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.models.Submission.get_evaluation_submissions()` (or "
    "`get_user_submissions()` for your own submissions) instead.",
)
def getSubmissions(self, evaluation, status=None, myOwn=False, limit=20, offset=0):
    """
    Arguments:
        evaluation: Evaluation to get submissions from.
        status: Optionally filter submissions for a specific status.
                One of:

            - `OPEN`
            - `CLOSED`
            - `SCORED`
            - `INVALID`
            - `VALIDATED`
            - `EVALUATION_IN_PROGRESS`
            - `RECEIVED`
            - `REJECTED`
            - `ACCEPTED`

        myOwn: Determines if only your Submissions should be fetched.
                 Defaults to False (all Submissions)
        limit: Limits the number of submissions in a single response.
                    Because this method returns a generator and repeatedly
                    fetches submissions, this argument is limiting the
                    size of a single request and NOT the number of sub-
                    missions returned in total.
        offset: Start iterating at a submission offset from the first submission.

    Yields:
        A generator over [synapseclient.evaluation.Submission][] objects for an Evaluation

    Example: Using this function
        Print submissions

            for submission in syn.getSubmissions(1234567):
                print(submission['entityId'])

    See:

    - [synapseclient.evaluation][]

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # for submission in syn.getSubmissions(1234567):
        #     print(submission)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import Submission

        syn = Synapse()
        syn.login()

        # All submissions for an evaluation
        for submission in Submission.get_evaluation_submissions(evaluation_id="1234567"):
            print(submission)

        # Only your own submissions (equivalent to myOwn=True)
        for submission in Submission.get_user_submissions(evaluation_id="1234567"):
            print(submission)
        ```
    """

    evaluation_id = id_of(evaluation)
    uri = "/evaluation/%s/submission%s" % (evaluation_id, "" if myOwn else "/all")

    if status is not None:
        uri += "?status=%s" % status

    for result in self._GET_paginated(uri, limit=limit, offset=offset):
        yield Submission(**result)

getSubmissionBundles

getSubmissionBundles(evaluation, status=None, myOwn=False, limit=20, offset=0)

Retrieve submission bundles (submission and submissions status) for an evaluation queue, optionally filtered by submission status and/or owner.

PARAMETER DESCRIPTION
evaluation

Evaluation to get submissions from.

status

Optionally filter submissions for a specific status. One of:

  • OPEN
  • CLOSED
  • SCORED
  • INVALID

DEFAULT: None

myOwn

Determines if only your Submissions should be fetched. Defaults to False (all Submissions)

DEFAULT: False

limit

Limits the number of submissions coming back from the service in a single response.

DEFAULT: 20

offset

Start iterating at a submission offset from the first submission.

DEFAULT: 0

YIELDS DESCRIPTION
Using this function

Loop over submissions

for submission, status in syn.getSubmissionBundles(evaluation):
    print(submission.name,
          submission.submitterAlias,
          status.status,
          status.score)

This may later be changed to return objects, pending some thought on how submissions along with related status and annotations should be represented in the clients.

See: - synapseclient.evaluation

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# for submission, status in syn.getSubmissionBundles(1234567):
#     print(submission, status)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import SubmissionBundle

syn = Synapse()
syn.login()

# All submission bundles for an evaluation
for bundle in SubmissionBundle.get_evaluation_submission_bundles(evaluation_id="1234567"):
    print(bundle.submission, bundle.submission_status)

# Only your own submission bundles (equivalent to myOwn=True)
for bundle in SubmissionBundle.get_user_submission_bundles(evaluation_id="1234567"):
    print(bundle.submission, bundle.submission_status)
Source code in synapseclient/client.py
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.models.SubmissionBundle.get_evaluation_submission_bundles()` "
    "(or `get_user_submission_bundles()` for your own) instead.",
)
def getSubmissionBundles(
    self, evaluation, status=None, myOwn=False, limit=20, offset=0
):
    """
    Retrieve submission bundles (submission and submissions status) for an evaluation queue, optionally filtered by
    submission status and/or owner.

    Arguments:
        evaluation: Evaluation to get submissions from.
        status:     Optionally filter submissions for a specific status.
                    One of:

            - `OPEN`
            - `CLOSED`
            - `SCORED`
            - `INVALID`

        myOwn:      Determines if only your Submissions should be fetched.
                    Defaults to False (all Submissions)
        limit:      Limits the number of submissions coming back from the
                    service in a single response.
        offset:     Start iterating at a submission offset from the first submission.

    Yields:
        A generator over tuples containing a [synapseclient.evaluation.Submission][] and a [synapseclient.evaluation.SubmissionStatus][].

    Example: Using this function
        Loop over submissions

            for submission, status in syn.getSubmissionBundles(evaluation):
                print(submission.name,
                      submission.submitterAlias,
                      status.status,
                      status.score)

    This may later be changed to return objects, pending some thought on how submissions along with related status
    and annotations should be represented in the clients.

    See:
    - [synapseclient.evaluation][]

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # for submission, status in syn.getSubmissionBundles(1234567):
        #     print(submission, status)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import SubmissionBundle

        syn = Synapse()
        syn.login()

        # All submission bundles for an evaluation
        for bundle in SubmissionBundle.get_evaluation_submission_bundles(evaluation_id="1234567"):
            print(bundle.submission, bundle.submission_status)

        # Only your own submission bundles (equivalent to myOwn=True)
        for bundle in SubmissionBundle.get_user_submission_bundles(evaluation_id="1234567"):
            print(bundle.submission, bundle.submission_status)
        ```
    """
    for bundle in self._getSubmissionBundles(
        evaluation, status=status, myOwn=myOwn, limit=limit, offset=offset
    ):
        yield (
            Submission(**bundle["submission"]),
            SubmissionStatus(**bundle["submissionStatus"]),
        )

getSubmissionStatus

getSubmissionStatus(submission: Union[str, int, Mapping]) -> SubmissionStatus

Downloads the status of a Submission given its ID or previous synapseclient.evaluation.Submission object.

PARAMETER DESCRIPTION
submission

The submission to lookup (ID or synapseclient.evaluation.Submission object)

TYPE: Union[str, int, Mapping]

RETURNS DESCRIPTION
SubmissionStatus
Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# status = syn.getSubmissionStatus(9700123)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import SubmissionStatus

syn = Synapse()
syn.login()

status = SubmissionStatus(id="9700123").get()
Source code in synapseclient/client.py
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.SubmissionStatus` model instead, e.g. "
    "`SubmissionStatus(id=...).get()`.",
)
def getSubmissionStatus(
    self, submission: typing.Union[str, int, collections.abc.Mapping]
) -> SubmissionStatus:
    """
    Downloads the status of a Submission given its ID or previous [synapseclient.evaluation.Submission][] object.

    Arguments:
        submission: The submission to lookup (ID or [synapseclient.evaluation.Submission][] object)

    Returns:
        A [synapseclient.evaluation.SubmissionStatus][] object

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # status = syn.getSubmissionStatus(9700123)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import SubmissionStatus

        syn = Synapse()
        syn.login()

        status = SubmissionStatus(id="9700123").get()
        ```
    """

    submission_id = validate_submission_id(submission)
    uri = SubmissionStatus.getURI(submission_id)
    val = self.restGET(uri)
    return SubmissionStatus(**val)

getWiki

getWiki(owner, subpageId=None, version=None)

Get a synapseclient.wiki.Wiki object from Synapse. Uses wiki2 API which supports versioning.

PARAMETER DESCRIPTION
owner

The entity to which the Wiki is attached

subpageId

The id of the specific sub-page or None to get the root Wiki page

DEFAULT: None

version

The version of the page to retrieve or None to retrieve the latest

DEFAULT: None

RETURNS DESCRIPTION
Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# wiki = syn.getWiki("syn123", subpageId="456")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import WikiPage

syn = Synapse()
syn.login()

wiki = WikiPage(owner_id="syn123", id="456").get()
Source code in synapseclient/client.py
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the `synapseclient.models.WikiPage` model instead, e.g. "
    "`WikiPage(owner_id=..., id=...).get()`.",
)
def getWiki(self, owner, subpageId=None, version=None):
    """
    Get a [synapseclient.wiki.Wiki][] object from Synapse. Uses wiki2 API which supports versioning.

    Arguments:
        owner: The entity to which the Wiki is attached
        subpageId: The id of the specific sub-page or None to get the root Wiki page
        version: The version of the page to retrieve or None to retrieve the latest

    Returns:
        A [synapseclient.wiki.Wiki][] object

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # wiki = syn.getWiki("syn123", subpageId="456")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import WikiPage

        syn = Synapse()
        syn.login()

        wiki = WikiPage(owner_id="syn123", id="456").get()
        ```
    """
    return wrap_async_to_sync(
        self.getWiki_async(owner, subpageId=subpageId, version=version)
    )

getWikiAttachments

getWikiAttachments(wiki)

Retrieve the attachments to a wiki page.

PARAMETER DESCRIPTION
wiki

The Wiki object for which the attachments are to be returned.

RETURNS DESCRIPTION

A list of file handles for the files attached to the Wiki.

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# attachments = syn.getWikiAttachments(wiki)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import WikiPage

syn = Synapse()
syn.login()

attachments = WikiPage(owner_id="syn123", id="456").get_attachment_handles()
Source code in synapseclient/client.py
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.models.WikiPage.get_attachment_handles()` on the WikiPage "
    "instead.",
)
def getWikiAttachments(self, wiki):
    """
    Retrieve the attachments to a wiki page.

    Arguments:
        wiki: The Wiki object for which the attachments are to be returned.

    Returns:
        A list of file handles for the files attached to the Wiki.

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # attachments = syn.getWikiAttachments(wiki)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import WikiPage

        syn = Synapse()
        syn.login()

        attachments = WikiPage(owner_id="syn123", id="456").get_attachment_handles()
        ```
    """
    uri = "/entity/%s/wiki/%s/attachmenthandles" % (wiki.ownerId, wiki.id)
    results = self.restGET(uri)
    file_handles = list(WikiAttachment(**fh) for fh in results["list"])
    return file_handles

getWikiHeaders

getWikiHeaders(owner)

Retrieves the headers of all Wikis belonging to the owner (the entity to which the Wiki is attached).

PARAMETER DESCRIPTION
owner

An Entity

RETURNS DESCRIPTION

A list of Objects with three fields: id, title and parentId.

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# headers = syn.getWikiHeaders("syn123")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import WikiHeader

syn = Synapse()
syn.login()

for header in WikiHeader.get(owner_id="syn123"):
    print(header)
Source code in synapseclient/client.py
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use `synapseclient.models.WikiHeader.get(owner_id=...)` instead.",
)
def getWikiHeaders(self, owner):
    """
    Retrieves the headers of all Wikis belonging to the owner (the entity to which the Wiki is attached).

    Arguments:
        owner: An Entity

    Returns:
        A list of Objects with three fields: id, title and parentId.

    Example: Migration to the object-oriented model
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # headers = syn.getWikiHeaders("syn123")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import WikiHeader

        syn = Synapse()
        syn.login()

        for header in WikiHeader.get(owner_id="syn123"):
            print(header)
        ```
    """

    uri = "/entity/%s/wikiheadertree" % id_of(owner)
    return [DictObject(**header) for header in self._GET_paginated(uri)]

get_download_list

get_download_list(downloadLocation: str = None) -> str

Download all files from your Synapse download list

Migration to new method

 

# Old approach (DEPRECATED)
# manifest_path = syn.get_download_list(downloadLocation="./downloads")

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.operations import download_list_files

syn = Synapse()
syn.login()

# Download all files in the cart and get the result manifest path
manifest_path = download_list_files(download_location="./downloads")
PARAMETER DESCRIPTION
downloadLocation

Directory to download files to.

TYPE: str DEFAULT: None

RETURNS DESCRIPTION
str

Manifest file with file paths

Source code in synapseclient/client.py
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
@deprecated(
    version="4.13.0",
    reason=(
        "Use `synapseclient.operations.download_list_files(download_location=...)` instead. "
        "See synapseclient.operations.download_list_operations for the new interface."
    ),
)
def get_download_list(self, downloadLocation: str = None) -> str:
    """Download all files from your Synapse download list

    Example: Migration to new method
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # manifest_path = syn.get_download_list(downloadLocation="./downloads")

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.operations import download_list_files

        syn = Synapse()
        syn.login()

        # Download all files in the cart and get the result manifest path
        manifest_path = download_list_files(download_location="./downloads")
        ```

    Arguments:
        downloadLocation: Directory to download files to.

    Returns:
        Manifest file with file paths
    """
    dl_list_path = self.get_download_list_manifest()
    downloaded_files = []
    new_manifest_path = f"manifest_{time.time_ns()}.csv"
    with (
        open(dl_list_path) as manifest_f,
        open(new_manifest_path, "w") as write_obj,
    ):
        reader = csv.DictReader(manifest_f)
        columns = reader.fieldnames
        columns.extend(["path", "error"])
        # Write the downloaded paths to a new manifest file
        writer = csv.DictWriter(write_obj, fieldnames=columns)
        writer.writeheader()

        for row in reader:
            # You can add things to the download list that you don't have access to
            # So there must be a try catch here
            try:
                entity = self.get(row["ID"], downloadLocation=downloadLocation)
                # Must include version number because you can have multiple versions of a
                # file in the download list
                downloaded_files.append(
                    {
                        "fileEntityId": row["ID"],
                        "versionNumber": row["versionNumber"],
                    }
                )
                row["path"] = entity.path
                row["error"] = ""
            except Exception:
                row["path"] = ""
                row["error"] = "DOWNLOAD FAILED"
                self.logger.exception("Unable to download file")
            writer.writerow(row)

    # Don't want to clear all the download list because you can add things
    # to the download list after initiating this command.
    # Files that failed to download should not be removed from download list
    # Remove all files from download list after the entire download is complete.
    # This is because if download fails midway, we want to return the full manifest
    if downloaded_files:
        # Only want to invoke this if there is a list of files to remove
        # or the API call will error
        self.remove_from_download_list(list_of_files=downloaded_files)
    else:
        self.logger.warning("A manifest was created, but no files were downloaded")

    # Always remove original manifest file
    os.remove(dl_list_path)

    return new_manifest_path

get_download_list_manifest

get_download_list_manifest()

Get the path of the download list manifest file

Migration to new method

 

# Old approach (DEPRECATED)
# manifest_path = syn.get_download_list_manifest()

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.operations import download_list_manifest

syn = Synapse()
syn.login()

# Generate and download the manifest CSV
manifest_path = download_list_manifest()
RETURNS DESCRIPTION

Path of download list manifest file

Source code in synapseclient/client.py
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
@deprecated(
    version="4.13.0",
    reason=(
        "Use `synapseclient.operations.download_list_manifest()` instead. "
        "See synapseclient.operations.download_list_operations for the new interface."
    ),
)
def get_download_list_manifest(self):
    """Get the path of the download list manifest file

    Example: Migration to new method
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # manifest_path = syn.get_download_list_manifest()

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.operations import download_list_manifest

        syn = Synapse()
        syn.login()

        # Generate and download the manifest CSV
        manifest_path = download_list_manifest()
        ```

    Returns:
        Path of download list manifest file
    """
    manifest = self._generate_manifest_from_download_list()
    # Get file handle download link
    file_result = get_file_handle_for_download(
        file_handle_id=manifest["resultFileHandleId"],
        synapse_id=manifest["resultFileHandleId"],
        entity_type="FileEntity",
        synapse_client=self,
    )
    # Download the manifest
    downloaded_path = self._download_from_URL(
        url=file_result["preSignedURL"],
        destination="./",
        fileHandleId=file_result["fileHandleId"],
        expected_md5=file_result["fileHandle"].get("contentMd5"),
    )
    trace.get_current_span().set_attributes(
        {"synapse.file_handle_id": file_result["fileHandleId"]}
    )
    return downloaded_path

remove_from_download_list

remove_from_download_list(list_of_files: List[Dict]) -> int

Remove a batch of files from download list

Migration to new method

 

# Old approach (DEPRECATED)
# syn.remove_from_download_list([
#     {"fileEntityId": "syn123", "versionNumber": 1},
# ])

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.operations import download_list_remove, DownloadListItem

syn = Synapse()
syn.login()

# Remove specific file versions from the download list
download_list_remove([
    DownloadListItem(file_entity_id="syn123", version_number=1),
])
PARAMETER DESCRIPTION
list_of_files

Array of files in the format of a mapping {fileEntityId: synid, versionNumber: version}

TYPE: List[Dict]

RETURNS DESCRIPTION
int

Number of files removed from download list

Source code in synapseclient/client.py
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
@deprecated(
    version="4.13.0",
    reason=(
        "Use `synapseclient.operations.download_list_remove(files)` instead. "
        "See synapseclient.operations.download_list_operations for the new interface."
    ),
)
def remove_from_download_list(self, list_of_files: typing.List[typing.Dict]) -> int:
    """Remove a batch of files from download list

    Example: Migration to new method
        &nbsp;

        ```python
        # Old approach (DEPRECATED)
        # syn.remove_from_download_list([
        #     {"fileEntityId": "syn123", "versionNumber": 1},
        # ])

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.operations import download_list_remove, DownloadListItem

        syn = Synapse()
        syn.login()

        # Remove specific file versions from the download list
        download_list_remove([
            DownloadListItem(file_entity_id="syn123", version_number=1),
        ])
        ```

    Arguments:
        list_of_files: Array of files in the format of a mapping {fileEntityId: synid, versionNumber: version}

    Returns:
        Number of files removed from download list
    """
    request_body = {"batchToRemove": list_of_files}
    num_files_removed = self.restPOST(
        "/download/list/remove", body=json.dumps(request_body)
    )
    return num_files_removed

md5Query

md5Query(md5)

Find the Entities which have attached file(s) which have the given MD5 hash.

PARAMETER DESCRIPTION
md5

The MD5 to query for (hexadecimal string)

RETURNS DESCRIPTION

A list of Entity headers

Source code in synapseclient/client.py
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
@deprecated(
    version="4.11.0",
    reason="To be removed in 5.0.0. "
    "Use `from synapseclient.operations import md5_query` instead.",
)
def md5Query(self, md5):
    """
    Find the Entities which have attached file(s) which have the given MD5 hash.

    Arguments:
        md5: The MD5 to query for (hexadecimal string)

    Returns:
        A list of Entity headers
    """

    return self.restGET("/entity/md5/%s" % md5)["results"]

sendMessage

sendMessage(userIds, messageSubject, messageBody, contentType='text/plain')

send a message via Synapse.

PARAMETER DESCRIPTION
userIds

A list of user IDs to which the message is to be sent

messageSubject

The subject for the message

messageBody

The body of the message

contentType

optional contentType of message body (default="text/plain") Should be one of "text/plain" or "text/html"

DEFAULT: 'text/plain'

RETURNS DESCRIPTION

The metadata of the created message

Source code in synapseclient/client.py
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
def sendMessage(
    self, userIds, messageSubject, messageBody, contentType="text/plain"
):
    """
    send a message via Synapse.

    Arguments:
        userIds: A list of user IDs to which the message is to be sent
        messageSubject: The subject for the message
        messageBody: The body of the message
        contentType: optional contentType of message body (default="text/plain")
                        Should be one of "text/plain" or "text/html"

    Returns:
        The metadata of the created message
    """
    return wrap_async_to_sync(
        self.sendMessage_async(
            userIds=userIds,
            messageSubject=messageSubject,
            messageBody=messageBody,
            contentType=contentType,
        )
    )

uploadFileHandle

uploadFileHandle(path, parent, synapseStore=True, mimetype=None, md5=None, file_size=None)

Uploads the file in the provided path (if necessary) to a storage location based on project settings. Returns a new FileHandle as a dict to represent the stored file.

PARAMETER DESCRIPTION
parent

Parent of the entity to which we upload.

path

File path to the file being uploaded

synapseStore

If False, will not upload the file, but instead create an ExternalFileHandle that references the file on the local machine. If True, will upload the file based on StorageLocation determined by the entity_parent_id

DEFAULT: True

mimetype

The MIME type metadata for the uploaded file

DEFAULT: None

md5

The MD5 checksum for the file, if known. Otherwise if the file is a local file, it will be calculated automatically.

DEFAULT: None

file_size

The size the file, if known. Otherwise if the file is a local file, it will be calculated automatically.

DEFAULT: None

file_type

The MIME type the file, if known. Otherwise if the file is a local file, it will be calculated automatically.

RETURNS DESCRIPTION

A dict of a new FileHandle as a dict that represents the uploaded file

Migrating from this method to upload_file_handle_async

Legacy approach (deprecated):

# Using the deprecated uploadFileHandle method
file_handle = syn.uploadFileHandle(
    path="/path/to/file.txt",
    parent="syn12345",
    synapseStore=True,
    mimetype="text/plain"
)

New approach using upload_file_handle:

import asyncio
import synapseclient
from synapseclient.core.upload.upload_functions_async import upload_file_handle

# Create client and login
syn = synapseclient.Synapse()
syn.login()

# Using the new async function directly
async def upload_file():
    file_handle = await upload_file_handle(
        syn=syn,
        parent_entity_id="syn12345",
        path="/path/to/file.txt",
        synapse_store=True,
        md5=None,
        file_size=None,
        mimetype="text/plain"
    )
    return file_handle

# Run the async function
file_handle = asyncio.run(upload_file())
print(f"File handle uploaded: {file_handle}")

Source code in synapseclient/client.py
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
@deprecated(
    version="4.9.0",
    reason="To be removed in 5.0.0. "
    "Moved to synapseclient/core/upload/upload_functions.py::upload_file_handle_async. "
    "Use `upload_file_handle_async` directly instead.",
)
def uploadFileHandle(
    self, path, parent, synapseStore=True, mimetype=None, md5=None, file_size=None
):
    """Uploads the file in the provided path (if necessary) to a storage location based on project settings.
    Returns a new FileHandle as a dict to represent the stored file.

    Arguments:
        parent: Parent of the entity to which we upload.
        path:   File path to the file being uploaded
        synapseStore: If False, will not upload the file, but instead create an ExternalFileHandle that references
                        the file on the local machine.
                        If True, will upload the file based on StorageLocation determined by the entity_parent_id
        mimetype: The MIME type metadata for the uploaded file
        md5: The MD5 checksum for the file, if known. Otherwise if the file is a local file, it will be calculated
                automatically.
        file_size: The size the file, if known. Otherwise if the file is a local file, it will be calculated
                    automatically.
        file_type: The MIME type the file, if known. Otherwise if the file is a local file, it will be calculated
                    automatically.

    Returns:
        A dict of a new FileHandle as a dict that represents the uploaded file

    Example: Migrating from this method to upload_file_handle_async
        **Legacy approach (deprecated):**
        ```python
        # Using the deprecated uploadFileHandle method
        file_handle = syn.uploadFileHandle(
            path="/path/to/file.txt",
            parent="syn12345",
            synapseStore=True,
            mimetype="text/plain"
        )
        ```

        **New approach using upload_file_handle:**
        ```python
        import asyncio
        import synapseclient
        from synapseclient.core.upload.upload_functions_async import upload_file_handle

        # Create client and login
        syn = synapseclient.Synapse()
        syn.login()

        # Using the new async function directly
        async def upload_file():
            file_handle = await upload_file_handle(
                syn=syn,
                parent_entity_id="syn12345",
                path="/path/to/file.txt",
                synapse_store=True,
                md5=None,
                file_size=None,
                mimetype="text/plain"
            )
            return file_handle

        # Run the async function
        file_handle = asyncio.run(upload_file())
        print(f"File handle uploaded: {file_handle}")
        ```
    """
    return wrap_async_to_sync(
        upload_file_handle_async(
            self, parent, path, synapseStore, md5, file_size, mimetype
        )
    )

restGET

restGET(uri, endpoint=None, headers=None, retryPolicy={}, requests_session=None, **kwargs)

Sends an HTTP GET request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

endpoint

Server endpoint, defaults to self.repoEndpoint

DEFAULT: None

headers

Dictionary of headers to use rather than the API-key-signed default set of headers

DEFAULT: None

requests_session

An external requests.Session object to use when making this specific call

DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

RETURNS DESCRIPTION

JSON encoding of response

Source code in synapseclient/client.py
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
def restGET(
    self,
    uri,
    endpoint=None,
    headers=None,
    retryPolicy={},
    requests_session=None,
    **kwargs,
):
    """
    Sends an HTTP GET request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use rather than the API-key-signed default set of headers
        requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
        kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

    Returns:
        JSON encoding of response
    """
    response = self._rest_call(
        "get", uri, None, endpoint, headers, retryPolicy, requests_session, **kwargs
    )
    return self._return_rest_body(response)

restPOST

restPOST(uri, body, endpoint=None, headers=None, retryPolicy={}, requests_session=None, **kwargs)

Sends an HTTP POST request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

endpoint

Server endpoint, defaults to self.repoEndpoint

DEFAULT: None

body

The payload to be delivered

headers

Dictionary of headers to use rather than the API-key-signed default set of headers

DEFAULT: None

requests_session

An external requests.Session object to use when making this specific call

DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

RETURNS DESCRIPTION

JSON encoding of response

Source code in synapseclient/client.py
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
def restPOST(
    self,
    uri,
    body,
    endpoint=None,
    headers=None,
    retryPolicy={},
    requests_session=None,
    **kwargs,
):
    """
    Sends an HTTP POST request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        endpoint: Server endpoint, defaults to self.repoEndpoint
        body: The payload to be delivered
        headers: Dictionary of headers to use rather than the API-key-signed default set of headers
        requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
        kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

    Returns:
        JSON encoding of response
    """
    response = self._rest_call(
        "post",
        uri,
        body,
        endpoint,
        headers,
        retryPolicy,
        requests_session,
        **kwargs,
    )
    return self._return_rest_body(response)

restPUT

restPUT(uri, body=None, endpoint=None, headers=None, retryPolicy={}, requests_session=None, **kwargs)

Sends an HTTP PUT request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

endpoint

Server endpoint, defaults to self.repoEndpoint

DEFAULT: None

body

The payload to be delivered

DEFAULT: None

headers

Dictionary of headers to use rather than the API-key-signed default set of headers

DEFAULT: None

requests_session

An external requests.Session object to use when making this specific call

DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

Returns JSON encoding of response

Source code in synapseclient/client.py
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
def restPUT(
    self,
    uri,
    body=None,
    endpoint=None,
    headers=None,
    retryPolicy={},
    requests_session=None,
    **kwargs,
):
    """
    Sends an HTTP PUT request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        endpoint: Server endpoint, defaults to self.repoEndpoint
        body: The payload to be delivered
        headers: Dictionary of headers to use rather than the API-key-signed default set of headers
        requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
        kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

    Returns
        JSON encoding of response
    """
    response = self._rest_call(
        "put",
        uri,
        body,
        endpoint,
        headers,
        retryPolicy,
        requests_session,
        **kwargs,
    )
    return self._return_rest_body(response)

restDELETE

restDELETE(uri, endpoint=None, headers=None, retryPolicy={}, requests_session=None, **kwargs)

Sends an HTTP DELETE request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI of resource to be deleted

endpoint

Server endpoint, defaults to self.repoEndpoint

DEFAULT: None

headers

Dictionary of headers to use rather than the API-key-signed default set of headers

DEFAULT: None

requests_session

An external requests.Session object to use when making this specific call

DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

Source code in synapseclient/client.py
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
def restDELETE(
    self,
    uri,
    endpoint=None,
    headers=None,
    retryPolicy={},
    requests_session=None,
    **kwargs,
):
    """
    Sends an HTTP DELETE request to the Synapse server.

    Arguments:
        uri: URI of resource to be deleted
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use rather than the API-key-signed default set of headers
        requests_session: An external [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) to use when making this specific call
        kwargs: Any other arguments taken by a [request](http://docs.python-requests.org/en/latest/) method

    """
    self._rest_call(
        "delete",
        uri,
        None,
        endpoint,
        headers,
        retryPolicy,
        requests_session,
        **kwargs,
    )

rest_get_async async

rest_get_async(uri: str, endpoint: str = None, headers: Headers = None, retry_policy: Dict[str, Any] = {}, requests_session_async_synapse: AsyncClient = None, **kwargs) -> Union[Dict[str, Any], str, None]

Sends an HTTP GET request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

TYPE: str

endpoint

Server endpoint, defaults to self.repoEndpoint

TYPE: str DEFAULT: None

headers

Dictionary of headers to use.

TYPE: Headers DEFAULT: None

retry_policy

A retry policy that matches the arguments of synapseclient.core.retry.with_retry_time_based_async.

TYPE: Dict[str, Any] DEFAULT: {}

requests_session_async_synapse

The async client to use when making this specific call.

TYPE: AsyncClient DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

RETURNS DESCRIPTION
Union[Dict[str, Any], str, None]

JSON encoding of response

Source code in synapseclient/client.py
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
async def rest_get_async(
    self,
    uri: str,
    endpoint: str = None,
    headers: httpx.Headers = None,
    retry_policy: Dict[str, Any] = {},
    requests_session_async_synapse: httpx.AsyncClient = None,
    **kwargs,
) -> Union[Dict[str, Any], str, None]:
    """
    Sends an HTTP GET request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use.
        retry_policy: A retry policy that matches the arguments of
            [synapseclient.core.retry.with_retry_time_based_async][].
        requests_session_async_synapse: The async client to use when making this
            specific call.
        kwargs: Any other arguments taken by a
            [request](https://www.python-httpx.org/api/) method

    Returns:
        JSON encoding of response
    """
    response = await self._rest_call_async(
        "get",
        uri,
        None,
        endpoint,
        headers,
        retry_policy,
        requests_session_async_synapse,
        **kwargs,
    )
    return self._return_rest_body(response)

rest_post_async async

rest_post_async(uri: str, body: Any = None, endpoint: str = None, headers: Headers = None, retry_policy: Dict[str, Any] = {}, requests_session_async_synapse: AsyncClient = None, **kwargs) -> Union[Dict[str, Any], str]

Sends an HTTP POST request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

TYPE: str

body

The payload to be delivered

TYPE: Any DEFAULT: None

endpoint

Server endpoint, defaults to self.repoEndpoint

TYPE: str DEFAULT: None

headers

Dictionary of headers to use.

TYPE: Headers DEFAULT: None

retry_policy

A retry policy that matches the arguments of synapseclient.core.retry.with_retry_time_based_async.

TYPE: Dict[str, Any] DEFAULT: {}

requests_session_async_synapse

The async client to use when making this specific call.

TYPE: AsyncClient DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

RETURNS DESCRIPTION
Union[Dict[str, Any], str]

JSON encoding of response

Source code in synapseclient/client.py
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
async def rest_post_async(
    self,
    uri: str,
    body: Any = None,
    endpoint: str = None,
    headers: httpx.Headers = None,
    retry_policy: Dict[str, Any] = {},
    requests_session_async_synapse: httpx.AsyncClient = None,
    **kwargs,
) -> Union[Dict[str, Any], str]:
    """
    Sends an HTTP POST request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        body: The payload to be delivered
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use.
        retry_policy: A retry policy that matches the arguments of
            [synapseclient.core.retry.with_retry_time_based_async][].
        requests_session_async_synapse: The async client to use when making this
            specific call.
        kwargs: Any other arguments taken by a
            [request](https://www.python-httpx.org/api/) method

    Returns:
        JSON encoding of response
    """
    response = await self._rest_call_async(
        "post",
        uri,
        body,
        endpoint,
        headers,
        retry_policy,
        requests_session_async_synapse,
        **kwargs,
    )
    return self._return_rest_body(response)

rest_put_async async

rest_put_async(uri: str, body: Any = None, endpoint: str = None, headers: Headers = None, retry_policy: Dict[str, Any] = {}, requests_session_async_synapse: AsyncClient = None, **kwargs) -> Union[Dict[str, Any], str]

Sends an HTTP PUT request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI on which get is performed

TYPE: str

body

The payload to be delivered.

TYPE: Any DEFAULT: None

endpoint

Server endpoint, defaults to self.repoEndpoint

TYPE: str DEFAULT: None

headers

Dictionary of headers to use.

TYPE: Headers DEFAULT: None

retry_policy

A retry policy that matches the arguments of synapseclient.core.retry.with_retry_time_based_async.

TYPE: Dict[str, Any] DEFAULT: {}

requests_session_async_synapse

The async client to use when making this specific call.

TYPE: AsyncClient DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

Returns JSON encoding of response

Source code in synapseclient/client.py
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
async def rest_put_async(
    self,
    uri: str,
    body: Any = None,
    endpoint: str = None,
    headers: httpx.Headers = None,
    retry_policy: Dict[str, Any] = {},
    requests_session_async_synapse: httpx.AsyncClient = None,
    **kwargs,
) -> Union[Dict[str, Any], str]:
    """
    Sends an HTTP PUT request to the Synapse server.

    Arguments:
        uri: URI on which get is performed
        body: The payload to be delivered.
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use.
        retry_policy: A retry policy that matches the arguments of
            [synapseclient.core.retry.with_retry_time_based_async][].
        requests_session_async_synapse: The async client to use when making this
            specific call.
        kwargs: Any other arguments taken by a
            [request](https://www.python-httpx.org/api/) method

    Returns
        JSON encoding of response
    """
    response = await self._rest_call_async(
        "put",
        uri,
        body,
        endpoint,
        headers,
        retry_policy,
        requests_session_async_synapse,
        **kwargs,
    )
    return self._return_rest_body(response)

rest_delete_async async

rest_delete_async(uri: str, endpoint: str = None, headers: Headers = None, retry_policy: Dict[str, Any] = {}, requests_session_async_synapse: AsyncClient = None, **kwargs) -> None

Sends an HTTP DELETE request to the Synapse server.

PARAMETER DESCRIPTION
uri

URI of resource to be deleted

TYPE: str

endpoint

Server endpoint, defaults to self.repoEndpoint

TYPE: str DEFAULT: None

headers

Dictionary of headers to use.

TYPE: Headers DEFAULT: None

retry_policy

A retry policy that matches the arguments of synapseclient.core.retry.with_retry_time_based_async.

TYPE: Dict[str, Any] DEFAULT: {}

requests_session_async_synapse

The async client to use when making this specific call

TYPE: AsyncClient DEFAULT: None

kwargs

Any other arguments taken by a request method

DEFAULT: {}

Source code in synapseclient/client.py
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
async def rest_delete_async(
    self,
    uri: str,
    endpoint: str = None,
    headers: httpx.Headers = None,
    retry_policy: Dict[str, Any] = {},
    requests_session_async_synapse: httpx.AsyncClient = None,
    **kwargs,
) -> None:
    """
    Sends an HTTP DELETE request to the Synapse server.

    Arguments:
        uri: URI of resource to be deleted
        endpoint: Server endpoint, defaults to self.repoEndpoint
        headers: Dictionary of headers to use.
        retry_policy: A retry policy that matches the arguments of
            [synapseclient.core.retry.with_retry_time_based_async][].
        requests_session_async_synapse: The async client to use when making this
            specific call
        kwargs: Any other arguments taken by a [request](https://www.python-httpx.org/api/) method

    """
    await self._rest_call_async(
        "delete",
        uri,
        None,
        endpoint,
        headers,
        retry_policy,
        requests_session_async_synapse,
        **kwargs,
    )

More information

See also the Synapse API documentation