Skip to content

JSONSchema

Contained within this file are experimental interfaces for working with the Synapse Python Client. Unless otherwise noted these interfaces are subject to change at any time. Use at your own risk.

API Reference

synapseclient.models.JSONSchema dataclass

Bases: JSONSchemaProtocol

Represents a JSON Schema

ATTRIBUTE DESCRIPTION
name

The name of the schema

TYPE: Optional[str]

organization_name

The name of the organization the schema belongs to

TYPE: Optional[str]

organization_id

the id of the organization the schema belongs to

TYPE: Optional[int]

id

The ID of the schema

TYPE: Optional[str]

created_on

The date this schema was created

TYPE: Optional[str]

created_by

The ID of the user that created this schema

TYPE: Optional[str]

uri

The schema identifier in format: -

TYPE: Optional[str]

Source code in synapseclient/models/schema_organization.py
 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
@dataclass()
@async_to_sync
class JSONSchema(JSONSchemaProtocol):
    """
    Represents a [JSON Schema](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/schema/JsonSchemaInfo.html)

    Attributes:
        name: The name of the schema
        organization_name: The name of the organization the schema belongs to
        organization_id: the id of the organization the schema belongs to
        id: The ID of the schema
        created_on: The date this schema was created
        created_by: The ID of the user that created this schema
        uri: The schema identifier in format: <organization_name>-<schema_name>
    """

    name: Optional[str] = None
    """The name of the schema"""

    organization_name: Optional[str] = None
    """The name of the organization the schema belongs to"""

    organization_id: Optional[int] = None
    """The id of the organization the schema belongs to"""

    id: Optional[str] = None
    """The ID of the schema"""

    created_on: Optional[str] = None
    """The date this schema was created"""

    created_by: Optional[str] = None
    """The ID of the user that created this schema"""

    uri: Optional[str] = field(init=False)
    """The schema identifier in format: <organization_name>-<schema_name>"""

    def __post_init__(self) -> None:
        if self.name:
            _check_name(self.name)
        if self.organization_name:
            _check_name(self.organization_name)
        if self.name and self.organization_name:
            self.uri = f"{self.organization_name}-{self.name}"
        else:
            self.uri = None

    async def get_async(
        self, *, synapse_client: Optional["Synapse"] = None
    ) -> "JSONSchema":
        """
        Gets the metadata for this JSONSchema from Synapse

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor

        Raises:
            ValueError: This JSONSchema doesn't have a name
            ValueError: This JSONSchema doesn't have an organization name
            ValueError: This JSONSchema doesn't exist in its organization

        Returns:
            Itself

        Example: Get an existing JSONSchema
            &nbsp;

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def get_schema():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
                await schema.get_async()
                return schema

            schema = asyncio.run(get_schema())
            print(schema.uri)
            ```
        """
        if not self.name:
            raise ValueError("JSONSchema must have a name")
        if not self.organization_name:
            raise ValueError("JSONSchema must have a organization_name")

        # Check that the org exists,
        #  if it doesn't list_json_schemas will unhelpfully return an empty generator.
        org = SchemaOrganization(self.organization_name)
        await org.get_async(synapse_client=synapse_client)

        org_schemas = list_json_schemas(
            self.organization_name, synapse_client=synapse_client
        )
        async for schema in org_schemas:
            if schema["schemaName"] == self.name:
                self.fill_from_dict(schema)
                return self
        raise ValueError(
            (
                f"Organization: '{self.organization_name}' does not contain a schema with "
                f"name: '{self.name}'"
            )
        )

    async def store_async(
        self,
        schema_body: dict[str, Any],
        version: Optional[str] = None,
        dry_run: bool = False,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> "JSONSchema":
        """
        Stores this JSONSchema in Synapse

        Arguments:
            schema_body: The body of the JSONSchema to store
            version: The version of the JSONSchema body to store
            dry_run: Whether or not to do a dry-run
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor

        Returns:
            Itself

        Example: Store a JSON Schema in Synapse
            &nbsp;

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def store_schema():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="my.org", name="test.schema")
                schema_body = {
                    {
                        "properties": {
                            "Component": {
                                "description": "TBD",
                                "not": {
                                    "type": "null"
                                },
                                "title": "Component"
                            }
                        }
                    }
                }
                await schema.store_async(schema_body = schema_body)

            asyncio.run(store_schema())
            ```
        """
        if not self.name:
            raise ValueError("JSONSchema must have a name")
        if not self.organization_name:
            raise ValueError("JSONSchema must have a organization_name")

        client = Synapse.get_client(synapse_client=synapse_client)

        request = CreateSchemaRequest(
            schema=schema_body,
            name=self.name,
            organization_name=self.organization_name,
            version=version,
            dry_run=dry_run,
            synapse_schema_url=f"{client.repoEndpoint}/schema/type/registered/",
        )
        completed_request: CreateSchemaRequest = await request.send_job_and_wait_async(
            synapse_client=synapse_client
        )
        new_version_info = completed_request.new_version_info
        self.organization_id = new_version_info.organization_id
        self.created_by = new_version_info.created_by
        self.created_on = new_version_info.created_on
        return self

    async def delete_async(
        self,
        version: Optional[str] = None,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> None:
        """
        If a version is supplied the specific version is deleted from Synapse.
        Otherwise the entire schema is deleted from Synapse

        Arguments:
            version: Defaults to None.
            - If a version is supplied, that version will be deleted.
            - If no version is supplied the whole schema will be deleted.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor

        Example: Delete an existing JSONSchema

            Delete the whole schema

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def delete_schema():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="my.org", name="test.schema")
                await schema.delete_async()

            asyncio.run(delete_schema())
            ```

            Delete a specific version of the schema

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def delete_schema():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="my.org", name="test.schema")
                await schema.delete_async(version = "0.0.1")

            asyncio.run(delete_schema())
            ```
        """
        if not self.name:
            raise ValueError("JSONSchema must have a name")
        if not self.organization_name:
            raise ValueError("JSONSchema must have a organization_name")

        uri = self.uri
        if version:
            self._check_semantic_version(version)
            uri = f"{uri}-{version}"

        await delete_json_schema(uri, synapse_client=synapse_client)

    @skip_async_to_sync
    async def get_versions_async(
        self, *, synapse_client: Optional["Synapse"] = None
    ) -> AsyncGenerator[JSONSchemaVersionInfo, None]:
        """
        Gets all versions of this JSONSchema

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor

        Returns:
            A generator containing each version of this schema

        Example: Get all the versions of the JSONSchema
            &nbsp;

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def get_versions():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
                version_generator = schema.get_versions_async()
                async for item in version_generator:
                    print(item)

            asyncio.run(get_versions())
            ```
        """
        all_schemas = list_json_schema_versions(
            self.organization_name, self.name, synapse_client=synapse_client
        )
        async for schema in all_schemas:
            # Schema "versions" without a semantic version will be returned from the API call,
            # but will be filtered out by this method.
            # Only those with a semantic version will be returned.
            if "semanticVersion" in schema:
                yield self._create_json_schema_version_from_response(schema)

    async def get_body_async(
        self,
        version: Optional[str] = None,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> dict[str, Any]:
        """
        Gets the body of this JSONSchema

        Arguments:
            version: Defaults to None.
            - If a version is supplied, that versions body will be returned.
            - If no version is supplied the most recent version will be returned.
            synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor

        Returns:
            The JSON Schema body

        Example: Get the body of the JSONSchema

            Get latest version

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def get_body():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
                body = await schema.get_body_async()
                return body

            body = asyncio.run(get_body())
            print(body)
            ```

            Get specific version

            ```python
            from synapseclient.models import JSONSchema
            from synapseclient import Synapse
            import asyncio

            async def get_body():

                syn = Synapse()
                syn.login()

                schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
                body = await schema.get_body_async(version="0.0.1")
                return body

            body = asyncio.run(get_body())
            print(body)
            ```

        """
        if not self.name:
            raise ValueError("JSONSchema must have a name")
        if not self.organization_name:
            raise ValueError("JSONSchema must have a organization_name")

        uri = self.uri
        if version:
            self._check_semantic_version(version)
            uri = f"{uri}-{version}"
        response = await get_json_schema_body(uri, synapse_client=synapse_client)
        return response

    def fill_from_dict(self, response: dict[str, Any]) -> "JSONSchema":
        """
        Fills in this classes attributes using a Synapse API response

        Arguments:
            response: This Synapse API object:
              [JsonSchema](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/schema/JsonSchema.html)

        Returns:
            Itself
        """
        self.organization_id = response.get("organizationId")
        self.organization_name = response.get("organizationName")
        self.id = response.get("schemaId")
        self.name = response.get("schemaName")
        self.created_on = response.get("createdOn")
        self.created_by = response.get("createdBy")
        self.uri = f"{self.organization_name}-{self.name}"
        return self

    @classmethod
    def from_uri(cls, uri: str) -> "JSONSchema":
        """
        Creates a JSONSchema from a URI.
        The URI can either be a semantic version or not
        - non-semantic: ORGANIZATION.NAME-SCHEMA.NAME
        - semantic: ORGANIZATION.NAME-SCHEMA.NAME-MAJOR.MINOR.PATCH

        Arguments:
            uri: The URI to the JSON Schema in Synapse

        Raises:
            ValueError:  If the URI isn't in the correct form.

        Returns:
            A JSONSchema object

        Example: Create a JSONSchema from a URI
            &nbsp;

            ```python
            from synapseclient.models import JSONSchema

            # Non-semantic URI
            js1 = JSONSchema.from_uri("my.org-my.schema")

            # Semantic URI
            js2 = JSONSchema.from_uri("my.org-my.schema-0.0.1")
            ```

        """
        uri_parts = uri.split("-")
        if len(uri_parts) > 3 or len(uri_parts) < 2:
            msg = (
                "The URI must be in the form of "
                "'<ORGANIZATION>-<NAME>' or '<ORGANIZATION>-<NAME>-<VERSION>': "
                f"{uri}"
            )
            raise ValueError(msg)
        return JSONSchema(name=uri_parts[1], organization_name=uri_parts[0])

    @staticmethod
    def _create_json_schema_version_from_response(
        response: dict[str, Any]
    ) -> JSONSchemaVersionInfo:
        """
        Creates a JSONSchemaVersionInfo object from a Synapse API response

        Arguments:
            response: This Synapse API object:
                [JsonSchemaVersionInfo](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/schema/JsonSchemaVersionInfo.html)

        Returns:
            A JSONSchemaVersionInfo object
        """
        return JSONSchemaVersionInfo(
            organization_id=response.get("organizationId"),
            organization_name=response.get("organizationName"),
            schema_id=response.get("schemaId"),
            id=response.get("$id"),
            schema_name=response.get("schemaName"),
            version_id=response.get("versionId"),
            semantic_version=response.get("semanticVersion"),
            json_sha256_hex=response.get("jsonSHA256Hex"),
            created_on=response.get("createdOn"),
            created_by=response.get("createdBy"),
        )

    def _check_semantic_version(self, version: str) -> None:
        """
        Checks that the semantic version is correctly formatted

        Arguments:
            version: A semantic version(ie. `1.0.0`) to be checked

        Raises:
            ValueError: If the string is not a correct semantic version
        """
        if version == "0.0.0":
            raise ValueError("Schema version must start at '0.0.1' or higher")
        if not re.match(r"^(\d+)\.(\d+)\.(\d+)$", version):
            raise ValueError(
                (
                    "Schema version must be a semantic version with no letters "
                    "and a major, minor and patch version, such as 0.0.1: "
                    f"{version}"
                )
            )

Functions

get_async async

get_async(*, synapse_client: Optional[Synapse] = None) -> JSONSchema

Gets the metadata for this JSONSchema from Synapse

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor

TYPE: Optional[Synapse] DEFAULT: None

RAISES DESCRIPTION
ValueError

This JSONSchema doesn't have a name

ValueError

This JSONSchema doesn't have an organization name

ValueError

This JSONSchema doesn't exist in its organization

RETURNS DESCRIPTION
JSONSchema

Itself

Get an existing JSONSchema

 

from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def get_schema():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
    await schema.get_async()
    return schema

schema = asyncio.run(get_schema())
print(schema.uri)
Source code in synapseclient/models/schema_organization.py
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
async def get_async(
    self, *, synapse_client: Optional["Synapse"] = None
) -> "JSONSchema":
    """
    Gets the metadata for this JSONSchema from Synapse

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor

    Raises:
        ValueError: This JSONSchema doesn't have a name
        ValueError: This JSONSchema doesn't have an organization name
        ValueError: This JSONSchema doesn't exist in its organization

    Returns:
        Itself

    Example: Get an existing JSONSchema
        &nbsp;

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def get_schema():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
            await schema.get_async()
            return schema

        schema = asyncio.run(get_schema())
        print(schema.uri)
        ```
    """
    if not self.name:
        raise ValueError("JSONSchema must have a name")
    if not self.organization_name:
        raise ValueError("JSONSchema must have a organization_name")

    # Check that the org exists,
    #  if it doesn't list_json_schemas will unhelpfully return an empty generator.
    org = SchemaOrganization(self.organization_name)
    await org.get_async(synapse_client=synapse_client)

    org_schemas = list_json_schemas(
        self.organization_name, synapse_client=synapse_client
    )
    async for schema in org_schemas:
        if schema["schemaName"] == self.name:
            self.fill_from_dict(schema)
            return self
    raise ValueError(
        (
            f"Organization: '{self.organization_name}' does not contain a schema with "
            f"name: '{self.name}'"
        )
    )

store_async async

store_async(schema_body: dict[str, Any], version: Optional[str] = None, dry_run: bool = False, *, synapse_client: Optional[Synapse] = None) -> JSONSchema

Stores this JSONSchema in Synapse

PARAMETER DESCRIPTION
schema_body

The body of the JSONSchema to store

TYPE: dict[str, Any]

version

The version of the JSONSchema body to store

TYPE: Optional[str] DEFAULT: None

dry_run

Whether or not to do a dry-run

TYPE: bool DEFAULT: False

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
JSONSchema

Itself

Store a JSON Schema in Synapse

 

from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def store_schema():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="my.org", name="test.schema")
    schema_body = {
        {
            "properties": {
                "Component": {
                    "description": "TBD",
                    "not": {
                        "type": "null"
                    },
                    "title": "Component"
                }
            }
        }
    }
    await schema.store_async(schema_body = schema_body)

asyncio.run(store_schema())
Source code in synapseclient/models/schema_organization.py
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
async def store_async(
    self,
    schema_body: dict[str, Any],
    version: Optional[str] = None,
    dry_run: bool = False,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> "JSONSchema":
    """
    Stores this JSONSchema in Synapse

    Arguments:
        schema_body: The body of the JSONSchema to store
        version: The version of the JSONSchema body to store
        dry_run: Whether or not to do a dry-run
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor

    Returns:
        Itself

    Example: Store a JSON Schema in Synapse
        &nbsp;

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def store_schema():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="my.org", name="test.schema")
            schema_body = {
                {
                    "properties": {
                        "Component": {
                            "description": "TBD",
                            "not": {
                                "type": "null"
                            },
                            "title": "Component"
                        }
                    }
                }
            }
            await schema.store_async(schema_body = schema_body)

        asyncio.run(store_schema())
        ```
    """
    if not self.name:
        raise ValueError("JSONSchema must have a name")
    if not self.organization_name:
        raise ValueError("JSONSchema must have a organization_name")

    client = Synapse.get_client(synapse_client=synapse_client)

    request = CreateSchemaRequest(
        schema=schema_body,
        name=self.name,
        organization_name=self.organization_name,
        version=version,
        dry_run=dry_run,
        synapse_schema_url=f"{client.repoEndpoint}/schema/type/registered/",
    )
    completed_request: CreateSchemaRequest = await request.send_job_and_wait_async(
        synapse_client=synapse_client
    )
    new_version_info = completed_request.new_version_info
    self.organization_id = new_version_info.organization_id
    self.created_by = new_version_info.created_by
    self.created_on = new_version_info.created_on
    return self

delete_async async

delete_async(version: Optional[str] = None, *, synapse_client: Optional[Synapse] = None) -> None

If a version is supplied the specific version is deleted from Synapse. Otherwise the entire schema is deleted from Synapse

PARAMETER DESCRIPTION
version

Defaults to None.

TYPE: Optional[str] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor

TYPE: Optional[Synapse] DEFAULT: None

Example: Delete an existing JSONSchema

Delete the whole schema

```python
from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def delete_schema():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="my.org", name="test.schema")
    await schema.delete_async()

asyncio.run(delete_schema())
```

Delete a specific version of the schema

```python
from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def delete_schema():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="my.org", name="test.schema")
    await schema.delete_async(version = "0.0.1")

asyncio.run(delete_schema())
```
Source code in synapseclient/models/schema_organization.py
 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
async def delete_async(
    self,
    version: Optional[str] = None,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> None:
    """
    If a version is supplied the specific version is deleted from Synapse.
    Otherwise the entire schema is deleted from Synapse

    Arguments:
        version: Defaults to None.
        - If a version is supplied, that version will be deleted.
        - If no version is supplied the whole schema will be deleted.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor

    Example: Delete an existing JSONSchema

        Delete the whole schema

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def delete_schema():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="my.org", name="test.schema")
            await schema.delete_async()

        asyncio.run(delete_schema())
        ```

        Delete a specific version of the schema

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def delete_schema():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="my.org", name="test.schema")
            await schema.delete_async(version = "0.0.1")

        asyncio.run(delete_schema())
        ```
    """
    if not self.name:
        raise ValueError("JSONSchema must have a name")
    if not self.organization_name:
        raise ValueError("JSONSchema must have a organization_name")

    uri = self.uri
    if version:
        self._check_semantic_version(version)
        uri = f"{uri}-{version}"

    await delete_json_schema(uri, synapse_client=synapse_client)

get_versions_async async

get_versions_async(*, synapse_client: Optional[Synapse] = None) -> AsyncGenerator[JSONSchemaVersionInfo, None]

Gets all versions of this JSONSchema

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
AsyncGenerator[JSONSchemaVersionInfo, None]

A generator containing each version of this schema

Get all the versions of the JSONSchema

 

from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def get_versions():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
    version_generator = schema.get_versions_async()
    async for item in version_generator:
        print(item)

asyncio.run(get_versions())
Source code in synapseclient/models/schema_organization.py
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
@skip_async_to_sync
async def get_versions_async(
    self, *, synapse_client: Optional["Synapse"] = None
) -> AsyncGenerator[JSONSchemaVersionInfo, None]:
    """
    Gets all versions of this JSONSchema

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor

    Returns:
        A generator containing each version of this schema

    Example: Get all the versions of the JSONSchema
        &nbsp;

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def get_versions():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
            version_generator = schema.get_versions_async()
            async for item in version_generator:
                print(item)

        asyncio.run(get_versions())
        ```
    """
    all_schemas = list_json_schema_versions(
        self.organization_name, self.name, synapse_client=synapse_client
    )
    async for schema in all_schemas:
        # Schema "versions" without a semantic version will be returned from the API call,
        # but will be filtered out by this method.
        # Only those with a semantic version will be returned.
        if "semanticVersion" in schema:
            yield self._create_json_schema_version_from_response(schema)

get_body_async async

get_body_async(version: Optional[str] = None, *, synapse_client: Optional[Synapse] = None) -> dict[str, Any]

Gets the body of this JSONSchema

PARAMETER DESCRIPTION
version

Defaults to None.

TYPE: Optional[str] DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
dict[str, Any]

The JSON Schema body

Example: Get the body of the JSONSchema

Get latest version

```python
from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def get_body():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
    body = await schema.get_body_async()
    return body

body = asyncio.run(get_body())
print(body)
```

Get specific version

```python
from synapseclient.models import JSONSchema
from synapseclient import Synapse
import asyncio

async def get_body():

    syn = Synapse()
    syn.login()

    schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
    body = await schema.get_body_async(version="0.0.1")
    return body

body = asyncio.run(get_body())
print(body)
```
Source code in synapseclient/models/schema_organization.py
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
async def get_body_async(
    self,
    version: Optional[str] = None,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> dict[str, Any]:
    """
    Gets the body of this JSONSchema

    Arguments:
        version: Defaults to None.
        - If a version is supplied, that versions body will be returned.
        - If no version is supplied the most recent version will be returned.
        synapse_client: If not passed in and caching was not disabled by
            `Synapse.allow_client_caching(False)` this will use the last created
            instance from the Synapse class constructor

    Returns:
        The JSON Schema body

    Example: Get the body of the JSONSchema

        Get latest version

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def get_body():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
            body = await schema.get_body_async()
            return body

        body = asyncio.run(get_body())
        print(body)
        ```

        Get specific version

        ```python
        from synapseclient.models import JSONSchema
        from synapseclient import Synapse
        import asyncio

        async def get_body():

            syn = Synapse()
            syn.login()

            schema = JSONSchema(organization_name="dpetest", name="test.schematic.Biospecimen")
            body = await schema.get_body_async(version="0.0.1")
            return body

        body = asyncio.run(get_body())
        print(body)
        ```

    """
    if not self.name:
        raise ValueError("JSONSchema must have a name")
    if not self.organization_name:
        raise ValueError("JSONSchema must have a organization_name")

    uri = self.uri
    if version:
        self._check_semantic_version(version)
        uri = f"{uri}-{version}"
    response = await get_json_schema_body(uri, synapse_client=synapse_client)
    return response

from_uri classmethod

from_uri(uri: str) -> JSONSchema

Creates a JSONSchema from a URI. The URI can either be a semantic version or not - non-semantic: ORGANIZATION.NAME-SCHEMA.NAME - semantic: ORGANIZATION.NAME-SCHEMA.NAME-MAJOR.MINOR.PATCH

PARAMETER DESCRIPTION
uri

The URI to the JSON Schema in Synapse

TYPE: str

RAISES DESCRIPTION
ValueError

If the URI isn't in the correct form.

RETURNS DESCRIPTION
JSONSchema

A JSONSchema object

Create a JSONSchema from a URI

 

from synapseclient.models import JSONSchema

# Non-semantic URI
js1 = JSONSchema.from_uri("my.org-my.schema")

# Semantic URI
js2 = JSONSchema.from_uri("my.org-my.schema-0.0.1")
Source code in synapseclient/models/schema_organization.py
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
@classmethod
def from_uri(cls, uri: str) -> "JSONSchema":
    """
    Creates a JSONSchema from a URI.
    The URI can either be a semantic version or not
    - non-semantic: ORGANIZATION.NAME-SCHEMA.NAME
    - semantic: ORGANIZATION.NAME-SCHEMA.NAME-MAJOR.MINOR.PATCH

    Arguments:
        uri: The URI to the JSON Schema in Synapse

    Raises:
        ValueError:  If the URI isn't in the correct form.

    Returns:
        A JSONSchema object

    Example: Create a JSONSchema from a URI
        &nbsp;

        ```python
        from synapseclient.models import JSONSchema

        # Non-semantic URI
        js1 = JSONSchema.from_uri("my.org-my.schema")

        # Semantic URI
        js2 = JSONSchema.from_uri("my.org-my.schema-0.0.1")
        ```

    """
    uri_parts = uri.split("-")
    if len(uri_parts) > 3 or len(uri_parts) < 2:
        msg = (
            "The URI must be in the form of "
            "'<ORGANIZATION>-<NAME>' or '<ORGANIZATION>-<NAME>-<VERSION>': "
            f"{uri}"
        )
        raise ValueError(msg)
    return JSONSchema(name=uri_parts[1], organization_name=uri_parts[0])